blob: 41cbbf4c988202fe007910b669de381c4c7c7ef7 [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;
Doug Zongker43866e02010-01-07 12:09:54 -080043import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.Handler;
45import android.os.HandlerThread;
46import android.os.IBinder;
47import android.os.IPowerManager;
48import android.os.LocalPowerManager;
49import android.os.Power;
50import android.os.PowerManager;
51import android.os.Process;
52import android.os.RemoteException;
San Mehat14e69af2010-01-06 14:58:18 -080053import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070055import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.provider.Settings.SettingNotFoundException;
57import android.provider.Settings;
58import android.util.EventLog;
59import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080060import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.view.WindowManagerPolicy;
62import static android.provider.Settings.System.DIM_SCREEN;
63import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050064import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070065import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
67import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
Joe Onorato609695d2010-10-14 14:57:49 -070068import static android.provider.Settings.System.WINDOW_ANIMATION_SCALE;
69import static android.provider.Settings.System.TRANSITION_ANIMATION_SCALE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070
71import java.io.FileDescriptor;
Doug Zongker50a21f42009-11-19 12:49:53 -080072import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.io.PrintWriter;
74import java.util.ArrayList;
75import java.util.HashMap;
76import java.util.Observable;
77import java.util.Observer;
78
Mike Lockwoodbc706a02009-07-27 13:50:57 -070079class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040080 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
82 private static final String TAG = "PowerManagerService";
83 static final String PARTIAL_NAME = "PowerManagerService";
84
85 private static final boolean LOG_PARTIAL_WL = false;
86
87 // Indicates whether touch-down cycles should be logged as part of the
88 // LOG_POWER_SCREEN_STATE log events
89 private static final boolean LOG_TOUCH_DOWNS = true;
90
91 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
92 | PowerManager.SCREEN_DIM_WAKE_LOCK
93 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070094 | PowerManager.FULL_WAKE_LOCK
95 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096
97 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -080098 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
100 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
101 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
102 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
103
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700104 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -0500105 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700106
Mike Lockwood20f87d72009-11-05 16:08:51 -0500107 // For debouncing the proximity sensor.
108 private static final int PROXIMITY_SENSOR_DELAY = 1000;
109
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400110 // trigger proximity if distance is less than 5 cm
111 private static final float PROXIMITY_THRESHOLD = 5.0f;
112
Doug Zongker43866e02010-01-07 12:09:54 -0800113 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
115
Amith Yamasani8b619832010-09-22 16:11:59 -0700116 // Default timeout for screen off, if not found in settings database = 15 seconds.
117 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15000;
118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 // flags for setPowerState
120 private static final int SCREEN_ON_BIT = 0x00000001;
121 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
122 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
123 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
124 private static final int BATTERY_LOW_BIT = 0x00000010;
125
126 // values for setPowerState
127
128 // SCREEN_OFF == everything off
129 private static final int SCREEN_OFF = 0x00000000;
130
131 // SCREEN_DIM == screen on, screen backlight dim
132 private static final int SCREEN_DIM = SCREEN_ON_BIT;
133
134 // SCREEN_BRIGHT == screen on, screen backlight bright
135 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
136
137 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
138 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
139
140 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
141 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
142
143 // used for noChangeLights in setPowerState()
144 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
145
Joe Onoratob08a1af2010-10-11 19:28:58 -0700146 boolean mAnimateScreenLights = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400149 // Slower animation for autobrightness changes
150 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
152 // These magic numbers are the initial state of the LEDs at boot. Ideally
153 // we should read them from the driver, but our current hardware returns 0
154 // for the initial value. Oops!
155 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
156 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
157 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private final int MY_UID;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700160 private final int MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
162 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500163 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500165 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
166 private final int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 private int mPartialCount = 0;
168 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500169 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
170 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
171 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 private int mUserState;
173 private boolean mKeyboardVisible = false;
174 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500175 private int mProximityWakeLockCount = 0;
176 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700177 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500178 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
179 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800180 private int mScreenOffTimeoutSetting;
181 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 private int mKeylightDelay;
183 private int mDimDelay;
184 private int mScreenOffDelay;
185 private int mWakeLockState;
186 private long mLastEventTime = 0;
187 private long mScreenOffTime;
188 private volatile WindowManagerPolicy mPolicy;
189 private final LockList mLocks = new LockList();
190 private Intent mScreenOffIntent;
191 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500192 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500194 private LightsService.Light mLcdLight;
195 private LightsService.Light mButtonLight;
196 private LightsService.Light mKeyboardLight;
197 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 private UnsynchronizedWakeLock mBroadcastWakeLock;
199 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
200 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
201 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500202 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 private HandlerThread mHandlerThread;
Joe Onoratob08a1af2010-10-11 19:28:58 -0700204 private HandlerThread mScreenOffThread;
205 private Handler mScreenOffHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500207 private final TimeoutTask mTimeoutTask = new TimeoutTask();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700209 = new BrightnessState(SCREEN_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700210 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 private boolean mIsPowered = false;
212 private IActivityManager mActivityService;
213 private IBatteryStats mBatteryStats;
214 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700215 private SensorManager mSensorManager;
216 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400217 private Sensor mLightSensor;
218 private boolean mLightSensorEnabled;
219 private float mLightSensorValue = -1;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400220 private boolean mProxIgnoredBecauseScreenTurnedOff = false;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500221 private int mHighestLightSensorValue = -1;
Jim Rodovichd102fea2010-09-02 12:30:49 -0500222 private boolean mLightSensorPendingDecrease = false;
223 private boolean mLightSensorPendingIncrease = false;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700224 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500225 private int mLightSensorScreenBrightness = -1;
226 private int mLightSensorButtonBrightness = -1;
227 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500229 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 private long mNextTimeout;
231 private volatile int mPokey = 0;
232 private volatile boolean mPokeAwakeOnSet = false;
233 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500234 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500235 // mLastScreenOnTime is the time the screen was last turned on
236 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 private boolean mPreventScreenOn;
238 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500239 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400240 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700241 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700242 private int[] mAutoBrightnessLevels;
243 private int[] mLcdBacklightValues;
244 private int[] mButtonBacklightValues;
245 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500246 private int mLightSensorWarmupTime;
Joe Onorato6d747652010-10-11 15:15:31 -0700247 boolean mUnplugTurnsOnScreen;
Joe Onorato4b9f62d2010-10-11 13:41:35 -0700248 private int mWarningSpewThrottleCount;
249 private long mWarningSpewThrottleTime;
Joe Onorato609695d2010-10-14 14:57:49 -0700250 private int mAnimationSetting = ANIM_SETTING_OFF;
251
252 // Must match with the ISurfaceComposer constants in C++.
253 private static final int ANIM_SETTING_ON = 0x01;
254 private static final int ANIM_SETTING_OFF = 0x10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255
256 // Used when logging number and duration of touch-down cycles
257 private long mTotalTouchDownTime;
258 private long mLastTouchDown;
259 private int mTouchCycles;
260
261 // could be either static or controllable at runtime
262 private static final boolean mSpew = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400263 private static final boolean mDebugProximitySensor = (false || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400264 private static final boolean mDebugLightSensor = (false || mSpew);
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700265
266 private native void nativeInit();
267 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
Joe Onorato609695d2010-10-14 14:57:49 -0700268 private native void nativeStartSurfaceFlingerAnimation(int mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269
270 /*
271 static PrintStream mLog;
272 static {
273 try {
274 mLog = new PrintStream("/data/power.log");
275 }
276 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800277 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 }
279 }
280 static class Log {
281 static void d(String tag, String s) {
282 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800283 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 }
285 static void i(String tag, String s) {
286 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800287 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 }
289 static void w(String tag, String s) {
290 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800291 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 }
293 static void e(String tag, String s) {
294 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800295 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 }
297 }
298 */
299
300 /**
301 * This class works around a deadlock between the lock in PowerManager.WakeLock
302 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
303 * mToken object so it can be accessed from any thread, but it calls into here
304 * with its lock held. This class is essentially a reimplementation of
305 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
306 * only call it with our own locks held.
307 */
308 private class UnsynchronizedWakeLock {
309 int mFlags;
310 String mTag;
311 IBinder mToken;
312 int mCount = 0;
313 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500314 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315
316 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
317 mFlags = flags;
318 mTag = tag;
319 mToken = new Binder();
320 mRefCounted = refCounted;
321 }
322
323 public void acquire() {
324 if (!mRefCounted || mCount++ == 0) {
325 long ident = Binder.clearCallingIdentity();
326 try {
327 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700328 MY_UID, MY_PID, mTag, null);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500329 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 } finally {
331 Binder.restoreCallingIdentity(ident);
332 }
333 }
334 }
335
336 public void release() {
337 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500338 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500339 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 }
341 if (mCount < 0) {
342 throw new RuntimeException("WakeLock under-locked " + mTag);
343 }
344 }
345
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500346 public boolean isHeld()
347 {
348 return mHeld;
349 }
350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 public String toString() {
352 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500353 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 }
355 }
356
357 private final class BatteryReceiver extends BroadcastReceiver {
358 @Override
359 public void onReceive(Context context, Intent intent) {
360 synchronized (mLocks) {
361 boolean wasPowered = mIsPowered;
362 mIsPowered = mBatteryService.isPowered();
363
364 if (mIsPowered != wasPowered) {
365 // update mStayOnWhilePluggedIn wake lock
366 updateWakeLockLocked();
367
368 // treat plugging and unplugging the devices as a user activity.
369 // users find it disconcerting when they unplug the device
370 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500371 // to avoid turning on the screen when unplugging, we only trigger
372 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 // temporarily set mUserActivityAllowed to true so this will work
374 // even when the keyguard is on.
Joe Onorato6d747652010-10-11 15:15:31 -0700375 // However, you can also set config_unplugTurnsOnScreen to have it
376 // turn on. Some devices want this because they don't have a
377 // charging LED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 synchronized (mLocks) {
Joe Onorato6d747652010-10-11 15:15:31 -0700379 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0 ||
380 mUnplugTurnsOnScreen) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500381 forceUserActivityLocked();
382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 }
384 }
385 }
386 }
387 }
388
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500389 private final class BootCompletedReceiver extends BroadcastReceiver {
390 @Override
391 public void onReceive(Context context, Intent intent) {
392 bootCompleted();
393 }
394 }
395
Mike Lockwoodb2865412010-02-02 22:40:33 -0500396 private final class DockReceiver extends BroadcastReceiver {
397 @Override
398 public void onReceive(Context context, Intent intent) {
399 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
400 Intent.EXTRA_DOCK_STATE_UNDOCKED);
401 dockStateChanged(state);
402 }
403 }
404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 /**
406 * Set the setting that determines whether the device stays on when plugged in.
407 * The argument is a bit string, with each bit specifying a power source that,
408 * when the device is connected to that source, causes the device to stay on.
409 * See {@link android.os.BatteryManager} for the list of power sources that
410 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
411 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
412 * @param val an {@code int} containing the bits that specify which power sources
413 * should cause the device to stay on.
414 */
415 public void setStayOnSetting(int val) {
416 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
417 Settings.System.putInt(mContext.getContentResolver(),
418 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
419 }
420
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800421 public void setMaximumScreenOffTimeount(int timeMs) {
422 mContext.enforceCallingOrSelfPermission(
423 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
424 synchronized (mLocks) {
425 mMaximumScreenOffTimeout = timeMs;
426 // recalculate everything
427 setScreenOffTimeoutsLocked();
428 }
429 }
430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 private class SettingsObserver implements Observer {
Amith Yamasani8b619832010-09-22 16:11:59 -0700432 private int getInt(String name, int defValue) {
433 ContentValues values = mSettings.getValues(name);
434 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null;
435 return iVal != null ? iVal : defValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 }
437
Joe Onorato609695d2010-10-14 14:57:49 -0700438 private float getFloat(String name, float defValue) {
439 ContentValues values = mSettings.getValues(name);
440 Float fVal = values != null ? values.getAsFloat(Settings.System.VALUE) : null;
441 return fVal != null ? fVal : defValue;
442 }
443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 public void update(Observable o, Object arg) {
445 synchronized (mLocks) {
Amith Yamasani8b619832010-09-22 16:11:59 -0700446 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC
447 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN,
448 BatteryManager.BATTERY_PLUGGED_AC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 updateWakeLockLocked();
450
Amith Yamasani8b619832010-09-22 16:11:59 -0700451 // SCREEN_OFF_TIMEOUT, default to 15 seconds
452 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453
Joe Onorato609695d2010-10-14 14:57:49 -0700454 // DIM_SCREEN
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 //mDimScreen = getInt(DIM_SCREEN) != 0;
456
Amith Yamasani8b619832010-09-22 16:11:59 -0700457 // SCREEN_BRIGHTNESS_MODE, default to manual
458 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE,
459 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL));
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 // recalculate everything
462 setScreenOffTimeoutsLocked();
Joe Onorato609695d2010-10-14 14:57:49 -0700463
464 final float windowScale = getFloat(WINDOW_ANIMATION_SCALE, 1.0f);
465 final float transitionScale = getFloat(TRANSITION_ANIMATION_SCALE, 1.0f);
466 mAnimationSetting = 0;
467 if (windowScale > 0.5f) {
468 mAnimationSetting |= ANIM_SETTING_OFF;
469 }
470 if (transitionScale > 0.5f) {
471 // Uncomment this if you want the screen-on animation.
472 // mAnimationSetting |= ANIM_SETTING_ON;
473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 }
475 }
476 }
477
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700478 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 // Hack to get our uid... should have a func for this.
480 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700481 MY_UID = Process.myUid();
482 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 Binder.restoreCallingIdentity(token);
484
485 // XXX remove this when the kernel doesn't timeout wake locks
486 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
487
488 // assume nothing is on yet
489 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 // Add ourself to the Watchdog monitors.
492 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 }
494
495 private ContentQueryMap mSettings;
496
Mike Lockwood3a322132009-11-24 00:30:52 -0500497 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700498 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500499 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 mContext = context;
501 mActivityService = activity;
502 mBatteryStats = BatteryStatsService.getService();
503 mBatteryService = battery;
504
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500505 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
506 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
507 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
508 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
509
Joe Onoratob08a1af2010-10-11 19:28:58 -0700510 nativeInit();
511 synchronized (mLocks) {
512 updateNativePowerStateLocked();
513 }
514
515 mInitComplete = false;
516 mScreenOffThread = new HandlerThread("PowerManagerService.mScreenOffThread") {
517 @Override
518 protected void onLooperPrepared() {
519 mScreenOffHandler = new Handler();
520 synchronized (mScreenOffThread) {
521 mInitComplete = true;
522 mScreenOffThread.notifyAll();
523 }
524 }
525 };
526 mScreenOffThread.start();
527
528 synchronized (mScreenOffThread) {
529 while (!mInitComplete) {
530 try {
531 mScreenOffThread.wait();
532 } catch (InterruptedException e) {
533 // Ignore
534 }
535 }
536 }
537
538 mInitComplete = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 mHandlerThread = new HandlerThread("PowerManagerService") {
540 @Override
541 protected void onLooperPrepared() {
542 super.onLooperPrepared();
543 initInThread();
544 }
545 };
546 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 synchronized (mHandlerThread) {
549 while (!mInitComplete) {
550 try {
551 mHandlerThread.wait();
552 } catch (InterruptedException e) {
553 // Ignore
554 }
555 }
556 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700557
558 nativeInit();
559 synchronized (mLocks) {
560 updateNativePowerStateLocked();
561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 void initInThread() {
565 mHandler = new Handler();
566
567 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700568 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
570 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
571 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
572 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
573 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
574 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500575 mProximityPartialLock = new UnsynchronizedWakeLock(
576 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577
578 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
579 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
580 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
581 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
582
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700583 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400584
Joe Onoratob08a1af2010-10-11 19:28:58 -0700585 mAnimateScreenLights = resources.getBoolean(
586 com.android.internal.R.bool.config_animateScreenLights);
587
Joe Onorato6d747652010-10-11 15:15:31 -0700588 mUnplugTurnsOnScreen = resources.getBoolean(
589 com.android.internal.R.bool.config_unplugTurnsOnScreen);
590
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400591 // read settings for auto-brightness
592 mUseSoftwareAutoBrightness = resources.getBoolean(
593 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400594 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700595 mAutoBrightnessLevels = resources.getIntArray(
596 com.android.internal.R.array.config_autoBrightnessLevels);
597 mLcdBacklightValues = resources.getIntArray(
598 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
599 mButtonBacklightValues = resources.getIntArray(
600 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
601 mKeyboardBacklightValues = resources.getIntArray(
602 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500603 mLightSensorWarmupTime = resources.getInteger(
604 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700605 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700606
607 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
609 "(" + Settings.System.NAME + "=?) or ("
610 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700611 + Settings.System.NAME + "=?) or ("
Joe Onorato609695d2010-10-14 14:57:49 -0700612 + Settings.System.NAME + "=?) or ("
613 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700615 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
Joe Onorato609695d2010-10-14 14:57:49 -0700616 SCREEN_BRIGHTNESS_MODE, WINDOW_ANIMATION_SCALE, TRANSITION_ANIMATION_SCALE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 null);
618 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
619 SettingsObserver settingsObserver = new SettingsObserver();
620 mSettings.addObserver(settingsObserver);
621
622 // pretend that the settings changed so we will get their initial state
623 settingsObserver.update(mSettings, null);
624
625 // register for the battery changed notifications
626 IntentFilter filter = new IntentFilter();
627 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
628 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500629 filter = new IntentFilter();
630 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
631 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500632 filter = new IntentFilter();
633 filter.addAction(Intent.ACTION_DOCK_EVENT);
634 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635
Doug Zongker43866e02010-01-07 12:09:54 -0800636 // Listen for secure settings changes
637 mContext.getContentResolver().registerContentObserver(
638 Settings.Secure.CONTENT_URI, true,
639 new ContentObserver(new Handler()) {
640 public void onChange(boolean selfChange) {
641 updateSettingsValues();
642 }
643 });
644 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 synchronized (mHandlerThread) {
647 mInitComplete = true;
648 mHandlerThread.notifyAll();
649 }
650 }
651
652 private class WakeLock implements IBinder.DeathRecipient
653 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700654 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 super();
656 flags = f;
657 binder = b;
658 tag = t;
659 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700660 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 if (u != MY_UID || (
662 !"KEEP_SCREEN_ON_FLAG".equals(tag)
663 && !"KeyInputQueue".equals(tag))) {
664 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
665 ? BatteryStats.WAKE_TYPE_PARTIAL
666 : BatteryStats.WAKE_TYPE_FULL;
667 } else {
668 monitorType = -1;
669 }
670 try {
671 b.linkToDeath(this, 0);
672 } catch (RemoteException e) {
673 binderDied();
674 }
675 }
676 public void binderDied() {
677 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500678 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 }
680 }
681 final int flags;
682 final IBinder binder;
683 final String tag;
684 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400685 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700687 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 boolean activated = true;
689 int minState;
690 }
691
692 private void updateWakeLockLocked() {
693 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
694 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
695 mStayOnWhilePluggedInScreenDimLock.acquire();
696 mStayOnWhilePluggedInPartialLock.acquire();
697 } else {
698 mStayOnWhilePluggedInScreenDimLock.release();
699 mStayOnWhilePluggedInPartialLock.release();
700 }
701 }
702
703 private boolean isScreenLock(int flags)
704 {
705 int n = flags & LOCK_MASK;
706 return n == PowerManager.FULL_WAKE_LOCK
707 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400708 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
709 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 }
711
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700712 void enforceWakeSourcePermission(int uid, int pid) {
713 if (uid == Process.myUid()) {
714 return;
715 }
716 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
717 pid, uid, null);
718 }
719
720 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700722 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700723 if (uid != Process.myUid()) {
724 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
725 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700726 if (ws != null) {
727 enforceWakeSourcePermission(uid, pid);
728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 long ident = Binder.clearCallingIdentity();
730 try {
731 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700732 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 }
734 } finally {
735 Binder.restoreCallingIdentity(ident);
736 }
737 }
738
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700739 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700740 if (wl.monitorType >= 0) {
741 long origId = Binder.clearCallingIdentity();
742 try {
743 if (ws != null) {
744 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
745 wl.monitorType);
746 } else {
747 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
748 }
749 } catch (RemoteException e) {
750 // Ignore
751 } finally {
752 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700753 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700754 }
755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700757 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700758 if (wl.monitorType >= 0) {
759 long origId = Binder.clearCallingIdentity();
760 try {
761 if (ws != null) {
762 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
763 wl.monitorType);
764 } else {
765 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
766 }
767 } catch (RemoteException e) {
768 // Ignore
769 } finally {
770 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700771 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700772 }
773 }
774
775 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
776 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800778 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 }
780
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700781 if (ws != null && ws.size() == 0) {
782 ws = null;
783 }
784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 int index = mLocks.getIndex(lock);
786 WakeLock wl;
787 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700788 boolean diffsource;
789 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700791 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 switch (wl.flags & LOCK_MASK)
793 {
794 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500795 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400796 wl.minState = SCREEN_BRIGHT;
797 } else {
798 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 break;
801 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
802 wl.minState = SCREEN_BRIGHT;
803 break;
804 case PowerManager.SCREEN_DIM_WAKE_LOCK:
805 wl.minState = SCREEN_DIM;
806 break;
807 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700808 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 break;
810 default:
811 // just log and bail. we're in the server, so don't
812 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800813 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 + " flags=" + flags);
815 return;
816 }
817 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700818 if (ws != null) {
819 wl.ws = new WorkSource(ws);
820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700822 diffsource = false;
823 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 } else {
825 wl = mLocks.get(index);
826 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700827 oldsource = wl.ws;
828 if (oldsource != null) {
829 if (ws == null) {
830 wl.ws = null;
831 diffsource = true;
832 } else {
833 diffsource = oldsource.diff(ws);
834 }
835 } else if (ws != null) {
836 diffsource = true;
837 } else {
838 diffsource = false;
839 }
840 if (diffsource) {
841 wl.ws = new WorkSource(ws);
842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 }
844 if (isScreenLock(flags)) {
845 // if this causes a wakeup, we reactivate all of the locks and
846 // set it to whatever they want. otherwise, we modulate that
847 // by the current state so we never turn it more on than
848 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400849 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
850 mProximityWakeLockCount++;
851 if (mProximityWakeLockCount == 1) {
852 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400855 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
856 int oldWakeLockState = mWakeLockState;
857 mWakeLockState = mLocks.reactivateScreenLocksLocked();
858 if (mSpew) {
859 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
860 + " mWakeLockState=0x"
861 + Integer.toHexString(mWakeLockState)
862 + " previous wakeLockState=0x"
863 + Integer.toHexString(oldWakeLockState));
864 }
865 } else {
866 if (mSpew) {
867 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
868 + " mLocks.gatherState()=0x"
869 + Integer.toHexString(mLocks.gatherState())
870 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
871 }
872 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400874 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 }
877 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
878 if (newlock) {
879 mPartialCount++;
880 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800881 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 }
883 }
884 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700887 if (diffsource) {
888 // If the lock sources have changed, need to first release the
889 // old ones.
890 noteStopWakeLocked(wl, oldsource);
891 }
892 if (newlock || diffsource) {
893 noteStartWakeLocked(wl, ws);
894 }
895 }
896
897 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
898 int uid = Binder.getCallingUid();
899 int pid = Binder.getCallingPid();
900 if (ws != null && ws.size() == 0) {
901 ws = null;
902 }
903 if (ws != null) {
904 enforceWakeSourcePermission(uid, pid);
905 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700906 synchronized (mLocks) {
907 int index = mLocks.getIndex(lock);
908 if (index < 0) {
909 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700911 WakeLock wl = mLocks.get(index);
912 WorkSource oldsource = wl.ws;
913 wl.ws = ws != null ? new WorkSource(ws) : null;
914 noteStopWakeLocked(wl, oldsource);
915 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
917 }
918
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500919 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700920 int uid = Binder.getCallingUid();
921 if (uid != Process.myUid()) {
922 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924
925 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500926 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 }
928 }
929
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500930 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 WakeLock wl = mLocks.removeLock(lock);
932 if (wl == null) {
933 return;
934 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800937 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
939 }
940
941 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400942 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
943 mProximityWakeLockCount--;
944 if (mProximityWakeLockCount == 0) {
945 if (mProximitySensorActive &&
946 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
947 // wait for proximity sensor to go negative before disabling sensor
948 if (mDebugProximitySensor) {
949 Slog.d(TAG, "waiting for proximity sensor to go negative");
950 }
951 } else {
952 disableProximityLockLocked();
953 }
954 }
955 } else {
956 mWakeLockState = mLocks.gatherState();
957 // goes in the middle to reduce flicker
958 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
959 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
960 }
961 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 }
964 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
965 mPartialCount--;
966 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800967 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 Power.releaseWakeLock(PARTIAL_NAME);
969 }
970 }
971 // Unlink the lock from the binder.
972 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973
Dianne Hackborn70be1672010-09-14 11:13:03 -0700974 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 private class PokeLock implements IBinder.DeathRecipient
978 {
979 PokeLock(int p, IBinder b, String t) {
980 super();
981 this.pokey = p;
982 this.binder = b;
983 this.tag = t;
984 try {
985 b.linkToDeath(this, 0);
986 } catch (RemoteException e) {
987 binderDied();
988 }
989 }
990 public void binderDied() {
991 setPokeLock(0, this.binder, this.tag);
992 }
993 int pokey;
994 IBinder binder;
995 String tag;
996 boolean awakeOnSet;
997 }
998
999 public void setPokeLock(int pokey, IBinder token, String tag) {
1000 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1001 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001002 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 return;
1004 }
1005
1006 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
1007 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
1008 + " and POKE_LOCK_MEDIUM_TIMEOUT");
1009 }
1010
1011 synchronized (mLocks) {
1012 if (pokey != 0) {
1013 PokeLock p = mPokeLocks.get(token);
1014 int oldPokey = 0;
1015 if (p != null) {
1016 oldPokey = p.pokey;
1017 p.pokey = pokey;
1018 } else {
1019 p = new PokeLock(pokey, token, tag);
1020 mPokeLocks.put(token, p);
1021 }
1022 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1023 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
1024 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
1025 p.awakeOnSet = true;
1026 }
1027 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001028 PokeLock rLock = mPokeLocks.remove(token);
1029 if (rLock != null) {
1030 token.unlinkToDeath(rLock, 0);
1031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 }
1033
1034 int oldPokey = mPokey;
1035 int cumulative = 0;
1036 boolean oldAwakeOnSet = mPokeAwakeOnSet;
1037 boolean awakeOnSet = false;
1038 for (PokeLock p: mPokeLocks.values()) {
1039 cumulative |= p.pokey;
1040 if (p.awakeOnSet) {
1041 awakeOnSet = true;
1042 }
1043 }
1044 mPokey = cumulative;
1045 mPokeAwakeOnSet = awakeOnSet;
1046
1047 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1048 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 if (oldCumulativeTimeout != newCumulativeTimeout) {
1051 setScreenOffTimeoutsLocked();
1052 // reset the countdown timer, but use the existing nextState so it doesn't
1053 // change anything
1054 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
1055 }
1056 }
1057 }
1058
1059 private static String lockType(int type)
1060 {
1061 switch (type)
1062 {
1063 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001064 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001066 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001068 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001070 return "PARTIAL_WAKE_LOCK ";
1071 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1072 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 default:
David Brown251faa62009-08-02 22:04:36 -07001074 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 }
1076 }
1077
1078 private static String dumpPowerState(int state) {
1079 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1080 ? "KEYBOARD_BRIGHT_BIT " : "")
1081 + (((state & SCREEN_BRIGHT_BIT) != 0)
1082 ? "SCREEN_BRIGHT_BIT " : "")
1083 + (((state & SCREEN_ON_BIT) != 0)
1084 ? "SCREEN_ON_BIT " : "")
1085 + (((state & BATTERY_LOW_BIT) != 0)
1086 ? "BATTERY_LOW_BIT " : "");
1087 }
1088
1089 @Override
1090 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1091 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1092 != PackageManager.PERMISSION_GRANTED) {
1093 pw.println("Permission Denial: can't dump PowerManager from from pid="
1094 + Binder.getCallingPid()
1095 + ", uid=" + Binder.getCallingUid());
1096 return;
1097 }
1098
1099 long now = SystemClock.uptimeMillis();
1100
Mike Lockwoodca44df82010-02-25 13:48:49 -05001101 synchronized (mLocks) {
1102 pw.println("Power Manager State:");
1103 pw.println(" mIsPowered=" + mIsPowered
1104 + " mPowerState=" + mPowerState
1105 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1106 + " ms");
1107 pw.println(" mPartialCount=" + mPartialCount);
1108 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1109 pw.println(" mUserState=" + dumpPowerState(mUserState));
1110 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1111 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1112 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1113 + " " + ((mNextTimeout-now)/1000) + "s from now");
1114 pw.println(" mDimScreen=" + mDimScreen
1115 + " mStayOnConditions=" + mStayOnConditions);
1116 pw.println(" mScreenOffReason=" + mScreenOffReason
1117 + " mUserState=" + mUserState);
1118 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1119 + ',' + mBroadcastQueue[2] + "}");
1120 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1121 + ',' + mBroadcastWhy[2] + "}");
1122 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1123 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1124 + " mUserActivityAllowed=" + mUserActivityAllowed);
1125 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1126 + " mScreenOffDelay=" + mScreenOffDelay);
1127 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1128 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1129 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1130 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1131 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1132 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1133 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1134 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1135 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1136 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1137 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1138 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1139 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1140 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1141 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1142 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
1143 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
1144 pw.println(" mLightSensorValue=" + mLightSensorValue
1145 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001146 pw.println(" mLightSensorPendingDecrease=" + mLightSensorPendingDecrease
1147 + " mLightSensorPendingIncrease=" + mLightSensorPendingIncrease);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001148 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1149 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1150 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1151 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1152 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
1153 mScreenBrightness.dump(pw, " mScreenBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001154
Mike Lockwoodca44df82010-02-25 13:48:49 -05001155 int N = mLocks.size();
1156 pw.println();
1157 pw.println("mLocks.size=" + N + ":");
1158 for (int i=0; i<N; i++) {
1159 WakeLock wl = mLocks.get(i);
1160 String type = lockType(wl.flags & LOCK_MASK);
1161 String acquireCausesWakeup = "";
1162 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1163 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1164 }
1165 String activated = "";
1166 if (wl.activated) {
1167 activated = " activated";
1168 }
1169 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001170 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1171 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001173
1174 pw.println();
1175 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1176 for (PokeLock p: mPokeLocks.values()) {
1177 pw.println(" poke lock '" + p.tag + "':"
1178 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
1179 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
1180 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
1181 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
1182 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1183 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1184 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1185 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001187
Mike Lockwoodca44df82010-02-25 13:48:49 -05001188 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 }
1191
Joe Onorato7999bff2010-07-24 11:50:05 -04001192 private void setTimeoutLocked(long now, int nextState) {
1193 setTimeoutLocked(now, -1, nextState);
1194 }
1195
1196 // If they gave a timeoutOverride it is the number of seconds
1197 // to screen-off. Figure out where in the countdown cycle we
1198 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001199 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1200 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001201 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001202 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001203 long when = 0;
1204 if (timeoutOverride <= 0) {
1205 switch (nextState)
1206 {
1207 case SCREEN_BRIGHT:
1208 when = now + mKeylightDelay;
1209 break;
1210 case SCREEN_DIM:
1211 if (mDimDelay >= 0) {
1212 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001213 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001214 } else {
1215 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1216 }
1217 case SCREEN_OFF:
1218 synchronized (mLocks) {
1219 when = now + mScreenOffDelay;
1220 }
1221 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001222 default:
1223 when = now;
1224 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001226 } else {
1227 override: {
1228 if (timeoutOverride <= mScreenOffDelay) {
1229 when = now + timeoutOverride;
1230 nextState = SCREEN_OFF;
1231 break override;
1232 }
1233 timeoutOverride -= mScreenOffDelay;
1234
1235 if (mDimDelay >= 0) {
1236 if (timeoutOverride <= mDimDelay) {
1237 when = now + timeoutOverride;
1238 nextState = SCREEN_DIM;
1239 break override;
1240 }
1241 timeoutOverride -= mDimDelay;
1242 }
1243
1244 when = now + timeoutOverride;
1245 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001247 }
1248 if (mSpew) {
1249 Slog.d(TAG, "setTimeoutLocked now=" + now
1250 + " timeoutOverride=" + timeoutOverride
1251 + " nextState=" + nextState + " when=" + when);
1252 }
Joe Onorato797e6882010-08-26 14:46:01 -04001253
1254 mHandler.removeCallbacks(mTimeoutTask);
1255 mTimeoutTask.nextState = nextState;
1256 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1257 ? (originalTimeoutOverride - timeoutOverride)
1258 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001259 mHandler.postAtTime(mTimeoutTask, when);
1260 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 }
1263 }
1264
1265 private void cancelTimerLocked()
1266 {
1267 mHandler.removeCallbacks(mTimeoutTask);
1268 mTimeoutTask.nextState = -1;
1269 }
1270
1271 private class TimeoutTask implements Runnable
1272 {
1273 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001274 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 public void run()
1276 {
1277 synchronized (mLocks) {
1278 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001279 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 }
1281
1282 if (nextState == -1) {
1283 return;
1284 }
1285
1286 mUserState = this.nextState;
1287 setPowerState(this.nextState | mWakeLockState);
1288
1289 long now = SystemClock.uptimeMillis();
1290
1291 switch (this.nextState)
1292 {
1293 case SCREEN_BRIGHT:
1294 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001295 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 break;
1297 }
1298 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001299 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 break;
1301 }
1302 }
1303 }
1304 }
1305
1306 private void sendNotificationLocked(boolean on, int why)
1307 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001308 if (!on) {
1309 mStillNeedSleepNotification = false;
1310 }
1311
Joe Onorato128e7292009-03-24 18:41:31 -07001312 // Add to the queue.
1313 int index = 0;
1314 while (mBroadcastQueue[index] != -1) {
1315 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 }
Joe Onorato128e7292009-03-24 18:41:31 -07001317 mBroadcastQueue[index] = on ? 1 : 0;
1318 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319
Joe Onorato128e7292009-03-24 18:41:31 -07001320 // If we added it position 2, then there is a pair that can be stripped.
1321 // If we added it position 1 and we're turning the screen off, we can strip
1322 // the pair and do nothing, because the screen is already off, and therefore
1323 // keyguard has already been enabled.
1324 // However, if we added it at position 1 and we're turning it on, then position
1325 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1326 // on, so have to run the queue then.
1327 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001328 // While we're collapsing them, if it's going off, and the new reason
1329 // is more significant than the first, then use the new one.
1330 if (!on && mBroadcastWhy[0] > why) {
1331 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001332 }
1333 mBroadcastQueue[0] = on ? 1 : 0;
1334 mBroadcastQueue[1] = -1;
1335 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001336 mBroadcastWakeLock.release();
1337 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001338 index = 0;
1339 }
1340 if (index == 1 && !on) {
1341 mBroadcastQueue[0] = -1;
1342 mBroadcastQueue[1] = -1;
1343 index = -1;
1344 // The wake lock was being held, but we're not actually going to do any
1345 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001346 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001348 }
1349
1350 // Now send the message.
1351 if (index >= 0) {
1352 // Acquire the broadcast wake lock before changing the power
1353 // state. It will be release after the broadcast is sent.
1354 // We always increment the ref count for each notification in the queue
1355 // and always decrement when that notification is handled.
1356 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001357 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001358 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 }
1360 }
1361
1362 private Runnable mNotificationTask = new Runnable()
1363 {
1364 public void run()
1365 {
Joe Onorato128e7292009-03-24 18:41:31 -07001366 while (true) {
1367 int value;
1368 int why;
1369 WindowManagerPolicy policy;
1370 synchronized (mLocks) {
1371 value = mBroadcastQueue[0];
1372 why = mBroadcastWhy[0];
1373 for (int i=0; i<2; i++) {
1374 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1375 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1376 }
1377 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 }
Joe Onorato128e7292009-03-24 18:41:31 -07001379 if (value == 1) {
1380 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001381
Joe Onorato128e7292009-03-24 18:41:31 -07001382 policy.screenTurnedOn();
1383 try {
1384 ActivityManagerNative.getDefault().wakingUp();
1385 } catch (RemoteException e) {
1386 // ignore it
1387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388
Joe Onorato128e7292009-03-24 18:41:31 -07001389 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001390 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001391 }
1392 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1393 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1394 mScreenOnBroadcastDone, mHandler, 0, null, null);
1395 } else {
1396 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001397 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001398 mBroadcastWakeLock.mCount);
1399 mBroadcastWakeLock.release();
1400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 }
1402 }
Joe Onorato128e7292009-03-24 18:41:31 -07001403 else if (value == 0) {
1404 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001405
Joe Onorato128e7292009-03-24 18:41:31 -07001406 policy.screenTurnedOff(why);
1407 try {
1408 ActivityManagerNative.getDefault().goingToSleep();
1409 } catch (RemoteException e) {
1410 // ignore it.
1411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412
Joe Onorato128e7292009-03-24 18:41:31 -07001413 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1414 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1415 mScreenOffBroadcastDone, mHandler, 0, null, null);
1416 } else {
1417 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001418 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001419 mBroadcastWakeLock.mCount);
1420 mBroadcastWakeLock.release();
1421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 }
1423 }
Joe Onorato128e7292009-03-24 18:41:31 -07001424 else {
1425 // If we're in this case, then this handler is running for a previous
1426 // paired transaction. mBroadcastWakeLock will already have been released.
1427 break;
1428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 }
1430 }
1431 };
1432
1433 long mScreenOnStart;
1434 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1435 public void onReceive(Context context, Intent intent) {
1436 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001437 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1439 mBroadcastWakeLock.release();
1440 }
1441 }
1442 };
1443
1444 long mScreenOffStart;
1445 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1446 public void onReceive(Context context, Intent intent) {
1447 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001448 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1450 mBroadcastWakeLock.release();
1451 }
1452 }
1453 };
1454
1455 void logPointerUpEvent() {
1456 if (LOG_TOUCH_DOWNS) {
1457 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1458 mLastTouchDown = 0;
1459 }
1460 }
1461
1462 void logPointerDownEvent() {
1463 if (LOG_TOUCH_DOWNS) {
1464 // If we are not already timing a down/up sequence
1465 if (mLastTouchDown == 0) {
1466 mLastTouchDown = SystemClock.elapsedRealtime();
1467 mTouchCycles++;
1468 }
1469 }
1470 }
1471
1472 /**
1473 * Prevents the screen from turning on even if it *should* turn on due
1474 * to a subsequent full wake lock being acquired.
1475 * <p>
1476 * This is a temporary hack that allows an activity to "cover up" any
1477 * display glitches that happen during the activity's startup
1478 * sequence. (Specifically, this API was added to work around a
1479 * cosmetic bug in the "incoming call" sequence, where the lock screen
1480 * would flicker briefly before the incoming call UI became visible.)
1481 * TODO: There ought to be a more elegant way of doing this,
1482 * probably by having the PowerManager and ActivityManager
1483 * work together to let apps specify that the screen on/off
1484 * state should be synchronized with the Activity lifecycle.
1485 * <p>
1486 * Note that calling preventScreenOn(true) will NOT turn the screen
1487 * off if it's currently on. (This API only affects *future*
1488 * acquisitions of full wake locks.)
1489 * But calling preventScreenOn(false) WILL turn the screen on if
1490 * it's currently off because of a prior preventScreenOn(true) call.
1491 * <p>
1492 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1493 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1494 * call doesn't occur within 5 seconds, we'll turn the screen back on
1495 * ourselves (and log a warning about it); this prevents a buggy app
1496 * from disabling the screen forever.)
1497 * <p>
1498 * TODO: this feature should really be controlled by a new type of poke
1499 * lock (rather than an IPowerManager call).
1500 */
1501 public void preventScreenOn(boolean prevent) {
1502 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1503
1504 synchronized (mLocks) {
1505 if (prevent) {
1506 // First of all, grab a partial wake lock to
1507 // make sure the CPU stays on during the entire
1508 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1509 mPreventScreenOnPartialLock.acquire();
1510
1511 // Post a forceReenableScreen() call (for 5 seconds in the
1512 // future) to make sure the matching preventScreenOn(false) call
1513 // has happened by then.
1514 mHandler.removeCallbacks(mForceReenableScreenTask);
1515 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1516
1517 // Finally, set the flag that prevents the screen from turning on.
1518 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001519 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 mPreventScreenOn = true;
1521 } else {
1522 // (Re)enable the screen.
1523 mPreventScreenOn = false;
1524
1525 // We're "undoing" a the prior preventScreenOn(true) call, so we
1526 // no longer need the 5-second safeguard.
1527 mHandler.removeCallbacks(mForceReenableScreenTask);
1528
1529 // Forcibly turn on the screen if it's supposed to be on. (This
1530 // handles the case where the screen is currently off because of
1531 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001532 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001534 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1536 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001537 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001539 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 }
1541 }
1542
1543 // Release the partial wake lock that we held during the
1544 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1545 mPreventScreenOnPartialLock.release();
1546 }
1547 }
1548 }
1549
1550 public void setScreenBrightnessOverride(int brightness) {
1551 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1552
Mike Lockwoodf527c712010-06-10 14:12:33 -04001553 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 synchronized (mLocks) {
1555 if (mScreenBrightnessOverride != brightness) {
1556 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001557 if (isScreenOn()) {
1558 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 }
1561 }
1562 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001563
1564 public void setButtonBrightnessOverride(int brightness) {
1565 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1566
Mike Lockwoodf527c712010-06-10 14:12:33 -04001567 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001568 synchronized (mLocks) {
1569 if (mButtonBrightnessOverride != brightness) {
1570 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001571 if (isScreenOn()) {
1572 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1573 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001574 }
1575 }
1576 }
1577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 /**
1579 * Sanity-check that gets called 5 seconds after any call to
1580 * preventScreenOn(true). This ensures that the original call
1581 * is followed promptly by a call to preventScreenOn(false).
1582 */
1583 private void forceReenableScreen() {
1584 // We shouldn't get here at all if mPreventScreenOn is false, since
1585 // we should have already removed any existing
1586 // mForceReenableScreenTask messages...
1587 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001588 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 return;
1590 }
1591
1592 // Uh oh. It's been 5 seconds since a call to
1593 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1594 // This means the app that called preventScreenOn(true) is either
1595 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1596 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1597 // crashed before doing so.)
1598
1599 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001600 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 + "Forcing the screen back on...");
1602 preventScreenOn(false);
1603 }
1604
1605 private Runnable mForceReenableScreenTask = new Runnable() {
1606 public void run() {
1607 forceReenableScreen();
1608 }
1609 };
1610
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001611 private int setScreenStateLocked(boolean on) {
1612 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001613 if (err == 0) {
1614 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1615 if (mUseSoftwareAutoBrightness) {
Joe Onoratod28f7532010-11-06 12:56:53 -07001616 enableLightSensorLocked(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001617 if (!on) {
1618 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001619 mButtonLight.turnOff();
1620 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001621 // clear current value so we will update based on the new conditions
1622 // when the sensor is reenabled.
1623 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001624 // reset our highest light sensor value when the screen turns off
1625 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001626 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001627 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001628 }
1629 return err;
1630 }
1631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 private void setPowerState(int state)
1633 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001634 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 }
1636
Mike Lockwood435eb642009-12-03 08:40:18 -05001637 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 {
1639 synchronized (mLocks) {
1640 int err;
1641
1642 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001643 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001645 + " noChangeLights=" + noChangeLights
1646 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 }
1648
1649 if (noChangeLights) {
1650 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1651 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001652 if (mProximitySensorActive) {
1653 // don't turn on the screen when the proximity sensor lock is held
1654 newState = (newState & ~SCREEN_BRIGHT);
1655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656
1657 if (batteryIsLow()) {
1658 newState |= BATTERY_LOW_BIT;
1659 } else {
1660 newState &= ~BATTERY_LOW_BIT;
1661 }
1662 if (newState == mPowerState) {
1663 return;
1664 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001665
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001666 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 newState |= ALL_BRIGHT;
1668 }
1669
1670 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1671 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1672
Mike Lockwood51b84492009-11-16 21:51:18 -05001673 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001674 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001676 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001678 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001680 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001682 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001684 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1686 }
1687
1688 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001689 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1691 }
1692
1693 if (oldScreenOn != newScreenOn) {
1694 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001695 // When the user presses the power button, we need to always send out the
1696 // notification that it's going to sleep so the keyguard goes on. But
1697 // we can't do that until the screen fades out, so we don't show the keyguard
1698 // too early.
1699 if (mStillNeedSleepNotification) {
1700 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1701 }
1702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 // Turn on the screen UNLESS there was a prior
1704 // preventScreenOn(true) request. (Note that the lifetime
1705 // of a single preventScreenOn() request is limited to 5
1706 // seconds to prevent a buggy app from disabling the
1707 // screen forever; see forceReenableScreen().)
1708 boolean reallyTurnScreenOn = true;
1709 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001710 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 + mPreventScreenOn);
1712 }
1713
1714 if (mPreventScreenOn) {
1715 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001716 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 }
1718 reallyTurnScreenOn = false;
1719 }
1720 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001721 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 long identity = Binder.clearCallingIdentity();
1723 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001724 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 mBatteryStats.noteScreenOn();
1726 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001727 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 } finally {
1729 Binder.restoreCallingIdentity(identity);
1730 }
1731 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001732 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 // But continue as if we really did turn the screen on...
1734 err = 0;
1735 }
1736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 mLastTouchDown = 0;
1738 mTotalTouchDownTime = 0;
1739 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001740 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 mTotalTouchDownTime, mTouchCycles);
1742 if (err == 0) {
1743 mPowerState |= SCREEN_ON_BIT;
1744 sendNotificationLocked(true, -1);
1745 }
1746 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001747 // cancel light sensor task
1748 mHandler.removeCallbacks(mAutoBrightnessTask);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001749 mLightSensorPendingDecrease = false;
1750 mLightSensorPendingIncrease = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 mScreenOffTime = SystemClock.elapsedRealtime();
1752 long identity = Binder.clearCallingIdentity();
1753 try {
1754 mBatteryStats.noteScreenOff();
1755 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001756 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 } finally {
1758 Binder.restoreCallingIdentity(identity);
1759 }
1760 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001761 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001763 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 err = 0;
1766 mLastTouchDown = 0;
1767 }
1768 }
1769 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001770
1771 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 }
1773 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001774
1775 private void updateNativePowerStateLocked() {
1776 nativeSetPowerState(
1777 (mPowerState & SCREEN_ON_BIT) != 0,
1778 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1779 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001780
Mike Lockwood435eb642009-12-03 08:40:18 -05001781 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001783 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001785 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1786 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001788 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001790 mScreenOffReason = reason;
1791 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 }
1793 return err;
1794 }
1795
1796 private boolean batteryIsLow() {
1797 return (!mIsPowered &&
1798 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1799 }
1800
The Android Open Source Project10592532009-03-18 17:39:46 -07001801 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001802 final int oldState = mPowerState;
Joe Onorato60607a92010-10-23 14:49:30 -07001803 if ((newState & SCREEN_ON_BIT) != 0) {
1804 // Only turn on the buttons or keyboard if the screen is also on.
1805 // We should never see the buttons on but not the screen.
1806 newState = applyButtonState(newState);
1807 newState = applyKeyboardState(newState);
1808 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001809 final int realDifference = (newState ^ oldState);
1810 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001812 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 int offMask = 0;
1816 int dimMask = 0;
1817 int onMask = 0;
1818
1819 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001822 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1823 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001825 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827 }
1828
1829 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001830 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1831 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001833 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 }
1835 }
1836
1837 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001838 int nominalCurrentValue = -1;
1839 // If there was an actual difference in the light state, then
1840 // figure out the "ideal" current value based on the previous
1841 // state. Otherwise, this is a change due to the brightness
1842 // override, so we want to animate from whatever the current
1843 // value is.
1844 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1845 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1846 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1847 nominalCurrentValue = preferredBrightness;
1848 break;
1849 case SCREEN_ON_BIT:
1850 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1851 break;
1852 case 0:
1853 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1854 break;
1855 case SCREEN_BRIGHT_BIT:
1856 default:
1857 // not possible
1858 nominalCurrentValue = (int)mScreenBrightness.curValue;
1859 break;
Joe Onorato128e7292009-03-24 18:41:31 -07001860 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001861 }
1862 int brightness = preferredBrightness;
1863 int steps = ANIM_STEPS;
1864 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1865 // dim or turn off backlight, depending on if the screen is on
1866 // the scale is because the brightness ramp isn't linear and this biases
1867 // it so the later parts take longer.
1868 final float scale = 1.5f;
1869 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1870 if (ratio > 1.0f) ratio = 1.0f;
1871 if ((newState & SCREEN_ON_BIT) == 0) {
1872 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1873 // was bright
1874 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001876 // was dim
1877 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001879 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001881 if ((oldState & SCREEN_ON_BIT) != 0) {
1882 // was bright
1883 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1884 } else {
1885 // was dim
1886 steps = (int)(ANIM_STEPS*ratio);
1887 }
1888 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1889 // If the "stay on while plugged in" option is
1890 // turned on, then the screen will often not
1891 // automatically turn off while plugged in. To
1892 // still have a sense of when it is inactive, we
1893 // will then count going dim as turning off.
1894 mScreenOffTime = SystemClock.elapsedRealtime();
1895 }
1896 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 }
1898 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001899 long identity = Binder.clearCallingIdentity();
1900 try {
1901 mBatteryStats.noteScreenBrightness(brightness);
1902 } catch (RemoteException e) {
1903 // Nothing interesting to do.
1904 } finally {
1905 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001907 mScreenBrightness.setTargetLocked(brightness, steps,
1908 INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001910
Joe Onorato60607a92010-10-23 14:49:30 -07001911 if (mSpew) {
1912 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask)
1913 + " dimMask=0x" + Integer.toHexString(dimMask)
1914 + " onMask=0x" + Integer.toHexString(onMask)
1915 + " difference=0x" + Integer.toHexString(difference)
1916 + " realDifference=0x" + Integer.toHexString(realDifference)
1917 + " forceState=0x" + Integer.toHexString(forceState)
1918 );
1919 }
1920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001922 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001923 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 }
1925 if (dimMask != 0) {
1926 int brightness = Power.BRIGHTNESS_DIM;
1927 if ((newState & BATTERY_LOW_BIT) != 0 &&
1928 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1929 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1930 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001931 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001932 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 }
1934 if (onMask != 0) {
1935 int brightness = getPreferredBrightness();
1936 if ((newState & BATTERY_LOW_BIT) != 0 &&
1937 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1938 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1939 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001940 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001941 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944
The Android Open Source Project10592532009-03-18 17:39:46 -07001945 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001946 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001947 ? LightsService.BRIGHTNESS_MODE_SENSOR
1948 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001949 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001950 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001951 }
1952 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001953 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001954 }
1955 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001956 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 }
1959
Joe Onoratob08a1af2010-10-11 19:28:58 -07001960 class BrightnessState implements Runnable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 boolean initialized;
1964 int targetValue;
1965 float curValue;
1966 float delta;
1967 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 BrightnessState(int m) {
1970 mask = m;
1971 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 public void dump(PrintWriter pw, String prefix) {
1974 pw.println(prefix + "animating=" + animating
1975 + " targetValue=" + targetValue
1976 + " curValue=" + curValue
1977 + " delta=" + delta);
1978 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001979
Joe Onoratob08a1af2010-10-11 19:28:58 -07001980 void setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001981 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 if (!initialized) {
1983 initialized = true;
1984 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001985 } else if (targetValue == target) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001986 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 }
1988 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001989 delta = (targetValue -
1990 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1991 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001993 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato3d3db602010-10-18 16:08:16 -04001994 Slog.i(TAG, "setTargetLocked mask=" + mask + " curValue=" + curValue
1995 + " target=" + target + " targetValue=" + targetValue + " delta=" + delta
Joe Onorato128e7292009-03-24 18:41:31 -07001996 + " nominalCurrentValue=" + nominalCurrentValue
1997 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 }
1999 animating = true;
Joe Onoratob08a1af2010-10-11 19:28:58 -07002000
2001 if (mSpew) {
2002 Slog.i(TAG, "scheduling light animator");
2003 }
2004 mScreenOffHandler.removeCallbacks(this);
2005 mScreenOffHandler.post(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 boolean stepLocked() {
2009 if (!animating) return false;
2010 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002011 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 + " target=" + targetValue + " delta=" + delta);
2013 }
2014 curValue += delta;
2015 int curIntValue = (int)curValue;
2016 boolean more = true;
2017 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002018 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 more = false;
2020 } else if (delta > 0) {
2021 if (curIntValue >= targetValue) {
2022 curValue = curIntValue = targetValue;
2023 more = false;
2024 }
2025 } else {
2026 if (curIntValue <= targetValue) {
2027 curValue = curIntValue = targetValue;
2028 more = false;
2029 }
2030 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002031 if (mSpew) Slog.d(TAG, "Animating curIntValue=" + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002032 setLightBrightness(mask, curIntValue);
Joe Onorato3d3db602010-10-18 16:08:16 -04002033 finishAnimationLocked(more, curIntValue);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002034 return more;
2035 }
2036
Joe Onorato3d3db602010-10-18 16:08:16 -04002037 void jumpToTargetLocked() {
2038 if (mSpew) Slog.d(TAG, "jumpToTargetLocked targetValue=" + targetValue + ": " + mask);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002039 setLightBrightness(mask, targetValue);
2040 final int tv = targetValue;
2041 curValue = tv;
2042 targetValue = -1;
Joe Onorato3d3db602010-10-18 16:08:16 -04002043 finishAnimationLocked(false, tv);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002044 }
2045
Joe Onorato3d3db602010-10-18 16:08:16 -04002046 private void finishAnimationLocked(boolean more, int curIntValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 animating = more;
2048 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002049 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002050 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 }
2052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 public void run() {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002056 if (mAnimateScreenLights) {
2057 synchronized (mLocks) {
2058 long now = SystemClock.uptimeMillis();
2059 boolean more = mScreenBrightness.stepLocked();
2060 if (more) {
2061 mScreenOffHandler.postAtTime(this, now+(1000/60));
2062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002064 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002065 synchronized (mLocks) {
Joe Onorato3d3db602010-10-18 16:08:16 -04002066 // we're turning off
2067 final boolean animate = animating && targetValue == Power.BRIGHTNESS_OFF;
2068 if (animate) {
2069 // It's pretty scary to hold mLocks for this long, and we should
2070 // redesign this, but it works for now.
2071 nativeStartSurfaceFlingerAnimation(
2072 mScreenOffReason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
2073 ? 0 : mAnimationSetting);
2074 }
2075 mScreenBrightness.jumpToTargetLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 }
2078 }
2079 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 private int getPreferredBrightness() {
2082 try {
2083 if (mScreenBrightnessOverride >= 0) {
2084 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002085 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05002086 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002087 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 }
2089 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
2090 SCREEN_BRIGHTNESS);
2091 // Don't let applications turn the screen all the way off
2092 return Math.max(brightness, Power.BRIGHTNESS_DIM);
2093 } catch (SettingNotFoundException snfe) {
2094 return Power.BRIGHTNESS_ON;
2095 }
2096 }
2097
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002098 private int applyButtonState(int state) {
2099 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002100 if ((state & BATTERY_LOW_BIT) != 0) {
2101 // do not override brightness if the battery is low
2102 return state;
2103 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002104 if (mButtonBrightnessOverride >= 0) {
2105 brightness = mButtonBrightnessOverride;
2106 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2107 brightness = mLightSensorButtonBrightness;
2108 }
2109 if (brightness > 0) {
2110 return state | BUTTON_BRIGHT_BIT;
2111 } else if (brightness == 0) {
2112 return state & ~BUTTON_BRIGHT_BIT;
2113 } else {
2114 return state;
2115 }
2116 }
2117
2118 private int applyKeyboardState(int state) {
2119 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002120 if ((state & BATTERY_LOW_BIT) != 0) {
2121 // do not override brightness if the battery is low
2122 return state;
2123 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002124 if (!mKeyboardVisible) {
2125 brightness = 0;
2126 } else if (mButtonBrightnessOverride >= 0) {
2127 brightness = mButtonBrightnessOverride;
2128 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2129 brightness = mLightSensorKeyboardBrightness;
2130 }
2131 if (brightness > 0) {
2132 return state | KEYBOARD_BRIGHT_BIT;
2133 } else if (brightness == 0) {
2134 return state & ~KEYBOARD_BRIGHT_BIT;
2135 } else {
2136 return state;
2137 }
2138 }
2139
Charles Mendis322591c2009-10-29 11:06:59 -07002140 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 synchronized (mLocks) {
2142 return (mPowerState & SCREEN_ON_BIT) != 0;
2143 }
2144 }
2145
Charles Mendis322591c2009-10-29 11:06:59 -07002146 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 synchronized (mLocks) {
2148 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2149 }
2150 }
2151
Mike Lockwood497087e32009-11-08 18:33:03 -05002152 private boolean isScreenTurningOffLocked() {
2153 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2154 }
2155
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002156 private boolean shouldLog(long time) {
2157 synchronized (mLocks) {
2158 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2159 mWarningSpewThrottleTime = time;
2160 mWarningSpewThrottleCount = 0;
2161 return true;
2162 } else if (mWarningSpewThrottleCount < 30) {
2163 mWarningSpewThrottleCount++;
2164 return true;
2165 } else {
2166 return false;
2167 }
2168 }
2169 }
2170
Mike Lockwood200b30b2009-09-20 00:23:59 -04002171 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002172 if (isScreenTurningOffLocked()) {
2173 // cancel animation so userActivity will succeed
2174 mScreenBrightness.animating = false;
2175 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002176 boolean savedActivityAllowed = mUserActivityAllowed;
2177 mUserActivityAllowed = true;
2178 userActivity(SystemClock.uptimeMillis(), false);
2179 mUserActivityAllowed = savedActivityAllowed;
2180 }
2181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2183 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002184 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 }
2186
2187 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002188 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2189 != PackageManager.PERMISSION_GRANTED) {
2190 if (shouldLog(time)) {
2191 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2192 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2193 }
2194 return;
2195 }
2196
Joe Onorato7999bff2010-07-24 11:50:05 -04002197 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 }
2199
2200 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002201 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 }
2203
2204 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002205 userActivity(time, -1, noChangeLights, eventType, force);
2206 }
2207
2208 /*
2209 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2210 * on with user activity. Don't use this function.
2211 */
2212 public void clearUserActivityTimeout(long now, long timeout) {
2213 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2214 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2215 userActivity(now, timeout, false, OTHER_EVENT, false);
2216 }
2217
2218 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2219 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220
2221 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Jeff Browna87ea462010-11-01 20:35:46 -07002222 && (eventType == CHEEK_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 if (false) {
Jeff Browna87ea462010-11-01 20:35:46 -07002224 Slog.d(TAG, "dropping cheek event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 }
2226 return;
2227 }
2228
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002229 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
2230 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
2231 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
2232 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002233 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002234 }
2235 return;
2236 }
2237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 if (false) {
2239 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002240 Slog.d(TAG, "userActivity !!!");//, new RuntimeException());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002242 Slog.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002243 }
2244 }
2245
2246 synchronized (mLocks) {
2247 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002248 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 + " mUserActivityAllowed=" + mUserActivityAllowed
2250 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002251 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2252 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002253 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002254 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002255 }
Mike Lockwood05067122009-10-27 23:07:25 -04002256 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002257 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002258 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002259 return;
2260 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002261 // Disable proximity sensor if if user presses power key while we are in the
2262 // "waiting for proximity sensor to go negative" state.
2263 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2264 mProximitySensorActive = false;
2265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 if (mLastEventTime <= time || force) {
2267 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002268 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002269 // Only turn on button backlights if a button was pressed
2270 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002271 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2273 } else {
2274 // don't clear button/keyboard backlights when the screen is touched.
2275 mUserState |= SCREEN_BRIGHT;
2276 }
2277
Dianne Hackborn617f8772009-03-31 15:04:46 -07002278 int uid = Binder.getCallingUid();
2279 long ident = Binder.clearCallingIdentity();
2280 try {
2281 mBatteryStats.noteUserActivity(uid, eventType);
2282 } catch (RemoteException e) {
2283 // Ignore
2284 } finally {
2285 Binder.restoreCallingIdentity(ident);
2286 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002287
Michael Chane96440f2009-05-06 10:27:36 -07002288 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002289 setPowerState(mUserState | mWakeLockState, noChangeLights,
2290 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002291 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 }
2293 }
2294 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002295
2296 if (mPolicy != null) {
2297 mPolicy.userActivity();
2298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002299 }
2300
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002301 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2302 try {
2303 int i;
2304 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2305 if (sensorValue < mAutoBrightnessLevels[i]) {
2306 break;
2307 }
2308 }
2309 return values[i];
2310 } catch (Exception e) {
2311 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002312 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002313 return 255;
2314 }
2315 }
2316
Mike Lockwood20f87d72009-11-05 16:08:51 -05002317 private Runnable mProximityTask = new Runnable() {
2318 public void run() {
2319 synchronized (mLocks) {
2320 if (mProximityPendingValue != -1) {
2321 proximityChangedLocked(mProximityPendingValue == 1);
2322 mProximityPendingValue = -1;
2323 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002324 if (mProximityPartialLock.isHeld()) {
2325 mProximityPartialLock.release();
2326 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002327 }
2328 }
2329 };
2330
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002331 private Runnable mAutoBrightnessTask = new Runnable() {
2332 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002333 synchronized (mLocks) {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002334 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2335 int value = (int)mLightSensorPendingValue;
2336 mLightSensorPendingDecrease = false;
2337 mLightSensorPendingIncrease = false;
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002338 lightSensorChangedLocked(value);
2339 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002340 }
2341 }
2342 };
2343
Mike Lockwoodb2865412010-02-02 22:40:33 -05002344 private void dockStateChanged(int state) {
2345 synchronized (mLocks) {
2346 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2347 if (mIsDocked) {
2348 mHighestLightSensorValue = -1;
2349 }
2350 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2351 // force lights recalculation
2352 int value = (int)mLightSensorValue;
2353 mLightSensorValue = -1;
2354 lightSensorChangedLocked(value);
2355 }
2356 }
2357 }
2358
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002359 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002360 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002361 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002362 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002363
Joe Onorato06eb33a2010-10-25 14:09:21 -07002364 // Don't do anything if the screen is off.
2365 if ((mPowerState & SCREEN_ON_BIT) == 0) {
2366 if (mDebugLightSensor) {
2367 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off");
2368 }
2369 return;
2370 }
2371
Mike Lockwoodb2865412010-02-02 22:40:33 -05002372 // do not allow light sensor value to decrease
2373 if (mHighestLightSensorValue < value) {
2374 mHighestLightSensorValue = value;
2375 }
2376
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002377 if (mLightSensorValue != value) {
2378 mLightSensorValue = value;
2379 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002380 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2381 // we only do this if we are undocked, since lighting should be stable when
2382 // stationary in a dock.
2383 int lcdValue = getAutoBrightnessValue(
2384 (mIsDocked ? value : mHighestLightSensorValue),
2385 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002386 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002387 int keyboardValue;
2388 if (mKeyboardVisible) {
2389 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2390 } else {
2391 keyboardValue = 0;
2392 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002393 mLightSensorScreenBrightness = lcdValue;
2394 mLightSensorButtonBrightness = buttonValue;
2395 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002396
2397 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002398 Slog.d(TAG, "lcdValue " + lcdValue);
2399 Slog.d(TAG, "buttonValue " + buttonValue);
2400 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002401 }
2402
Mike Lockwood4984e732009-11-01 08:16:33 -05002403 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002404 mScreenBrightness.setTargetLocked(lcdValue, AUTOBRIGHTNESS_ANIM_STEPS,
2405 INITIAL_SCREEN_BRIGHTNESS, (int)mScreenBrightness.curValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002406 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002407 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002408 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002409 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002410 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002411 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002412 }
2413 }
2414 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002415 }
2416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 /**
2418 * The user requested that we go to sleep (probably with the power button).
2419 * This overrides all wake locks that are held.
2420 */
2421 public void goToSleep(long time)
2422 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002423 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2424 }
2425
2426 /**
2427 * The user requested that we go to sleep (probably with the power button).
2428 * This overrides all wake locks that are held.
2429 */
2430 public void goToSleepWithReason(long time, int reason)
2431 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2433 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002434 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 }
2436 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002439 * Reboot the device immediately, passing 'reason' (may be null)
2440 * to the underlying __reboot system call. Should not return.
2441 */
2442 public void reboot(String reason)
2443 {
2444 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002445
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002446 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2447 throw new IllegalStateException("Too early to call reboot()");
2448 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002449
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002450 final String finalReason = reason;
2451 Runnable runnable = new Runnable() {
2452 public void run() {
2453 synchronized (this) {
2454 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002455 }
2456
San Mehat1e512792010-01-07 10:40:29 -08002457 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002458 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002459 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002460 mHandler.post(runnable);
2461
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002462 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002463 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002464 while (true) {
2465 try {
2466 runnable.wait();
2467 } catch (InterruptedException e) {
2468 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002469 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002470 }
2471 }
2472
Dan Egnor60d87622009-12-16 16:32:58 -08002473 /**
2474 * Crash the runtime (causing a complete restart of the Android framework).
2475 * Requires REBOOT permission. Mostly for testing. Should not return.
2476 */
2477 public void crash(final String message)
2478 {
2479 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2480 Thread t = new Thread("PowerManagerService.crash()") {
2481 public void run() { throw new RuntimeException(message); }
2482 };
2483 try {
2484 t.start();
2485 t.join();
2486 } catch (InterruptedException e) {
2487 Log.wtf(TAG, e);
2488 }
2489 }
2490
Mike Lockwood435eb642009-12-03 08:40:18 -05002491 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492
2493 if (mLastEventTime <= time) {
2494 mLastEventTime = time;
2495 // cancel all of the wake locks
2496 mWakeLockState = SCREEN_OFF;
2497 int N = mLocks.size();
2498 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002499 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 for (int i=0; i<N; i++) {
2501 WakeLock wl = mLocks.get(i);
2502 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002503 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2504 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2505 proxLock = true;
2506 } else {
2507 mLocks.get(i).activated = false;
2508 numCleared++;
2509 }
2510 }
2511 }
2512 if (!proxLock) {
2513 mProxIgnoredBecauseScreenTurnedOff = true;
2514 if (mDebugProximitySensor) {
2515 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 }
2517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002518 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002519 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002521 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 cancelTimerLocked();
2523 }
2524 }
2525
2526 public long timeSinceScreenOn() {
2527 synchronized (mLocks) {
2528 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2529 return 0;
2530 }
2531 return SystemClock.elapsedRealtime() - mScreenOffTime;
2532 }
2533 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002536 synchronized (mLocks) {
2537 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002538 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002539 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002540 if (mKeyboardVisible != visible) {
2541 mKeyboardVisible = visible;
2542 // don't signal user activity if the screen is off; other code
2543 // will take care of turning on due to a true change to the lid
2544 // switch and synchronized with the lock screen.
2545 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002546 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002547 // force recompute of backlight values
2548 if (mLightSensorValue >= 0) {
2549 int value = (int)mLightSensorValue;
2550 mLightSensorValue = -1;
2551 lightSensorChangedLocked(value);
2552 }
2553 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002554 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2555 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002556 }
2557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 }
2559
2560 /**
2561 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002562 * When disabling user activity we also reset user power state so the keyguard can reset its
2563 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 */
2565 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002566 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002567 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 synchronized (mLocks) {
2570 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002571 if (!enabled) {
2572 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2573 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 }
2576 }
2577
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002578 private void setScreenBrightnessMode(int mode) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002579 synchronized (mLocks) {
2580 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2581 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
2582 mAutoBrightessEnabled = enabled;
2583 // This will get us a new value
2584 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn());
Mike Lockwood2d155d22009-10-27 09:32:30 -04002585 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002586 }
2587 }
2588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 /** Sets the screen off timeouts:
2590 * mKeylightDelay
2591 * mDimDelay
2592 * mScreenOffDelay
2593 * */
2594 private void setScreenOffTimeoutsLocked() {
2595 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002596 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 mDimDelay = -1;
2598 mScreenOffDelay = 0;
2599 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2600 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2601 mDimDelay = -1;
2602 mScreenOffDelay = 0;
2603 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002604 int totalDelay = mScreenOffTimeoutSetting;
2605 if (totalDelay > mMaximumScreenOffTimeout) {
2606 totalDelay = mMaximumScreenOffTimeout;
2607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2609 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002610 // negative number means stay on as long as possible.
2611 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 } else if (mKeylightDelay < totalDelay) {
2613 // subtract the time that the keylight delay. This will give us the
2614 // remainder of the time that we need to sleep to get the accurate
2615 // screen off timeout.
2616 mScreenOffDelay = totalDelay - mKeylightDelay;
2617 } else {
2618 mScreenOffDelay = 0;
2619 }
2620 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2621 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2622 mScreenOffDelay = LONG_DIM_TIME;
2623 } else {
2624 mDimDelay = -1;
2625 }
2626 }
2627 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002628 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2630 + " mDimScreen=" + mDimScreen);
2631 }
2632 }
2633
2634 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002635 * Refreshes cached secure settings. Called once on startup, and
2636 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 */
Doug Zongker43866e02010-01-07 12:09:54 -08002638 private void updateSettingsValues() {
2639 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002641 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002643 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 }
2645
2646 private class LockList extends ArrayList<WakeLock>
2647 {
2648 void addLock(WakeLock wl)
2649 {
2650 int index = getIndex(wl.binder);
2651 if (index < 0) {
2652 this.add(wl);
2653 }
2654 }
2655
2656 WakeLock removeLock(IBinder binder)
2657 {
2658 int index = getIndex(binder);
2659 if (index >= 0) {
2660 return this.remove(index);
2661 } else {
2662 return null;
2663 }
2664 }
2665
2666 int getIndex(IBinder binder)
2667 {
2668 int N = this.size();
2669 for (int i=0; i<N; i++) {
2670 if (this.get(i).binder == binder) {
2671 return i;
2672 }
2673 }
2674 return -1;
2675 }
2676
2677 int gatherState()
2678 {
2679 int result = 0;
2680 int N = this.size();
2681 for (int i=0; i<N; i++) {
2682 WakeLock wl = this.get(i);
2683 if (wl.activated) {
2684 if (isScreenLock(wl.flags)) {
2685 result |= wl.minState;
2686 }
2687 }
2688 }
2689 return result;
2690 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002691
Michael Chane96440f2009-05-06 10:27:36 -07002692 int reactivateScreenLocksLocked()
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 (isScreenLock(wl.flags)) {
2699 wl.activated = true;
2700 result |= wl.minState;
2701 }
2702 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002703 if (mDebugProximitySensor) {
2704 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2705 + mProxIgnoredBecauseScreenTurnedOff);
2706 }
2707 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002708 return result;
2709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 }
2711
2712 void setPolicy(WindowManagerPolicy p) {
2713 synchronized (mLocks) {
2714 mPolicy = p;
2715 mLocks.notifyAll();
2716 }
2717 }
2718
2719 WindowManagerPolicy getPolicyLocked() {
2720 while (mPolicy == null || !mDoneBooting) {
2721 try {
2722 mLocks.wait();
2723 } catch (InterruptedException e) {
2724 // Ignore
2725 }
2726 }
2727 return mPolicy;
2728 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002731 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2732 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2733 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002734 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002735 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002736 }
2737
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002738 // wait until sensors are enabled before turning on screen.
2739 // some devices will not activate the light sensor properly on boot
2740 // unless we do this.
2741 if (mUseSoftwareAutoBrightness) {
2742 // turn the screen on
2743 setPowerState(SCREEN_BRIGHT);
2744 } else {
2745 // turn everything on
2746 setPowerState(ALL_BRIGHT);
2747 }
2748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002750 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002752
Joe Onoratod28f7532010-11-06 12:56:53 -07002753 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled);
2754
Dianne Hackborn617f8772009-03-31 15:04:46 -07002755 long identity = Binder.clearCallingIdentity();
2756 try {
2757 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2758 mBatteryStats.noteScreenOn();
2759 } catch (RemoteException e) {
2760 // Nothing interesting to do.
2761 } finally {
2762 Binder.restoreCallingIdentity(identity);
2763 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002764 }
2765 }
2766
2767 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002768 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002769 synchronized (mLocks) {
2770 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2772 updateWakeLockLocked();
2773 mLocks.notifyAll();
2774 }
2775 }
2776
Joe Onoratob08a1af2010-10-11 19:28:58 -07002777 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778 public void monitor() {
2779 synchronized (mLocks) { }
2780 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002781
2782 public int getSupportedWakeLockFlags() {
2783 int result = PowerManager.PARTIAL_WAKE_LOCK
2784 | PowerManager.FULL_WAKE_LOCK
2785 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2786
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002787 if (mProximitySensor != null) {
2788 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2789 }
2790
2791 return result;
2792 }
2793
Mike Lockwood237a2992009-09-15 14:42:16 -04002794 public void setBacklightBrightness(int brightness) {
2795 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2796 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07002797 synchronized (mLocks) {
2798 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2799 mLcdLight.setBrightness(brightness);
2800 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2801 mButtonLight.setBrightness(brightness);
2802 long identity = Binder.clearCallingIdentity();
2803 try {
2804 mBatteryStats.noteScreenBrightness(brightness);
2805 } catch (RemoteException e) {
2806 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2807 } finally {
2808 Binder.restoreCallingIdentity(identity);
2809 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002810
Joe Onoratob08a1af2010-10-11 19:28:58 -07002811 // update our animation state
Joe Onorato3d3db602010-10-18 16:08:16 -04002812 synchronized (mLocks) {
2813 mScreenBrightness.targetValue = brightness;
2814 mScreenBrightness.jumpToTargetLocked();
2815 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002816 }
2817 }
2818
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002819 public void setAttentionLight(boolean on, int color) {
2820 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002821 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002822 }
2823
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002824 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002825 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002826 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002827 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002828 if (!mProximitySensorEnabled) {
2829 // clear calling identity so sensor manager battery stats are accurate
2830 long identity = Binder.clearCallingIdentity();
2831 try {
2832 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2833 SensorManager.SENSOR_DELAY_NORMAL);
2834 mProximitySensorEnabled = true;
2835 } finally {
2836 Binder.restoreCallingIdentity(identity);
2837 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002838 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002839 }
2840
2841 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002842 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002843 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002844 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002845 if (mProximitySensorEnabled) {
2846 // clear calling identity so sensor manager battery stats are accurate
2847 long identity = Binder.clearCallingIdentity();
2848 try {
2849 mSensorManager.unregisterListener(mProximityListener);
2850 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002851 if (mProximityPartialLock.isHeld()) {
2852 mProximityPartialLock.release();
2853 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002854 mProximitySensorEnabled = false;
2855 } finally {
2856 Binder.restoreCallingIdentity(identity);
2857 }
2858 if (mProximitySensorActive) {
2859 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002860 if (mDebugProximitySensor) {
2861 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
2862 + mProxIgnoredBecauseScreenTurnedOff);
2863 }
2864 if (!mProxIgnoredBecauseScreenTurnedOff) {
2865 forceUserActivityLocked();
2866 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002867 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002868 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002869 }
2870
Mike Lockwood20f87d72009-11-05 16:08:51 -05002871 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002872 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002873 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002874 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002875 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002876 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002877 return;
2878 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002879 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002880 if (mDebugProximitySensor) {
2881 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2882 + mProxIgnoredBecauseScreenTurnedOff);
2883 }
2884 if (!mProxIgnoredBecauseScreenTurnedOff) {
2885 goToSleepLocked(SystemClock.uptimeMillis(),
2886 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
2887 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002888 mProximitySensorActive = true;
2889 } else {
2890 // proximity sensor negative events trigger as user activity.
2891 // temporarily set mUserActivityAllowed to true so this will work
2892 // even when the keyguard is on.
2893 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002894 if (mDebugProximitySensor) {
2895 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2896 + mProxIgnoredBecauseScreenTurnedOff);
2897 }
2898 if (!mProxIgnoredBecauseScreenTurnedOff) {
2899 forceUserActivityLocked();
2900 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002901
2902 if (mProximityWakeLockCount == 0) {
2903 // disable sensor if we have no listeners left after proximity negative
2904 disableProximityLockLocked();
2905 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002906 }
2907 }
2908
Joe Onoratod28f7532010-11-06 12:56:53 -07002909 private void enableLightSensorLocked(boolean enable) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002910 if (mDebugLightSensor) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002911 Slog.d(TAG, "enableLightSensorLocked enable=" + enable
2912 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled);
2913 }
2914 if (!mAutoBrightessEnabled) {
2915 enable = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002916 }
2917 if (mSensorManager != null && mLightSensorEnabled != enable) {
2918 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002919 // clear calling identity so sensor manager battery stats are accurate
2920 long identity = Binder.clearCallingIdentity();
2921 try {
2922 if (enable) {
2923 mSensorManager.registerListener(mLightListener, mLightSensor,
2924 SensorManager.SENSOR_DELAY_NORMAL);
2925 } else {
2926 mSensorManager.unregisterListener(mLightListener);
2927 mHandler.removeCallbacks(mAutoBrightnessTask);
2928 }
2929 } finally {
2930 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002931 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002932 }
2933 }
2934
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002935 SensorEventListener mProximityListener = new SensorEventListener() {
2936 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002937 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002938 synchronized (mLocks) {
2939 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002940 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2941 mLastProximityEventTime = milliseconds;
2942 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002943 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002944
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002945 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002946 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2947 distance < mProximitySensor.getMaximumRange());
2948
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002949 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002950 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002951 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002952 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2953 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2954 mProximityPendingValue = (active ? 1 : 0);
2955 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002956 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002957 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002958 // process the value immediately
2959 mProximityPendingValue = -1;
2960 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002961 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002962
2963 // update mProximityPartialLock state
2964 boolean held = mProximityPartialLock.isHeld();
2965 if (!held && proximityTaskQueued) {
2966 // hold wakelock until mProximityTask runs
2967 mProximityPartialLock.acquire();
2968 } else if (held && !proximityTaskQueued) {
2969 mProximityPartialLock.release();
2970 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002971 }
2972 }
2973
2974 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2975 // ignore
2976 }
2977 };
2978
2979 SensorEventListener mLightListener = new SensorEventListener() {
2980 public void onSensorChanged(SensorEvent event) {
2981 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002982 // ignore light sensor while screen is turning off
2983 if (isScreenTurningOffLocked()) {
2984 return;
2985 }
2986
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002987 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002988 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002989 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002990 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002991 }
Jim Rodovichd102fea2010-09-02 12:30:49 -05002992 if (mLightSensorValue == -1 ||
2993 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2994 // process the value immediately if screen has just turned on
2995 mHandler.removeCallbacks(mAutoBrightnessTask);
2996 mLightSensorPendingDecrease = false;
2997 mLightSensorPendingIncrease = false;
2998 lightSensorChangedLocked(value);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002999 } else {
Jim Rodovichd102fea2010-09-02 12:30:49 -05003000 if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
3001 (value < mLightSensorValue && mLightSensorPendingIncrease) ||
3002 (value == mLightSensorValue) ||
3003 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
3004 // delay processing to debounce the sensor
3005 mHandler.removeCallbacks(mAutoBrightnessTask);
3006 mLightSensorPendingDecrease = (value < mLightSensorValue);
3007 mLightSensorPendingIncrease = (value > mLightSensorValue);
3008 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
3009 mLightSensorPendingValue = value;
3010 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
3011 }
3012 } else {
3013 mLightSensorPendingValue = value;
3014 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07003015 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003016 }
3017 }
3018
3019 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3020 // ignore
3021 }
3022 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023}