blob: caf637600c11741e47ec235d932ce9c42c39f6e0 [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 + "':"
Joe Onorato1a542c72010-11-08 09:48:20 -08001178 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0
1179 ? " POKE_LOCK_IGNORE_TOUCH_EVENTS" : "")
Mike Lockwoodca44df82010-02-25 13:48:49 -05001180 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1181 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1182 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1183 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001185
Mike Lockwoodca44df82010-02-25 13:48:49 -05001186 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 }
1189
Joe Onorato7999bff2010-07-24 11:50:05 -04001190 private void setTimeoutLocked(long now, int nextState) {
1191 setTimeoutLocked(now, -1, nextState);
1192 }
1193
1194 // If they gave a timeoutOverride it is the number of seconds
1195 // to screen-off. Figure out where in the countdown cycle we
1196 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001197 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1198 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001199 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001200 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001201 long when = 0;
1202 if (timeoutOverride <= 0) {
1203 switch (nextState)
1204 {
1205 case SCREEN_BRIGHT:
1206 when = now + mKeylightDelay;
1207 break;
1208 case SCREEN_DIM:
1209 if (mDimDelay >= 0) {
1210 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001211 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001212 } else {
1213 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1214 }
1215 case SCREEN_OFF:
1216 synchronized (mLocks) {
1217 when = now + mScreenOffDelay;
1218 }
1219 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001220 default:
1221 when = now;
1222 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001224 } else {
1225 override: {
1226 if (timeoutOverride <= mScreenOffDelay) {
1227 when = now + timeoutOverride;
1228 nextState = SCREEN_OFF;
1229 break override;
1230 }
1231 timeoutOverride -= mScreenOffDelay;
1232
1233 if (mDimDelay >= 0) {
1234 if (timeoutOverride <= mDimDelay) {
1235 when = now + timeoutOverride;
1236 nextState = SCREEN_DIM;
1237 break override;
1238 }
1239 timeoutOverride -= mDimDelay;
1240 }
1241
1242 when = now + timeoutOverride;
1243 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001245 }
1246 if (mSpew) {
1247 Slog.d(TAG, "setTimeoutLocked now=" + now
1248 + " timeoutOverride=" + timeoutOverride
1249 + " nextState=" + nextState + " when=" + when);
1250 }
Joe Onorato797e6882010-08-26 14:46:01 -04001251
1252 mHandler.removeCallbacks(mTimeoutTask);
1253 mTimeoutTask.nextState = nextState;
1254 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1255 ? (originalTimeoutOverride - timeoutOverride)
1256 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001257 mHandler.postAtTime(mTimeoutTask, when);
1258 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 }
1261 }
1262
1263 private void cancelTimerLocked()
1264 {
1265 mHandler.removeCallbacks(mTimeoutTask);
1266 mTimeoutTask.nextState = -1;
1267 }
1268
1269 private class TimeoutTask implements Runnable
1270 {
1271 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001272 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 public void run()
1274 {
1275 synchronized (mLocks) {
1276 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001277 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 }
1279
1280 if (nextState == -1) {
1281 return;
1282 }
1283
1284 mUserState = this.nextState;
1285 setPowerState(this.nextState | mWakeLockState);
1286
1287 long now = SystemClock.uptimeMillis();
1288
1289 switch (this.nextState)
1290 {
1291 case SCREEN_BRIGHT:
1292 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001293 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 break;
1295 }
1296 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001297 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 break;
1299 }
1300 }
1301 }
1302 }
1303
1304 private void sendNotificationLocked(boolean on, int why)
1305 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001306 if (!on) {
1307 mStillNeedSleepNotification = false;
1308 }
1309
Joe Onorato128e7292009-03-24 18:41:31 -07001310 // Add to the queue.
1311 int index = 0;
1312 while (mBroadcastQueue[index] != -1) {
1313 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 }
Joe Onorato128e7292009-03-24 18:41:31 -07001315 mBroadcastQueue[index] = on ? 1 : 0;
1316 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317
Joe Onorato128e7292009-03-24 18:41:31 -07001318 // If we added it position 2, then there is a pair that can be stripped.
1319 // If we added it position 1 and we're turning the screen off, we can strip
1320 // the pair and do nothing, because the screen is already off, and therefore
1321 // keyguard has already been enabled.
1322 // However, if we added it at position 1 and we're turning it on, then position
1323 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1324 // on, so have to run the queue then.
1325 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001326 // While we're collapsing them, if it's going off, and the new reason
1327 // is more significant than the first, then use the new one.
1328 if (!on && mBroadcastWhy[0] > why) {
1329 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001330 }
1331 mBroadcastQueue[0] = on ? 1 : 0;
1332 mBroadcastQueue[1] = -1;
1333 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001334 mBroadcastWakeLock.release();
1335 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001336 index = 0;
1337 }
1338 if (index == 1 && !on) {
1339 mBroadcastQueue[0] = -1;
1340 mBroadcastQueue[1] = -1;
1341 index = -1;
1342 // The wake lock was being held, but we're not actually going to do any
1343 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001344 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001346 }
1347
1348 // Now send the message.
1349 if (index >= 0) {
1350 // Acquire the broadcast wake lock before changing the power
1351 // state. It will be release after the broadcast is sent.
1352 // We always increment the ref count for each notification in the queue
1353 // and always decrement when that notification is handled.
1354 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001355 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001356 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 }
1358 }
1359
1360 private Runnable mNotificationTask = new Runnable()
1361 {
1362 public void run()
1363 {
Joe Onorato128e7292009-03-24 18:41:31 -07001364 while (true) {
1365 int value;
1366 int why;
1367 WindowManagerPolicy policy;
1368 synchronized (mLocks) {
1369 value = mBroadcastQueue[0];
1370 why = mBroadcastWhy[0];
1371 for (int i=0; i<2; i++) {
1372 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1373 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1374 }
1375 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 }
Joe Onorato128e7292009-03-24 18:41:31 -07001377 if (value == 1) {
1378 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001379
Joe Onorato128e7292009-03-24 18:41:31 -07001380 policy.screenTurnedOn();
1381 try {
1382 ActivityManagerNative.getDefault().wakingUp();
1383 } catch (RemoteException e) {
1384 // ignore it
1385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386
Joe Onorato128e7292009-03-24 18:41:31 -07001387 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001388 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001389 }
1390 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1391 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1392 mScreenOnBroadcastDone, mHandler, 0, null, null);
1393 } else {
1394 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001395 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001396 mBroadcastWakeLock.mCount);
1397 mBroadcastWakeLock.release();
1398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 }
1400 }
Joe Onorato128e7292009-03-24 18:41:31 -07001401 else if (value == 0) {
1402 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001403
Joe Onorato128e7292009-03-24 18:41:31 -07001404 policy.screenTurnedOff(why);
1405 try {
1406 ActivityManagerNative.getDefault().goingToSleep();
1407 } catch (RemoteException e) {
1408 // ignore it.
1409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410
Joe Onorato128e7292009-03-24 18:41:31 -07001411 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1412 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1413 mScreenOffBroadcastDone, mHandler, 0, null, null);
1414 } else {
1415 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001416 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001417 mBroadcastWakeLock.mCount);
1418 mBroadcastWakeLock.release();
1419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
1421 }
Joe Onorato128e7292009-03-24 18:41:31 -07001422 else {
1423 // If we're in this case, then this handler is running for a previous
1424 // paired transaction. mBroadcastWakeLock will already have been released.
1425 break;
1426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
1428 }
1429 };
1430
1431 long mScreenOnStart;
1432 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1433 public void onReceive(Context context, Intent intent) {
1434 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001435 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1437 mBroadcastWakeLock.release();
1438 }
1439 }
1440 };
1441
1442 long mScreenOffStart;
1443 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1444 public void onReceive(Context context, Intent intent) {
1445 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001446 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1448 mBroadcastWakeLock.release();
1449 }
1450 }
1451 };
1452
1453 void logPointerUpEvent() {
1454 if (LOG_TOUCH_DOWNS) {
1455 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1456 mLastTouchDown = 0;
1457 }
1458 }
1459
1460 void logPointerDownEvent() {
1461 if (LOG_TOUCH_DOWNS) {
1462 // If we are not already timing a down/up sequence
1463 if (mLastTouchDown == 0) {
1464 mLastTouchDown = SystemClock.elapsedRealtime();
1465 mTouchCycles++;
1466 }
1467 }
1468 }
1469
1470 /**
1471 * Prevents the screen from turning on even if it *should* turn on due
1472 * to a subsequent full wake lock being acquired.
1473 * <p>
1474 * This is a temporary hack that allows an activity to "cover up" any
1475 * display glitches that happen during the activity's startup
1476 * sequence. (Specifically, this API was added to work around a
1477 * cosmetic bug in the "incoming call" sequence, where the lock screen
1478 * would flicker briefly before the incoming call UI became visible.)
1479 * TODO: There ought to be a more elegant way of doing this,
1480 * probably by having the PowerManager and ActivityManager
1481 * work together to let apps specify that the screen on/off
1482 * state should be synchronized with the Activity lifecycle.
1483 * <p>
1484 * Note that calling preventScreenOn(true) will NOT turn the screen
1485 * off if it's currently on. (This API only affects *future*
1486 * acquisitions of full wake locks.)
1487 * But calling preventScreenOn(false) WILL turn the screen on if
1488 * it's currently off because of a prior preventScreenOn(true) call.
1489 * <p>
1490 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1491 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1492 * call doesn't occur within 5 seconds, we'll turn the screen back on
1493 * ourselves (and log a warning about it); this prevents a buggy app
1494 * from disabling the screen forever.)
1495 * <p>
1496 * TODO: this feature should really be controlled by a new type of poke
1497 * lock (rather than an IPowerManager call).
1498 */
1499 public void preventScreenOn(boolean prevent) {
1500 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1501
1502 synchronized (mLocks) {
1503 if (prevent) {
1504 // First of all, grab a partial wake lock to
1505 // make sure the CPU stays on during the entire
1506 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1507 mPreventScreenOnPartialLock.acquire();
1508
1509 // Post a forceReenableScreen() call (for 5 seconds in the
1510 // future) to make sure the matching preventScreenOn(false) call
1511 // has happened by then.
1512 mHandler.removeCallbacks(mForceReenableScreenTask);
1513 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1514
1515 // Finally, set the flag that prevents the screen from turning on.
1516 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001517 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 mPreventScreenOn = true;
1519 } else {
1520 // (Re)enable the screen.
1521 mPreventScreenOn = false;
1522
1523 // We're "undoing" a the prior preventScreenOn(true) call, so we
1524 // no longer need the 5-second safeguard.
1525 mHandler.removeCallbacks(mForceReenableScreenTask);
1526
1527 // Forcibly turn on the screen if it's supposed to be on. (This
1528 // handles the case where the screen is currently off because of
1529 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001530 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001532 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1534 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001535 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001537 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539 }
1540
1541 // Release the partial wake lock that we held during the
1542 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1543 mPreventScreenOnPartialLock.release();
1544 }
1545 }
1546 }
1547
1548 public void setScreenBrightnessOverride(int brightness) {
1549 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1550
Mike Lockwoodf527c712010-06-10 14:12:33 -04001551 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 synchronized (mLocks) {
1553 if (mScreenBrightnessOverride != brightness) {
1554 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001555 if (isScreenOn()) {
1556 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 }
1559 }
1560 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001561
1562 public void setButtonBrightnessOverride(int brightness) {
1563 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1564
Mike Lockwoodf527c712010-06-10 14:12:33 -04001565 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001566 synchronized (mLocks) {
1567 if (mButtonBrightnessOverride != brightness) {
1568 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001569 if (isScreenOn()) {
1570 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1571 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001572 }
1573 }
1574 }
1575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 /**
1577 * Sanity-check that gets called 5 seconds after any call to
1578 * preventScreenOn(true). This ensures that the original call
1579 * is followed promptly by a call to preventScreenOn(false).
1580 */
1581 private void forceReenableScreen() {
1582 // We shouldn't get here at all if mPreventScreenOn is false, since
1583 // we should have already removed any existing
1584 // mForceReenableScreenTask messages...
1585 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001586 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 return;
1588 }
1589
1590 // Uh oh. It's been 5 seconds since a call to
1591 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1592 // This means the app that called preventScreenOn(true) is either
1593 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1594 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1595 // crashed before doing so.)
1596
1597 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001598 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 + "Forcing the screen back on...");
1600 preventScreenOn(false);
1601 }
1602
1603 private Runnable mForceReenableScreenTask = new Runnable() {
1604 public void run() {
1605 forceReenableScreen();
1606 }
1607 };
1608
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001609 private int setScreenStateLocked(boolean on) {
1610 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001611 if (err == 0) {
1612 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1613 if (mUseSoftwareAutoBrightness) {
Joe Onoratod28f7532010-11-06 12:56:53 -07001614 enableLightSensorLocked(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001615 if (!on) {
1616 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001617 mButtonLight.turnOff();
1618 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001619 // clear current value so we will update based on the new conditions
1620 // when the sensor is reenabled.
1621 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001622 // reset our highest light sensor value when the screen turns off
1623 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001624 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001625 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001626 }
1627 return err;
1628 }
1629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 private void setPowerState(int state)
1631 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001632 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
1634
Mike Lockwood435eb642009-12-03 08:40:18 -05001635 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 {
1637 synchronized (mLocks) {
1638 int err;
1639
1640 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001641 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001643 + " noChangeLights=" + noChangeLights
1644 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 }
1646
1647 if (noChangeLights) {
1648 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1649 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001650 if (mProximitySensorActive) {
1651 // don't turn on the screen when the proximity sensor lock is held
1652 newState = (newState & ~SCREEN_BRIGHT);
1653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654
1655 if (batteryIsLow()) {
1656 newState |= BATTERY_LOW_BIT;
1657 } else {
1658 newState &= ~BATTERY_LOW_BIT;
1659 }
1660 if (newState == mPowerState) {
1661 return;
1662 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001663
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001664 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 newState |= ALL_BRIGHT;
1666 }
1667
1668 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1669 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1670
Mike Lockwood51b84492009-11-16 21:51:18 -05001671 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001672 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001674 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001676 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001678 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001680 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001682 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1684 }
1685
1686 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001687 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1689 }
1690
1691 if (oldScreenOn != newScreenOn) {
1692 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001693 // When the user presses the power button, we need to always send out the
1694 // notification that it's going to sleep so the keyguard goes on. But
1695 // we can't do that until the screen fades out, so we don't show the keyguard
1696 // too early.
1697 if (mStillNeedSleepNotification) {
1698 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1699 }
1700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 // Turn on the screen UNLESS there was a prior
1702 // preventScreenOn(true) request. (Note that the lifetime
1703 // of a single preventScreenOn() request is limited to 5
1704 // seconds to prevent a buggy app from disabling the
1705 // screen forever; see forceReenableScreen().)
1706 boolean reallyTurnScreenOn = true;
1707 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001708 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 + mPreventScreenOn);
1710 }
1711
1712 if (mPreventScreenOn) {
1713 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001714 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 }
1716 reallyTurnScreenOn = false;
1717 }
1718 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001719 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 long identity = Binder.clearCallingIdentity();
1721 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001722 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 mBatteryStats.noteScreenOn();
1724 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001725 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 } finally {
1727 Binder.restoreCallingIdentity(identity);
1728 }
1729 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001730 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 // But continue as if we really did turn the screen on...
1732 err = 0;
1733 }
1734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 mLastTouchDown = 0;
1736 mTotalTouchDownTime = 0;
1737 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001738 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 mTotalTouchDownTime, mTouchCycles);
1740 if (err == 0) {
1741 mPowerState |= SCREEN_ON_BIT;
1742 sendNotificationLocked(true, -1);
1743 }
1744 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001745 // cancel light sensor task
1746 mHandler.removeCallbacks(mAutoBrightnessTask);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001747 mLightSensorPendingDecrease = false;
1748 mLightSensorPendingIncrease = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 mScreenOffTime = SystemClock.elapsedRealtime();
1750 long identity = Binder.clearCallingIdentity();
1751 try {
1752 mBatteryStats.noteScreenOff();
1753 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001754 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 } finally {
1756 Binder.restoreCallingIdentity(identity);
1757 }
1758 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001759 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001761 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 err = 0;
1764 mLastTouchDown = 0;
1765 }
1766 }
1767 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001768
1769 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 }
1771 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001772
1773 private void updateNativePowerStateLocked() {
1774 nativeSetPowerState(
1775 (mPowerState & SCREEN_ON_BIT) != 0,
1776 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001778
Mike Lockwood435eb642009-12-03 08:40:18 -05001779 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001781 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001783 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1784 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001786 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001788 mScreenOffReason = reason;
1789 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 }
1791 return err;
1792 }
1793
1794 private boolean batteryIsLow() {
1795 return (!mIsPowered &&
1796 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1797 }
1798
The Android Open Source Project10592532009-03-18 17:39:46 -07001799 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001800 final int oldState = mPowerState;
Joe Onorato60607a92010-10-23 14:49:30 -07001801 if ((newState & SCREEN_ON_BIT) != 0) {
1802 // Only turn on the buttons or keyboard if the screen is also on.
1803 // We should never see the buttons on but not the screen.
1804 newState = applyButtonState(newState);
1805 newState = applyKeyboardState(newState);
1806 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001807 final int realDifference = (newState ^ oldState);
1808 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001810 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 int offMask = 0;
1814 int dimMask = 0;
1815 int onMask = 0;
1816
1817 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001820 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1821 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001823 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 }
1825 }
1826
1827 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001828 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1829 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001831 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 }
1833 }
1834
1835 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001836 int nominalCurrentValue = -1;
1837 // If there was an actual difference in the light state, then
1838 // figure out the "ideal" current value based on the previous
1839 // state. Otherwise, this is a change due to the brightness
1840 // override, so we want to animate from whatever the current
1841 // value is.
1842 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1843 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1844 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1845 nominalCurrentValue = preferredBrightness;
1846 break;
1847 case SCREEN_ON_BIT:
1848 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1849 break;
1850 case 0:
1851 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1852 break;
1853 case SCREEN_BRIGHT_BIT:
1854 default:
1855 // not possible
1856 nominalCurrentValue = (int)mScreenBrightness.curValue;
1857 break;
Joe Onorato128e7292009-03-24 18:41:31 -07001858 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001859 }
1860 int brightness = preferredBrightness;
1861 int steps = ANIM_STEPS;
1862 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1863 // dim or turn off backlight, depending on if the screen is on
1864 // the scale is because the brightness ramp isn't linear and this biases
1865 // it so the later parts take longer.
1866 final float scale = 1.5f;
1867 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1868 if (ratio > 1.0f) ratio = 1.0f;
1869 if ((newState & SCREEN_ON_BIT) == 0) {
1870 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1871 // was bright
1872 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001874 // was dim
1875 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001877 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001879 if ((oldState & SCREEN_ON_BIT) != 0) {
1880 // was bright
1881 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1882 } else {
1883 // was dim
1884 steps = (int)(ANIM_STEPS*ratio);
1885 }
1886 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1887 // If the "stay on while plugged in" option is
1888 // turned on, then the screen will often not
1889 // automatically turn off while plugged in. To
1890 // still have a sense of when it is inactive, we
1891 // will then count going dim as turning off.
1892 mScreenOffTime = SystemClock.elapsedRealtime();
1893 }
1894 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 }
1896 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001897 long identity = Binder.clearCallingIdentity();
1898 try {
1899 mBatteryStats.noteScreenBrightness(brightness);
1900 } catch (RemoteException e) {
1901 // Nothing interesting to do.
1902 } finally {
1903 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001905 mScreenBrightness.setTargetLocked(brightness, steps,
1906 INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001908
Joe Onorato60607a92010-10-23 14:49:30 -07001909 if (mSpew) {
1910 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask)
1911 + " dimMask=0x" + Integer.toHexString(dimMask)
1912 + " onMask=0x" + Integer.toHexString(onMask)
1913 + " difference=0x" + Integer.toHexString(difference)
1914 + " realDifference=0x" + Integer.toHexString(realDifference)
1915 + " forceState=0x" + Integer.toHexString(forceState)
1916 );
1917 }
1918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001920 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001921 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001922 }
1923 if (dimMask != 0) {
1924 int brightness = Power.BRIGHTNESS_DIM;
1925 if ((newState & BATTERY_LOW_BIT) != 0 &&
1926 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1927 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1928 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001929 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001930 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 }
1932 if (onMask != 0) {
1933 int brightness = getPreferredBrightness();
1934 if ((newState & BATTERY_LOW_BIT) != 0 &&
1935 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1936 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1937 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001938 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001939 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942
The Android Open Source Project10592532009-03-18 17:39:46 -07001943 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001944 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001945 ? LightsService.BRIGHTNESS_MODE_SENSOR
1946 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001947 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001948 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001949 }
1950 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001951 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001952 }
1953 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001954 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 }
1957
Joe Onoratob08a1af2010-10-11 19:28:58 -07001958 class BrightnessState implements Runnable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 boolean initialized;
1962 int targetValue;
1963 float curValue;
1964 float delta;
1965 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 BrightnessState(int m) {
1968 mask = m;
1969 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 public void dump(PrintWriter pw, String prefix) {
1972 pw.println(prefix + "animating=" + animating
1973 + " targetValue=" + targetValue
1974 + " curValue=" + curValue
1975 + " delta=" + delta);
1976 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001977
Joe Onoratob08a1af2010-10-11 19:28:58 -07001978 void setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001979 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 if (!initialized) {
1981 initialized = true;
1982 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001983 } else if (targetValue == target) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001984 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 }
1986 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001987 delta = (targetValue -
1988 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1989 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001991 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato3d3db602010-10-18 16:08:16 -04001992 Slog.i(TAG, "setTargetLocked mask=" + mask + " curValue=" + curValue
1993 + " target=" + target + " targetValue=" + targetValue + " delta=" + delta
Joe Onorato128e7292009-03-24 18:41:31 -07001994 + " nominalCurrentValue=" + nominalCurrentValue
1995 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
1997 animating = true;
Joe Onoratob08a1af2010-10-11 19:28:58 -07001998
1999 if (mSpew) {
2000 Slog.i(TAG, "scheduling light animator");
2001 }
2002 mScreenOffHandler.removeCallbacks(this);
2003 mScreenOffHandler.post(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 boolean stepLocked() {
2007 if (!animating) return false;
2008 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002009 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 + " target=" + targetValue + " delta=" + delta);
2011 }
2012 curValue += delta;
2013 int curIntValue = (int)curValue;
2014 boolean more = true;
2015 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002016 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 more = false;
2018 } else if (delta > 0) {
2019 if (curIntValue >= targetValue) {
2020 curValue = curIntValue = targetValue;
2021 more = false;
2022 }
2023 } else {
2024 if (curIntValue <= targetValue) {
2025 curValue = curIntValue = targetValue;
2026 more = false;
2027 }
2028 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002029 if (mSpew) Slog.d(TAG, "Animating curIntValue=" + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002030 setLightBrightness(mask, curIntValue);
Joe Onorato3d3db602010-10-18 16:08:16 -04002031 finishAnimationLocked(more, curIntValue);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002032 return more;
2033 }
2034
Joe Onorato3d3db602010-10-18 16:08:16 -04002035 void jumpToTargetLocked() {
2036 if (mSpew) Slog.d(TAG, "jumpToTargetLocked targetValue=" + targetValue + ": " + mask);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002037 setLightBrightness(mask, targetValue);
2038 final int tv = targetValue;
2039 curValue = tv;
2040 targetValue = -1;
Joe Onorato3d3db602010-10-18 16:08:16 -04002041 finishAnimationLocked(false, tv);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002042 }
2043
Joe Onorato3d3db602010-10-18 16:08:16 -04002044 private void finishAnimationLocked(boolean more, int curIntValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 animating = more;
2046 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002047 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002048 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 }
2050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 public void run() {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002054 if (mAnimateScreenLights) {
2055 synchronized (mLocks) {
2056 long now = SystemClock.uptimeMillis();
2057 boolean more = mScreenBrightness.stepLocked();
2058 if (more) {
2059 mScreenOffHandler.postAtTime(this, now+(1000/60));
2060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002062 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002063 synchronized (mLocks) {
Joe Onorato3d3db602010-10-18 16:08:16 -04002064 // we're turning off
2065 final boolean animate = animating && targetValue == Power.BRIGHTNESS_OFF;
2066 if (animate) {
2067 // It's pretty scary to hold mLocks for this long, and we should
2068 // redesign this, but it works for now.
2069 nativeStartSurfaceFlingerAnimation(
2070 mScreenOffReason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
2071 ? 0 : mAnimationSetting);
2072 }
2073 mScreenBrightness.jumpToTargetLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 }
2076 }
2077 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 private int getPreferredBrightness() {
2080 try {
2081 if (mScreenBrightnessOverride >= 0) {
2082 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002083 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05002084 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002085 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 }
2087 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
2088 SCREEN_BRIGHTNESS);
2089 // Don't let applications turn the screen all the way off
2090 return Math.max(brightness, Power.BRIGHTNESS_DIM);
2091 } catch (SettingNotFoundException snfe) {
2092 return Power.BRIGHTNESS_ON;
2093 }
2094 }
2095
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002096 private int applyButtonState(int state) {
2097 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002098 if ((state & BATTERY_LOW_BIT) != 0) {
2099 // do not override brightness if the battery is low
2100 return state;
2101 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002102 if (mButtonBrightnessOverride >= 0) {
2103 brightness = mButtonBrightnessOverride;
2104 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2105 brightness = mLightSensorButtonBrightness;
2106 }
2107 if (brightness > 0) {
2108 return state | BUTTON_BRIGHT_BIT;
2109 } else if (brightness == 0) {
2110 return state & ~BUTTON_BRIGHT_BIT;
2111 } else {
2112 return state;
2113 }
2114 }
2115
2116 private int applyKeyboardState(int state) {
2117 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002118 if ((state & BATTERY_LOW_BIT) != 0) {
2119 // do not override brightness if the battery is low
2120 return state;
2121 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002122 if (!mKeyboardVisible) {
2123 brightness = 0;
2124 } else if (mButtonBrightnessOverride >= 0) {
2125 brightness = mButtonBrightnessOverride;
2126 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2127 brightness = mLightSensorKeyboardBrightness;
2128 }
2129 if (brightness > 0) {
2130 return state | KEYBOARD_BRIGHT_BIT;
2131 } else if (brightness == 0) {
2132 return state & ~KEYBOARD_BRIGHT_BIT;
2133 } else {
2134 return state;
2135 }
2136 }
2137
Charles Mendis322591c2009-10-29 11:06:59 -07002138 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 synchronized (mLocks) {
2140 return (mPowerState & SCREEN_ON_BIT) != 0;
2141 }
2142 }
2143
Charles Mendis322591c2009-10-29 11:06:59 -07002144 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 synchronized (mLocks) {
2146 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2147 }
2148 }
2149
Mike Lockwood497087e32009-11-08 18:33:03 -05002150 private boolean isScreenTurningOffLocked() {
2151 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2152 }
2153
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002154 private boolean shouldLog(long time) {
2155 synchronized (mLocks) {
2156 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2157 mWarningSpewThrottleTime = time;
2158 mWarningSpewThrottleCount = 0;
2159 return true;
2160 } else if (mWarningSpewThrottleCount < 30) {
2161 mWarningSpewThrottleCount++;
2162 return true;
2163 } else {
2164 return false;
2165 }
2166 }
2167 }
2168
Mike Lockwood200b30b2009-09-20 00:23:59 -04002169 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002170 if (isScreenTurningOffLocked()) {
2171 // cancel animation so userActivity will succeed
2172 mScreenBrightness.animating = false;
2173 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002174 boolean savedActivityAllowed = mUserActivityAllowed;
2175 mUserActivityAllowed = true;
2176 userActivity(SystemClock.uptimeMillis(), false);
2177 mUserActivityAllowed = savedActivityAllowed;
2178 }
2179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2181 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002182 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 }
2184
2185 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002186 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2187 != PackageManager.PERMISSION_GRANTED) {
2188 if (shouldLog(time)) {
2189 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2190 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2191 }
2192 return;
2193 }
2194
Joe Onorato7999bff2010-07-24 11:50:05 -04002195 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 }
2197
2198 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002199 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 }
2201
2202 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002203 userActivity(time, -1, noChangeLights, eventType, force);
2204 }
2205
2206 /*
2207 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2208 * on with user activity. Don't use this function.
2209 */
2210 public void clearUserActivityTimeout(long now, long timeout) {
2211 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2212 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2213 userActivity(now, timeout, false, OTHER_EVENT, false);
2214 }
2215
2216 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2217 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218
Joe Onorato1a542c72010-11-08 09:48:20 -08002219 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0) && (eventType == TOUCH_EVENT)) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002220 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002221 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002222 }
2223 return;
2224 }
2225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 synchronized (mLocks) {
2227 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002228 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002229 + " mUserActivityAllowed=" + mUserActivityAllowed
2230 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002231 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2232 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002233 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002234 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 }
Mike Lockwood05067122009-10-27 23:07:25 -04002236 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002237 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002238 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002239 return;
2240 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002241 // Disable proximity sensor if if user presses power key while we are in the
2242 // "waiting for proximity sensor to go negative" state.
2243 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2244 mProximitySensorActive = false;
2245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 if (mLastEventTime <= time || force) {
2247 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002248 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002249 // Only turn on button backlights if a button was pressed
2250 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002251 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2253 } else {
2254 // don't clear button/keyboard backlights when the screen is touched.
2255 mUserState |= SCREEN_BRIGHT;
2256 }
2257
Dianne Hackborn617f8772009-03-31 15:04:46 -07002258 int uid = Binder.getCallingUid();
2259 long ident = Binder.clearCallingIdentity();
2260 try {
2261 mBatteryStats.noteUserActivity(uid, eventType);
2262 } catch (RemoteException e) {
2263 // Ignore
2264 } finally {
2265 Binder.restoreCallingIdentity(ident);
2266 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002267
Michael Chane96440f2009-05-06 10:27:36 -07002268 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002269 setPowerState(mUserState | mWakeLockState, noChangeLights,
2270 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002271 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 }
2273 }
2274 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002275
2276 if (mPolicy != null) {
2277 mPolicy.userActivity();
2278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 }
2280
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002281 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2282 try {
2283 int i;
2284 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2285 if (sensorValue < mAutoBrightnessLevels[i]) {
2286 break;
2287 }
2288 }
2289 return values[i];
2290 } catch (Exception e) {
2291 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002292 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002293 return 255;
2294 }
2295 }
2296
Mike Lockwood20f87d72009-11-05 16:08:51 -05002297 private Runnable mProximityTask = new Runnable() {
2298 public void run() {
2299 synchronized (mLocks) {
2300 if (mProximityPendingValue != -1) {
2301 proximityChangedLocked(mProximityPendingValue == 1);
2302 mProximityPendingValue = -1;
2303 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002304 if (mProximityPartialLock.isHeld()) {
2305 mProximityPartialLock.release();
2306 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002307 }
2308 }
2309 };
2310
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002311 private Runnable mAutoBrightnessTask = new Runnable() {
2312 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002313 synchronized (mLocks) {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002314 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2315 int value = (int)mLightSensorPendingValue;
2316 mLightSensorPendingDecrease = false;
2317 mLightSensorPendingIncrease = false;
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002318 lightSensorChangedLocked(value);
2319 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002320 }
2321 }
2322 };
2323
Mike Lockwoodb2865412010-02-02 22:40:33 -05002324 private void dockStateChanged(int state) {
2325 synchronized (mLocks) {
2326 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2327 if (mIsDocked) {
2328 mHighestLightSensorValue = -1;
2329 }
2330 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2331 // force lights recalculation
2332 int value = (int)mLightSensorValue;
2333 mLightSensorValue = -1;
2334 lightSensorChangedLocked(value);
2335 }
2336 }
2337 }
2338
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002339 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002340 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002341 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002342 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002343
Joe Onorato06eb33a2010-10-25 14:09:21 -07002344 // Don't do anything if the screen is off.
2345 if ((mPowerState & SCREEN_ON_BIT) == 0) {
2346 if (mDebugLightSensor) {
2347 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off");
2348 }
2349 return;
2350 }
2351
Mike Lockwoodb2865412010-02-02 22:40:33 -05002352 // do not allow light sensor value to decrease
2353 if (mHighestLightSensorValue < value) {
2354 mHighestLightSensorValue = value;
2355 }
2356
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002357 if (mLightSensorValue != value) {
2358 mLightSensorValue = value;
2359 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002360 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2361 // we only do this if we are undocked, since lighting should be stable when
2362 // stationary in a dock.
2363 int lcdValue = getAutoBrightnessValue(
2364 (mIsDocked ? value : mHighestLightSensorValue),
2365 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002366 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002367 int keyboardValue;
2368 if (mKeyboardVisible) {
2369 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2370 } else {
2371 keyboardValue = 0;
2372 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002373 mLightSensorScreenBrightness = lcdValue;
2374 mLightSensorButtonBrightness = buttonValue;
2375 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002376
2377 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002378 Slog.d(TAG, "lcdValue " + lcdValue);
2379 Slog.d(TAG, "buttonValue " + buttonValue);
2380 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002381 }
2382
Mike Lockwood4984e732009-11-01 08:16:33 -05002383 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002384 mScreenBrightness.setTargetLocked(lcdValue, AUTOBRIGHTNESS_ANIM_STEPS,
2385 INITIAL_SCREEN_BRIGHTNESS, (int)mScreenBrightness.curValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002386 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002387 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002388 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002389 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002390 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002391 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002392 }
2393 }
2394 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002395 }
2396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 /**
2398 * The user requested that we go to sleep (probably with the power button).
2399 * This overrides all wake locks that are held.
2400 */
2401 public void goToSleep(long time)
2402 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002403 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2404 }
2405
2406 /**
2407 * The user requested that we go to sleep (probably with the power button).
2408 * This overrides all wake locks that are held.
2409 */
2410 public void goToSleepWithReason(long time, int reason)
2411 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2413 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002414 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 }
2416 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002419 * Reboot the device immediately, passing 'reason' (may be null)
2420 * to the underlying __reboot system call. Should not return.
2421 */
2422 public void reboot(String reason)
2423 {
2424 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002425
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002426 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2427 throw new IllegalStateException("Too early to call reboot()");
2428 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002429
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002430 final String finalReason = reason;
2431 Runnable runnable = new Runnable() {
2432 public void run() {
2433 synchronized (this) {
2434 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002435 }
2436
San Mehat1e512792010-01-07 10:40:29 -08002437 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002438 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002439 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002440 mHandler.post(runnable);
2441
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002442 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002443 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002444 while (true) {
2445 try {
2446 runnable.wait();
2447 } catch (InterruptedException e) {
2448 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002449 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002450 }
2451 }
2452
Dan Egnor60d87622009-12-16 16:32:58 -08002453 /**
2454 * Crash the runtime (causing a complete restart of the Android framework).
2455 * Requires REBOOT permission. Mostly for testing. Should not return.
2456 */
2457 public void crash(final String message)
2458 {
2459 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2460 Thread t = new Thread("PowerManagerService.crash()") {
2461 public void run() { throw new RuntimeException(message); }
2462 };
2463 try {
2464 t.start();
2465 t.join();
2466 } catch (InterruptedException e) {
2467 Log.wtf(TAG, e);
2468 }
2469 }
2470
Mike Lockwood435eb642009-12-03 08:40:18 -05002471 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472
2473 if (mLastEventTime <= time) {
2474 mLastEventTime = time;
2475 // cancel all of the wake locks
2476 mWakeLockState = SCREEN_OFF;
2477 int N = mLocks.size();
2478 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002479 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 for (int i=0; i<N; i++) {
2481 WakeLock wl = mLocks.get(i);
2482 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002483 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2484 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2485 proxLock = true;
2486 } else {
2487 mLocks.get(i).activated = false;
2488 numCleared++;
2489 }
2490 }
2491 }
2492 if (!proxLock) {
2493 mProxIgnoredBecauseScreenTurnedOff = true;
2494 if (mDebugProximitySensor) {
2495 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 }
2497 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002498 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002499 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002501 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 cancelTimerLocked();
2503 }
2504 }
2505
2506 public long timeSinceScreenOn() {
2507 synchronized (mLocks) {
2508 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2509 return 0;
2510 }
2511 return SystemClock.elapsedRealtime() - mScreenOffTime;
2512 }
2513 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002516 synchronized (mLocks) {
2517 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002518 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002519 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002520 if (mKeyboardVisible != visible) {
2521 mKeyboardVisible = visible;
2522 // don't signal user activity if the screen is off; other code
2523 // will take care of turning on due to a true change to the lid
2524 // switch and synchronized with the lock screen.
2525 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002526 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002527 // force recompute of backlight values
2528 if (mLightSensorValue >= 0) {
2529 int value = (int)mLightSensorValue;
2530 mLightSensorValue = -1;
2531 lightSensorChangedLocked(value);
2532 }
2533 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002534 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2535 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002536 }
2537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 }
2539
2540 /**
2541 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002542 * When disabling user activity we also reset user power state so the keyguard can reset its
2543 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 */
2545 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002546 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002547 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 synchronized (mLocks) {
2550 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002551 if (!enabled) {
2552 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2553 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 }
2556 }
2557
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002558 private void setScreenBrightnessMode(int mode) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002559 synchronized (mLocks) {
2560 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2561 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
2562 mAutoBrightessEnabled = enabled;
2563 // This will get us a new value
2564 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn());
Mike Lockwood2d155d22009-10-27 09:32:30 -04002565 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002566 }
2567 }
2568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 /** Sets the screen off timeouts:
2570 * mKeylightDelay
2571 * mDimDelay
2572 * mScreenOffDelay
2573 * */
2574 private void setScreenOffTimeoutsLocked() {
2575 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002576 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 mDimDelay = -1;
2578 mScreenOffDelay = 0;
2579 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2580 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2581 mDimDelay = -1;
2582 mScreenOffDelay = 0;
2583 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002584 int totalDelay = mScreenOffTimeoutSetting;
2585 if (totalDelay > mMaximumScreenOffTimeout) {
2586 totalDelay = mMaximumScreenOffTimeout;
2587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2589 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002590 // negative number means stay on as long as possible.
2591 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 } else if (mKeylightDelay < totalDelay) {
2593 // subtract the time that the keylight delay. This will give us the
2594 // remainder of the time that we need to sleep to get the accurate
2595 // screen off timeout.
2596 mScreenOffDelay = totalDelay - mKeylightDelay;
2597 } else {
2598 mScreenOffDelay = 0;
2599 }
2600 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2601 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2602 mScreenOffDelay = LONG_DIM_TIME;
2603 } else {
2604 mDimDelay = -1;
2605 }
2606 }
2607 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002608 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2610 + " mDimScreen=" + mDimScreen);
2611 }
2612 }
2613
2614 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002615 * Refreshes cached secure settings. Called once on startup, and
2616 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 */
Doug Zongker43866e02010-01-07 12:09:54 -08002618 private void updateSettingsValues() {
2619 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002621 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002623 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 }
2625
2626 private class LockList extends ArrayList<WakeLock>
2627 {
2628 void addLock(WakeLock wl)
2629 {
2630 int index = getIndex(wl.binder);
2631 if (index < 0) {
2632 this.add(wl);
2633 }
2634 }
2635
2636 WakeLock removeLock(IBinder binder)
2637 {
2638 int index = getIndex(binder);
2639 if (index >= 0) {
2640 return this.remove(index);
2641 } else {
2642 return null;
2643 }
2644 }
2645
2646 int getIndex(IBinder binder)
2647 {
2648 int N = this.size();
2649 for (int i=0; i<N; i++) {
2650 if (this.get(i).binder == binder) {
2651 return i;
2652 }
2653 }
2654 return -1;
2655 }
2656
2657 int gatherState()
2658 {
2659 int result = 0;
2660 int N = this.size();
2661 for (int i=0; i<N; i++) {
2662 WakeLock wl = this.get(i);
2663 if (wl.activated) {
2664 if (isScreenLock(wl.flags)) {
2665 result |= wl.minState;
2666 }
2667 }
2668 }
2669 return result;
2670 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002671
Michael Chane96440f2009-05-06 10:27:36 -07002672 int reactivateScreenLocksLocked()
2673 {
2674 int result = 0;
2675 int N = this.size();
2676 for (int i=0; i<N; i++) {
2677 WakeLock wl = this.get(i);
2678 if (isScreenLock(wl.flags)) {
2679 wl.activated = true;
2680 result |= wl.minState;
2681 }
2682 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002683 if (mDebugProximitySensor) {
2684 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2685 + mProxIgnoredBecauseScreenTurnedOff);
2686 }
2687 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002688 return result;
2689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 }
2691
2692 void setPolicy(WindowManagerPolicy p) {
2693 synchronized (mLocks) {
2694 mPolicy = p;
2695 mLocks.notifyAll();
2696 }
2697 }
2698
2699 WindowManagerPolicy getPolicyLocked() {
2700 while (mPolicy == null || !mDoneBooting) {
2701 try {
2702 mLocks.wait();
2703 } catch (InterruptedException e) {
2704 // Ignore
2705 }
2706 }
2707 return mPolicy;
2708 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002711 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2712 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2713 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002714 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002715 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002716 }
2717
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002718 // wait until sensors are enabled before turning on screen.
2719 // some devices will not activate the light sensor properly on boot
2720 // unless we do this.
2721 if (mUseSoftwareAutoBrightness) {
2722 // turn the screen on
2723 setPowerState(SCREEN_BRIGHT);
2724 } else {
2725 // turn everything on
2726 setPowerState(ALL_BRIGHT);
2727 }
2728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002730 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002732
Joe Onoratod28f7532010-11-06 12:56:53 -07002733 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled);
2734
Dianne Hackborn617f8772009-03-31 15:04:46 -07002735 long identity = Binder.clearCallingIdentity();
2736 try {
2737 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2738 mBatteryStats.noteScreenOn();
2739 } catch (RemoteException e) {
2740 // Nothing interesting to do.
2741 } finally {
2742 Binder.restoreCallingIdentity(identity);
2743 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002744 }
2745 }
2746
2747 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002748 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002749 synchronized (mLocks) {
2750 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2752 updateWakeLockLocked();
2753 mLocks.notifyAll();
2754 }
2755 }
2756
Joe Onoratob08a1af2010-10-11 19:28:58 -07002757 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 public void monitor() {
2759 synchronized (mLocks) { }
2760 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002761
2762 public int getSupportedWakeLockFlags() {
2763 int result = PowerManager.PARTIAL_WAKE_LOCK
2764 | PowerManager.FULL_WAKE_LOCK
2765 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2766
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002767 if (mProximitySensor != null) {
2768 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2769 }
2770
2771 return result;
2772 }
2773
Mike Lockwood237a2992009-09-15 14:42:16 -04002774 public void setBacklightBrightness(int brightness) {
2775 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2776 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07002777 synchronized (mLocks) {
2778 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2779 mLcdLight.setBrightness(brightness);
2780 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2781 mButtonLight.setBrightness(brightness);
2782 long identity = Binder.clearCallingIdentity();
2783 try {
2784 mBatteryStats.noteScreenBrightness(brightness);
2785 } catch (RemoteException e) {
2786 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2787 } finally {
2788 Binder.restoreCallingIdentity(identity);
2789 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002790
Joe Onoratob08a1af2010-10-11 19:28:58 -07002791 // update our animation state
Joe Onorato3d3db602010-10-18 16:08:16 -04002792 synchronized (mLocks) {
2793 mScreenBrightness.targetValue = brightness;
2794 mScreenBrightness.jumpToTargetLocked();
2795 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002796 }
2797 }
2798
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002799 public void setAttentionLight(boolean on, int color) {
2800 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002801 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002802 }
2803
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002804 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002805 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002806 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002807 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002808 if (!mProximitySensorEnabled) {
2809 // clear calling identity so sensor manager battery stats are accurate
2810 long identity = Binder.clearCallingIdentity();
2811 try {
2812 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2813 SensorManager.SENSOR_DELAY_NORMAL);
2814 mProximitySensorEnabled = true;
2815 } finally {
2816 Binder.restoreCallingIdentity(identity);
2817 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002818 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002819 }
2820
2821 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002822 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002823 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002824 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002825 if (mProximitySensorEnabled) {
2826 // clear calling identity so sensor manager battery stats are accurate
2827 long identity = Binder.clearCallingIdentity();
2828 try {
2829 mSensorManager.unregisterListener(mProximityListener);
2830 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002831 if (mProximityPartialLock.isHeld()) {
2832 mProximityPartialLock.release();
2833 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002834 mProximitySensorEnabled = false;
2835 } finally {
2836 Binder.restoreCallingIdentity(identity);
2837 }
2838 if (mProximitySensorActive) {
2839 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002840 if (mDebugProximitySensor) {
2841 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
2842 + mProxIgnoredBecauseScreenTurnedOff);
2843 }
2844 if (!mProxIgnoredBecauseScreenTurnedOff) {
2845 forceUserActivityLocked();
2846 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002847 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002848 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002849 }
2850
Mike Lockwood20f87d72009-11-05 16:08:51 -05002851 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002852 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002853 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002854 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002855 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002856 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002857 return;
2858 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002859 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002860 if (mDebugProximitySensor) {
2861 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2862 + mProxIgnoredBecauseScreenTurnedOff);
2863 }
2864 if (!mProxIgnoredBecauseScreenTurnedOff) {
2865 goToSleepLocked(SystemClock.uptimeMillis(),
2866 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
2867 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002868 mProximitySensorActive = true;
2869 } else {
2870 // proximity sensor negative events trigger as user activity.
2871 // temporarily set mUserActivityAllowed to true so this will work
2872 // even when the keyguard is on.
2873 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002874 if (mDebugProximitySensor) {
2875 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2876 + mProxIgnoredBecauseScreenTurnedOff);
2877 }
2878 if (!mProxIgnoredBecauseScreenTurnedOff) {
2879 forceUserActivityLocked();
2880 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002881
2882 if (mProximityWakeLockCount == 0) {
2883 // disable sensor if we have no listeners left after proximity negative
2884 disableProximityLockLocked();
2885 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002886 }
2887 }
2888
Joe Onoratod28f7532010-11-06 12:56:53 -07002889 private void enableLightSensorLocked(boolean enable) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002890 if (mDebugLightSensor) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002891 Slog.d(TAG, "enableLightSensorLocked enable=" + enable
2892 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled);
2893 }
2894 if (!mAutoBrightessEnabled) {
2895 enable = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002896 }
2897 if (mSensorManager != null && mLightSensorEnabled != enable) {
2898 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002899 // clear calling identity so sensor manager battery stats are accurate
2900 long identity = Binder.clearCallingIdentity();
2901 try {
2902 if (enable) {
2903 mSensorManager.registerListener(mLightListener, mLightSensor,
2904 SensorManager.SENSOR_DELAY_NORMAL);
2905 } else {
2906 mSensorManager.unregisterListener(mLightListener);
2907 mHandler.removeCallbacks(mAutoBrightnessTask);
2908 }
2909 } finally {
2910 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002911 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002912 }
2913 }
2914
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002915 SensorEventListener mProximityListener = new SensorEventListener() {
2916 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002917 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002918 synchronized (mLocks) {
2919 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002920 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2921 mLastProximityEventTime = milliseconds;
2922 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002923 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002924
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002925 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002926 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2927 distance < mProximitySensor.getMaximumRange());
2928
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002929 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002930 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002931 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002932 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2933 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2934 mProximityPendingValue = (active ? 1 : 0);
2935 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002936 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002937 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002938 // process the value immediately
2939 mProximityPendingValue = -1;
2940 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002941 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002942
2943 // update mProximityPartialLock state
2944 boolean held = mProximityPartialLock.isHeld();
2945 if (!held && proximityTaskQueued) {
2946 // hold wakelock until mProximityTask runs
2947 mProximityPartialLock.acquire();
2948 } else if (held && !proximityTaskQueued) {
2949 mProximityPartialLock.release();
2950 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002951 }
2952 }
2953
2954 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2955 // ignore
2956 }
2957 };
2958
2959 SensorEventListener mLightListener = new SensorEventListener() {
2960 public void onSensorChanged(SensorEvent event) {
2961 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002962 // ignore light sensor while screen is turning off
2963 if (isScreenTurningOffLocked()) {
2964 return;
2965 }
2966
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002967 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002968 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002969 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002970 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002971 }
Jim Rodovichd102fea2010-09-02 12:30:49 -05002972 if (mLightSensorValue == -1 ||
2973 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2974 // process the value immediately if screen has just turned on
2975 mHandler.removeCallbacks(mAutoBrightnessTask);
2976 mLightSensorPendingDecrease = false;
2977 mLightSensorPendingIncrease = false;
2978 lightSensorChangedLocked(value);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002979 } else {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002980 if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
2981 (value < mLightSensorValue && mLightSensorPendingIncrease) ||
2982 (value == mLightSensorValue) ||
2983 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
2984 // delay processing to debounce the sensor
2985 mHandler.removeCallbacks(mAutoBrightnessTask);
2986 mLightSensorPendingDecrease = (value < mLightSensorValue);
2987 mLightSensorPendingIncrease = (value > mLightSensorValue);
2988 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2989 mLightSensorPendingValue = value;
2990 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2991 }
2992 } else {
2993 mLightSensorPendingValue = value;
2994 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002995 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002996 }
2997 }
2998
2999 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3000 // ignore
3001 }
3002 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003}