blob: ad910c412c562e36769d6c21b21dd191d30e82d5 [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;
28import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
31import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070032import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080033import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070035import android.hardware.Sensor;
36import android.hardware.SensorEvent;
37import android.hardware.SensorEventListener;
38import android.hardware.SensorManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.os.BatteryStats;
40import android.os.Binder;
Doug Zongker43866e02010-01-07 12:09:54 -080041import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.Handler;
43import android.os.HandlerThread;
44import android.os.IBinder;
45import android.os.IPowerManager;
46import android.os.LocalPowerManager;
47import android.os.Power;
48import android.os.PowerManager;
49import android.os.Process;
50import android.os.RemoteException;
San Mehat14e69af2010-01-06 14:58:18 -080051import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.SystemClock;
53import android.provider.Settings.SettingNotFoundException;
54import android.provider.Settings;
55import android.util.EventLog;
56import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080057import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.view.WindowManagerPolicy;
59import static android.provider.Settings.System.DIM_SCREEN;
60import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050061import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070062import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
64import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
65
66import java.io.FileDescriptor;
Doug Zongker50a21f42009-11-19 12:49:53 -080067import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import java.io.PrintWriter;
69import java.util.ArrayList;
70import java.util.HashMap;
71import java.util.Observable;
72import java.util.Observer;
73
Mike Lockwoodbc706a02009-07-27 13:50:57 -070074class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040075 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
77 private static final String TAG = "PowerManagerService";
78 static final String PARTIAL_NAME = "PowerManagerService";
79
80 private static final boolean LOG_PARTIAL_WL = false;
81
82 // Indicates whether touch-down cycles should be logged as part of the
83 // LOG_POWER_SCREEN_STATE log events
84 private static final boolean LOG_TOUCH_DOWNS = true;
85
86 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
87 | PowerManager.SCREEN_DIM_WAKE_LOCK
88 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070089 | PowerManager.FULL_WAKE_LOCK
90 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091
92 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -080093 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
95 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
96 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
97 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
98
Mike Lockwoodd7786b42009-10-15 17:09:16 -070099 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -0500100 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700101
Mike Lockwood20f87d72009-11-05 16:08:51 -0500102 // For debouncing the proximity sensor.
103 private static final int PROXIMITY_SENSOR_DELAY = 1000;
104
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400105 // trigger proximity if distance is less than 5 cm
106 private static final float PROXIMITY_THRESHOLD = 5.0f;
107
Doug Zongker43866e02010-01-07 12:09:54 -0800108 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
110
111 // flags for setPowerState
112 private static final int SCREEN_ON_BIT = 0x00000001;
113 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
114 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
115 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
116 private static final int BATTERY_LOW_BIT = 0x00000010;
117
118 // values for setPowerState
119
120 // SCREEN_OFF == everything off
121 private static final int SCREEN_OFF = 0x00000000;
122
123 // SCREEN_DIM == screen on, screen backlight dim
124 private static final int SCREEN_DIM = SCREEN_ON_BIT;
125
126 // SCREEN_BRIGHT == screen on, screen backlight bright
127 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
128
129 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
130 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
131
132 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
133 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
134
135 // used for noChangeLights in setPowerState()
136 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
137
138 static final boolean ANIMATE_SCREEN_LIGHTS = true;
139 static final boolean ANIMATE_BUTTON_LIGHTS = false;
140 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400143 // Slower animation for autobrightness changes
144 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
146 // These magic numbers are the initial state of the LEDs at boot. Ideally
147 // we should read them from the driver, but our current hardware returns 0
148 // for the initial value. Oops!
149 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
150 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
151 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 private final int MY_UID;
154
155 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500156 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500158 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
159 private final int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private int mPartialCount = 0;
161 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500162 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
163 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
164 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 private int mUserState;
166 private boolean mKeyboardVisible = false;
167 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500168 private int mProximityWakeLockCount = 0;
169 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700170 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500171 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
172 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800173 private int mScreenOffTimeoutSetting;
174 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 private int mKeylightDelay;
176 private int mDimDelay;
177 private int mScreenOffDelay;
178 private int mWakeLockState;
179 private long mLastEventTime = 0;
180 private long mScreenOffTime;
181 private volatile WindowManagerPolicy mPolicy;
182 private final LockList mLocks = new LockList();
183 private Intent mScreenOffIntent;
184 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500185 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500187 private LightsService.Light mLcdLight;
188 private LightsService.Light mButtonLight;
189 private LightsService.Light mKeyboardLight;
190 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 private UnsynchronizedWakeLock mBroadcastWakeLock;
192 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
193 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
194 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500195 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 private HandlerThread mHandlerThread;
197 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500198 private final TimeoutTask mTimeoutTask = new TimeoutTask();
199 private final LightAnimator mLightAnimator = new LightAnimator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700201 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700203 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700205 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700206 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 private boolean mIsPowered = false;
208 private IActivityManager mActivityService;
209 private IBatteryStats mBatteryStats;
210 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700211 private SensorManager mSensorManager;
212 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400213 private Sensor mLightSensor;
214 private boolean mLightSensorEnabled;
215 private float mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500216 private int mHighestLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700217 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500218 private int mLightSensorScreenBrightness = -1;
219 private int mLightSensorButtonBrightness = -1;
220 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500222 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 private long mNextTimeout;
224 private volatile int mPokey = 0;
225 private volatile boolean mPokeAwakeOnSet = false;
226 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500227 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500228 // mLastScreenOnTime is the time the screen was last turned on
229 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 private boolean mPreventScreenOn;
231 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500232 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400233 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700234 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700235 private int[] mAutoBrightnessLevels;
236 private int[] mLcdBacklightValues;
237 private int[] mButtonBacklightValues;
238 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500239 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240
241 // Used when logging number and duration of touch-down cycles
242 private long mTotalTouchDownTime;
243 private long mLastTouchDown;
244 private int mTouchCycles;
245
246 // could be either static or controllable at runtime
247 private static final boolean mSpew = false;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500248 private static final boolean mDebugProximitySensor = (true || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400249 private static final boolean mDebugLightSensor = (false || mSpew);
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700250
251 private native void nativeInit();
252 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253
254 /*
255 static PrintStream mLog;
256 static {
257 try {
258 mLog = new PrintStream("/data/power.log");
259 }
260 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800261 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 }
263 }
264 static class Log {
265 static void d(String tag, String s) {
266 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800267 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 }
269 static void i(String tag, String s) {
270 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800271 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 }
273 static void w(String tag, String s) {
274 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800275 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 }
277 static void e(String tag, String s) {
278 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800279 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 }
281 }
282 */
283
284 /**
285 * This class works around a deadlock between the lock in PowerManager.WakeLock
286 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
287 * mToken object so it can be accessed from any thread, but it calls into here
288 * with its lock held. This class is essentially a reimplementation of
289 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
290 * only call it with our own locks held.
291 */
292 private class UnsynchronizedWakeLock {
293 int mFlags;
294 String mTag;
295 IBinder mToken;
296 int mCount = 0;
297 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500298 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299
300 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
301 mFlags = flags;
302 mTag = tag;
303 mToken = new Binder();
304 mRefCounted = refCounted;
305 }
306
307 public void acquire() {
308 if (!mRefCounted || mCount++ == 0) {
309 long ident = Binder.clearCallingIdentity();
310 try {
311 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
312 MY_UID, mTag);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500313 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 } finally {
315 Binder.restoreCallingIdentity(ident);
316 }
317 }
318 }
319
320 public void release() {
321 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500322 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500323 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 }
325 if (mCount < 0) {
326 throw new RuntimeException("WakeLock under-locked " + mTag);
327 }
328 }
329
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500330 public boolean isHeld()
331 {
332 return mHeld;
333 }
334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 public String toString() {
336 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500337 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 }
339 }
340
341 private final class BatteryReceiver extends BroadcastReceiver {
342 @Override
343 public void onReceive(Context context, Intent intent) {
344 synchronized (mLocks) {
345 boolean wasPowered = mIsPowered;
346 mIsPowered = mBatteryService.isPowered();
347
348 if (mIsPowered != wasPowered) {
349 // update mStayOnWhilePluggedIn wake lock
350 updateWakeLockLocked();
351
352 // treat plugging and unplugging the devices as a user activity.
353 // users find it disconcerting when they unplug the device
354 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500355 // to avoid turning on the screen when unplugging, we only trigger
356 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 // temporarily set mUserActivityAllowed to true so this will work
358 // even when the keyguard is on.
359 synchronized (mLocks) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500360 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0) {
361 forceUserActivityLocked();
362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 }
364 }
365 }
366 }
367 }
368
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500369 private final class BootCompletedReceiver extends BroadcastReceiver {
370 @Override
371 public void onReceive(Context context, Intent intent) {
372 bootCompleted();
373 }
374 }
375
Mike Lockwoodb2865412010-02-02 22:40:33 -0500376 private final class DockReceiver extends BroadcastReceiver {
377 @Override
378 public void onReceive(Context context, Intent intent) {
379 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
380 Intent.EXTRA_DOCK_STATE_UNDOCKED);
381 dockStateChanged(state);
382 }
383 }
384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 /**
386 * Set the setting that determines whether the device stays on when plugged in.
387 * The argument is a bit string, with each bit specifying a power source that,
388 * when the device is connected to that source, causes the device to stay on.
389 * See {@link android.os.BatteryManager} for the list of power sources that
390 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
391 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
392 * @param val an {@code int} containing the bits that specify which power sources
393 * should cause the device to stay on.
394 */
395 public void setStayOnSetting(int val) {
396 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
397 Settings.System.putInt(mContext.getContentResolver(),
398 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
399 }
400
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800401 public void setMaximumScreenOffTimeount(int timeMs) {
402 mContext.enforceCallingOrSelfPermission(
403 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
404 synchronized (mLocks) {
405 mMaximumScreenOffTimeout = timeMs;
406 // recalculate everything
407 setScreenOffTimeoutsLocked();
408 }
409 }
410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 private class SettingsObserver implements Observer {
412 private int getInt(String name) {
413 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
414 }
415
416 public void update(Observable o, Object arg) {
417 synchronized (mLocks) {
418 // STAY_ON_WHILE_PLUGGED_IN
419 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
420 updateWakeLockLocked();
421
422 // SCREEN_OFF_TIMEOUT
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800423 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424
425 // DIM_SCREEN
426 //mDimScreen = getInt(DIM_SCREEN) != 0;
427
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700428 // SCREEN_BRIGHTNESS_MODE
429 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 // recalculate everything
432 setScreenOffTimeoutsLocked();
433 }
434 }
435 }
436
437 PowerManagerService()
438 {
439 // Hack to get our uid... should have a func for this.
440 long token = Binder.clearCallingIdentity();
441 MY_UID = Binder.getCallingUid();
442 Binder.restoreCallingIdentity(token);
443
444 // XXX remove this when the kernel doesn't timeout wake locks
445 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
446
447 // assume nothing is on yet
448 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 // Add ourself to the Watchdog monitors.
451 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 }
453
454 private ContentQueryMap mSettings;
455
Mike Lockwood3a322132009-11-24 00:30:52 -0500456 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700457 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500458 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 mContext = context;
460 mActivityService = activity;
461 mBatteryStats = BatteryStatsService.getService();
462 mBatteryService = battery;
463
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500464 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
465 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
466 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
467 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 mHandlerThread = new HandlerThread("PowerManagerService") {
470 @Override
471 protected void onLooperPrepared() {
472 super.onLooperPrepared();
473 initInThread();
474 }
475 };
476 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 synchronized (mHandlerThread) {
479 while (!mInitComplete) {
480 try {
481 mHandlerThread.wait();
482 } catch (InterruptedException e) {
483 // Ignore
484 }
485 }
486 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700487
488 nativeInit();
489 synchronized (mLocks) {
490 updateNativePowerStateLocked();
491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 void initInThread() {
495 mHandler = new Handler();
496
497 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700498 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
500 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
501 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
502 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
503 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
504 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500505 mProximityPartialLock = new UnsynchronizedWakeLock(
506 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507
508 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
509 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
510 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
511 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
512
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700513 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400514
515 // read settings for auto-brightness
516 mUseSoftwareAutoBrightness = resources.getBoolean(
517 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400518 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700519 mAutoBrightnessLevels = resources.getIntArray(
520 com.android.internal.R.array.config_autoBrightnessLevels);
521 mLcdBacklightValues = resources.getIntArray(
522 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
523 mButtonBacklightValues = resources.getIntArray(
524 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
525 mKeyboardBacklightValues = resources.getIntArray(
526 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500527 mLightSensorWarmupTime = resources.getInteger(
528 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700529 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700530
531 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
533 "(" + Settings.System.NAME + "=?) or ("
534 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700535 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700537 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
538 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 null);
540 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
541 SettingsObserver settingsObserver = new SettingsObserver();
542 mSettings.addObserver(settingsObserver);
543
544 // pretend that the settings changed so we will get their initial state
545 settingsObserver.update(mSettings, null);
546
547 // register for the battery changed notifications
548 IntentFilter filter = new IntentFilter();
549 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
550 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500551 filter = new IntentFilter();
552 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
553 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500554 filter = new IntentFilter();
555 filter.addAction(Intent.ACTION_DOCK_EVENT);
556 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557
Doug Zongker43866e02010-01-07 12:09:54 -0800558 // Listen for secure settings changes
559 mContext.getContentResolver().registerContentObserver(
560 Settings.Secure.CONTENT_URI, true,
561 new ContentObserver(new Handler()) {
562 public void onChange(boolean selfChange) {
563 updateSettingsValues();
564 }
565 });
566 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 synchronized (mHandlerThread) {
569 mInitComplete = true;
570 mHandlerThread.notifyAll();
571 }
572 }
573
574 private class WakeLock implements IBinder.DeathRecipient
575 {
576 WakeLock(int f, IBinder b, String t, int u) {
577 super();
578 flags = f;
579 binder = b;
580 tag = t;
581 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400582 pid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 if (u != MY_UID || (
584 !"KEEP_SCREEN_ON_FLAG".equals(tag)
585 && !"KeyInputQueue".equals(tag))) {
586 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
587 ? BatteryStats.WAKE_TYPE_PARTIAL
588 : BatteryStats.WAKE_TYPE_FULL;
589 } else {
590 monitorType = -1;
591 }
592 try {
593 b.linkToDeath(this, 0);
594 } catch (RemoteException e) {
595 binderDied();
596 }
597 }
598 public void binderDied() {
599 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500600 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 }
602 }
603 final int flags;
604 final IBinder binder;
605 final String tag;
606 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400607 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 final int monitorType;
609 boolean activated = true;
610 int minState;
611 }
612
613 private void updateWakeLockLocked() {
614 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
615 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
616 mStayOnWhilePluggedInScreenDimLock.acquire();
617 mStayOnWhilePluggedInPartialLock.acquire();
618 } else {
619 mStayOnWhilePluggedInScreenDimLock.release();
620 mStayOnWhilePluggedInPartialLock.release();
621 }
622 }
623
624 private boolean isScreenLock(int flags)
625 {
626 int n = flags & LOCK_MASK;
627 return n == PowerManager.FULL_WAKE_LOCK
628 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
629 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
630 }
631
632 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700634 if (uid != Process.myUid()) {
635 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 long ident = Binder.clearCallingIdentity();
638 try {
639 synchronized (mLocks) {
640 acquireWakeLockLocked(flags, lock, uid, tag);
641 }
642 } finally {
643 Binder.restoreCallingIdentity(ident);
644 }
645 }
646
647 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
648 int acquireUid = -1;
649 String acquireName = null;
650 int acquireType = -1;
651
652 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800653 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 }
655
656 int index = mLocks.getIndex(lock);
657 WakeLock wl;
658 boolean newlock;
659 if (index < 0) {
660 wl = new WakeLock(flags, lock, tag, uid);
661 switch (wl.flags & LOCK_MASK)
662 {
663 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500664 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400665 wl.minState = SCREEN_BRIGHT;
666 } else {
667 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 break;
670 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
671 wl.minState = SCREEN_BRIGHT;
672 break;
673 case PowerManager.SCREEN_DIM_WAKE_LOCK:
674 wl.minState = SCREEN_DIM;
675 break;
676 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700677 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 break;
679 default:
680 // just log and bail. we're in the server, so don't
681 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800682 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 + " flags=" + flags);
684 return;
685 }
686 mLocks.addLock(wl);
687 newlock = true;
688 } else {
689 wl = mLocks.get(index);
690 newlock = false;
691 }
692 if (isScreenLock(flags)) {
693 // if this causes a wakeup, we reactivate all of the locks and
694 // set it to whatever they want. otherwise, we modulate that
695 // by the current state so we never turn it more on than
696 // it already is.
697 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700698 int oldWakeLockState = mWakeLockState;
699 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800701 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700702 + " mWakeLockState=0x"
703 + Integer.toHexString(mWakeLockState)
704 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 } else {
707 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800708 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 + " mLocks.gatherState()=0x"
710 + Integer.toHexString(mLocks.gatherState())
711 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
712 }
713 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
714 }
715 setPowerState(mWakeLockState | mUserState);
716 }
717 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
718 if (newlock) {
719 mPartialCount++;
720 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800721 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 }
723 }
724 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700725 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500726 mProximityWakeLockCount++;
727 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700728 enableProximityLockLocked();
729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 }
731 if (newlock) {
732 acquireUid = wl.uid;
733 acquireName = wl.tag;
734 acquireType = wl.monitorType;
735 }
736
737 if (acquireType >= 0) {
738 try {
739 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
740 } catch (RemoteException e) {
741 // Ignore
742 }
743 }
744 }
745
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500746 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700747 int uid = Binder.getCallingUid();
748 if (uid != Process.myUid()) {
749 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751
752 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500753 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 }
755 }
756
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500757 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 int releaseUid;
759 String releaseName;
760 int releaseType;
761
762 WakeLock wl = mLocks.removeLock(lock);
763 if (wl == null) {
764 return;
765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800768 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
770 }
771
772 if (isScreenLock(wl.flags)) {
773 mWakeLockState = mLocks.gatherState();
774 // goes in the middle to reduce flicker
775 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
776 userActivity(SystemClock.uptimeMillis(), false);
777 }
778 setPowerState(mWakeLockState | mUserState);
779 }
780 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
781 mPartialCount--;
782 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800783 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 Power.releaseWakeLock(PARTIAL_NAME);
785 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700786 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500787 mProximityWakeLockCount--;
788 if (mProximityWakeLockCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500789 if (mProximitySensorActive &&
790 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500791 // wait for proximity sensor to go negative before disabling sensor
792 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800793 Slog.d(TAG, "waiting for proximity sensor to go negative");
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500794 }
795 } else {
796 disableProximityLockLocked();
797 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 }
800 // Unlink the lock from the binder.
801 wl.binder.unlinkToDeath(wl, 0);
802 releaseUid = wl.uid;
803 releaseName = wl.tag;
804 releaseType = wl.monitorType;
805
806 if (releaseType >= 0) {
807 long origId = Binder.clearCallingIdentity();
808 try {
809 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
810 } catch (RemoteException e) {
811 // Ignore
812 } finally {
813 Binder.restoreCallingIdentity(origId);
814 }
815 }
816 }
817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 private class PokeLock implements IBinder.DeathRecipient
819 {
820 PokeLock(int p, IBinder b, String t) {
821 super();
822 this.pokey = p;
823 this.binder = b;
824 this.tag = t;
825 try {
826 b.linkToDeath(this, 0);
827 } catch (RemoteException e) {
828 binderDied();
829 }
830 }
831 public void binderDied() {
832 setPokeLock(0, this.binder, this.tag);
833 }
834 int pokey;
835 IBinder binder;
836 String tag;
837 boolean awakeOnSet;
838 }
839
840 public void setPokeLock(int pokey, IBinder token, String tag) {
841 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
842 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800843 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 return;
845 }
846
847 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
848 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
849 + " and POKE_LOCK_MEDIUM_TIMEOUT");
850 }
851
852 synchronized (mLocks) {
853 if (pokey != 0) {
854 PokeLock p = mPokeLocks.get(token);
855 int oldPokey = 0;
856 if (p != null) {
857 oldPokey = p.pokey;
858 p.pokey = pokey;
859 } else {
860 p = new PokeLock(pokey, token, tag);
861 mPokeLocks.put(token, p);
862 }
863 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
864 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
865 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
866 p.awakeOnSet = true;
867 }
868 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700869 PokeLock rLock = mPokeLocks.remove(token);
870 if (rLock != null) {
871 token.unlinkToDeath(rLock, 0);
872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 }
874
875 int oldPokey = mPokey;
876 int cumulative = 0;
877 boolean oldAwakeOnSet = mPokeAwakeOnSet;
878 boolean awakeOnSet = false;
879 for (PokeLock p: mPokeLocks.values()) {
880 cumulative |= p.pokey;
881 if (p.awakeOnSet) {
882 awakeOnSet = true;
883 }
884 }
885 mPokey = cumulative;
886 mPokeAwakeOnSet = awakeOnSet;
887
888 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
889 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 if (oldCumulativeTimeout != newCumulativeTimeout) {
892 setScreenOffTimeoutsLocked();
893 // reset the countdown timer, but use the existing nextState so it doesn't
894 // change anything
895 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
896 }
897 }
898 }
899
900 private static String lockType(int type)
901 {
902 switch (type)
903 {
904 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700905 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700907 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700909 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700911 return "PARTIAL_WAKE_LOCK ";
912 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
913 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 default:
David Brown251faa62009-08-02 22:04:36 -0700915 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
917 }
918
919 private static String dumpPowerState(int state) {
920 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
921 ? "KEYBOARD_BRIGHT_BIT " : "")
922 + (((state & SCREEN_BRIGHT_BIT) != 0)
923 ? "SCREEN_BRIGHT_BIT " : "")
924 + (((state & SCREEN_ON_BIT) != 0)
925 ? "SCREEN_ON_BIT " : "")
926 + (((state & BATTERY_LOW_BIT) != 0)
927 ? "BATTERY_LOW_BIT " : "");
928 }
929
930 @Override
931 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
932 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
933 != PackageManager.PERMISSION_GRANTED) {
934 pw.println("Permission Denial: can't dump PowerManager from from pid="
935 + Binder.getCallingPid()
936 + ", uid=" + Binder.getCallingUid());
937 return;
938 }
939
940 long now = SystemClock.uptimeMillis();
941
Mike Lockwoodca44df82010-02-25 13:48:49 -0500942 synchronized (mLocks) {
943 pw.println("Power Manager State:");
944 pw.println(" mIsPowered=" + mIsPowered
945 + " mPowerState=" + mPowerState
946 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
947 + " ms");
948 pw.println(" mPartialCount=" + mPartialCount);
949 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
950 pw.println(" mUserState=" + dumpPowerState(mUserState));
951 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
952 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
953 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
954 + " " + ((mNextTimeout-now)/1000) + "s from now");
955 pw.println(" mDimScreen=" + mDimScreen
956 + " mStayOnConditions=" + mStayOnConditions);
957 pw.println(" mScreenOffReason=" + mScreenOffReason
958 + " mUserState=" + mUserState);
959 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
960 + ',' + mBroadcastQueue[2] + "}");
961 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
962 + ',' + mBroadcastWhy[2] + "}");
963 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
964 pw.println(" mKeyboardVisible=" + mKeyboardVisible
965 + " mUserActivityAllowed=" + mUserActivityAllowed);
966 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
967 + " mScreenOffDelay=" + mScreenOffDelay);
968 pw.println(" mPreventScreenOn=" + mPreventScreenOn
969 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
970 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
971 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
972 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
973 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
974 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
975 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
976 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
977 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
978 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
979 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
980 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
981 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
982 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
983 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
984 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
985 pw.println(" mLightSensorValue=" + mLightSensorValue
986 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
987 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
988 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
989 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
990 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
991 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
992 mScreenBrightness.dump(pw, " mScreenBrightness: ");
993 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
994 mButtonBrightness.dump(pw, " mButtonBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800995
Mike Lockwoodca44df82010-02-25 13:48:49 -0500996 int N = mLocks.size();
997 pw.println();
998 pw.println("mLocks.size=" + N + ":");
999 for (int i=0; i<N; i++) {
1000 WakeLock wl = mLocks.get(i);
1001 String type = lockType(wl.flags & LOCK_MASK);
1002 String acquireCausesWakeup = "";
1003 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1004 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1005 }
1006 String activated = "";
1007 if (wl.activated) {
1008 activated = " activated";
1009 }
1010 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001011 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1012 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001014
1015 pw.println();
1016 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1017 for (PokeLock p: mPokeLocks.values()) {
1018 pw.println(" poke lock '" + p.tag + "':"
1019 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
1020 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
1021 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
1022 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
1023 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1024 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1025 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1026 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001028
Mike Lockwoodca44df82010-02-25 13:48:49 -05001029 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 }
1032
Joe Onorato7999bff2010-07-24 11:50:05 -04001033 private void setTimeoutLocked(long now, int nextState) {
1034 setTimeoutLocked(now, -1, nextState);
1035 }
1036
1037 // If they gave a timeoutOverride it is the number of seconds
1038 // to screen-off. Figure out where in the countdown cycle we
1039 // should jump to.
1040 private void setTimeoutLocked(long now, long timeoutOverride, int nextState) {
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001041 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001042 synchronized (mLocks) {
1043 mHandler.removeCallbacks(mTimeoutTask);
1044 mTimeoutTask.nextState = nextState;
1045 long when = 0;
1046 if (timeoutOverride <= 0) {
1047 switch (nextState)
1048 {
1049 case SCREEN_BRIGHT:
1050 when = now + mKeylightDelay;
1051 break;
1052 case SCREEN_DIM:
1053 if (mDimDelay >= 0) {
1054 when = now + mDimDelay;
1055 } else {
1056 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1057 }
1058 case SCREEN_OFF:
1059 synchronized (mLocks) {
1060 when = now + mScreenOffDelay;
1061 }
1062 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001064 } else {
1065 override: {
1066 if (timeoutOverride <= mScreenOffDelay) {
1067 when = now + timeoutOverride;
1068 nextState = SCREEN_OFF;
1069 break override;
1070 }
1071 timeoutOverride -= mScreenOffDelay;
1072
1073 if (mDimDelay >= 0) {
1074 if (timeoutOverride <= mDimDelay) {
1075 when = now + timeoutOverride;
1076 nextState = SCREEN_DIM;
1077 break override;
1078 }
1079 timeoutOverride -= mDimDelay;
1080 }
1081
1082 when = now + timeoutOverride;
1083 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001085 }
1086 if (mSpew) {
1087 Slog.d(TAG, "setTimeoutLocked now=" + now
1088 + " timeoutOverride=" + timeoutOverride
1089 + " nextState=" + nextState + " when=" + when);
1090 }
1091 mHandler.postAtTime(mTimeoutTask, when);
1092 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 }
1095 }
1096
1097 private void cancelTimerLocked()
1098 {
1099 mHandler.removeCallbacks(mTimeoutTask);
1100 mTimeoutTask.nextState = -1;
1101 }
1102
1103 private class TimeoutTask implements Runnable
1104 {
1105 int nextState; // access should be synchronized on mLocks
1106 public void run()
1107 {
1108 synchronized (mLocks) {
1109 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001110 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 }
1112
1113 if (nextState == -1) {
1114 return;
1115 }
1116
1117 mUserState = this.nextState;
1118 setPowerState(this.nextState | mWakeLockState);
1119
1120 long now = SystemClock.uptimeMillis();
1121
1122 switch (this.nextState)
1123 {
1124 case SCREEN_BRIGHT:
1125 if (mDimDelay >= 0) {
1126 setTimeoutLocked(now, SCREEN_DIM);
1127 break;
1128 }
1129 case SCREEN_DIM:
1130 setTimeoutLocked(now, SCREEN_OFF);
1131 break;
1132 }
1133 }
1134 }
1135 }
1136
1137 private void sendNotificationLocked(boolean on, int why)
1138 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001139 if (!on) {
1140 mStillNeedSleepNotification = false;
1141 }
1142
Joe Onorato128e7292009-03-24 18:41:31 -07001143 // Add to the queue.
1144 int index = 0;
1145 while (mBroadcastQueue[index] != -1) {
1146 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 }
Joe Onorato128e7292009-03-24 18:41:31 -07001148 mBroadcastQueue[index] = on ? 1 : 0;
1149 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150
Joe Onorato128e7292009-03-24 18:41:31 -07001151 // If we added it position 2, then there is a pair that can be stripped.
1152 // If we added it position 1 and we're turning the screen off, we can strip
1153 // the pair and do nothing, because the screen is already off, and therefore
1154 // keyguard has already been enabled.
1155 // However, if we added it at position 1 and we're turning it on, then position
1156 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1157 // on, so have to run the queue then.
1158 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001159 // While we're collapsing them, if it's going off, and the new reason
1160 // is more significant than the first, then use the new one.
1161 if (!on && mBroadcastWhy[0] > why) {
1162 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001163 }
1164 mBroadcastQueue[0] = on ? 1 : 0;
1165 mBroadcastQueue[1] = -1;
1166 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001167 mBroadcastWakeLock.release();
1168 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001169 index = 0;
1170 }
1171 if (index == 1 && !on) {
1172 mBroadcastQueue[0] = -1;
1173 mBroadcastQueue[1] = -1;
1174 index = -1;
1175 // The wake lock was being held, but we're not actually going to do any
1176 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001177 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001179 }
1180
1181 // Now send the message.
1182 if (index >= 0) {
1183 // Acquire the broadcast wake lock before changing the power
1184 // state. It will be release after the broadcast is sent.
1185 // We always increment the ref count for each notification in the queue
1186 // and always decrement when that notification is handled.
1187 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001188 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001189 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 }
1191 }
1192
1193 private Runnable mNotificationTask = new Runnable()
1194 {
1195 public void run()
1196 {
Joe Onorato128e7292009-03-24 18:41:31 -07001197 while (true) {
1198 int value;
1199 int why;
1200 WindowManagerPolicy policy;
1201 synchronized (mLocks) {
1202 value = mBroadcastQueue[0];
1203 why = mBroadcastWhy[0];
1204 for (int i=0; i<2; i++) {
1205 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1206 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1207 }
1208 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 }
Joe Onorato128e7292009-03-24 18:41:31 -07001210 if (value == 1) {
1211 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001212
Joe Onorato128e7292009-03-24 18:41:31 -07001213 policy.screenTurnedOn();
1214 try {
1215 ActivityManagerNative.getDefault().wakingUp();
1216 } catch (RemoteException e) {
1217 // ignore it
1218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219
Joe Onorato128e7292009-03-24 18:41:31 -07001220 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001221 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001222 }
1223 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1224 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1225 mScreenOnBroadcastDone, mHandler, 0, null, null);
1226 } else {
1227 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001228 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001229 mBroadcastWakeLock.mCount);
1230 mBroadcastWakeLock.release();
1231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233 }
Joe Onorato128e7292009-03-24 18:41:31 -07001234 else if (value == 0) {
1235 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001236
Joe Onorato128e7292009-03-24 18:41:31 -07001237 policy.screenTurnedOff(why);
1238 try {
1239 ActivityManagerNative.getDefault().goingToSleep();
1240 } catch (RemoteException e) {
1241 // ignore it.
1242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243
Joe Onorato128e7292009-03-24 18:41:31 -07001244 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1245 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1246 mScreenOffBroadcastDone, mHandler, 0, null, null);
1247 } else {
1248 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001249 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001250 mBroadcastWakeLock.mCount);
1251 mBroadcastWakeLock.release();
1252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 }
1254 }
Joe Onorato128e7292009-03-24 18:41:31 -07001255 else {
1256 // If we're in this case, then this handler is running for a previous
1257 // paired transaction. mBroadcastWakeLock will already have been released.
1258 break;
1259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 }
1261 }
1262 };
1263
1264 long mScreenOnStart;
1265 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1266 public void onReceive(Context context, Intent intent) {
1267 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001268 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1270 mBroadcastWakeLock.release();
1271 }
1272 }
1273 };
1274
1275 long mScreenOffStart;
1276 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1277 public void onReceive(Context context, Intent intent) {
1278 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001279 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1281 mBroadcastWakeLock.release();
1282 }
1283 }
1284 };
1285
1286 void logPointerUpEvent() {
1287 if (LOG_TOUCH_DOWNS) {
1288 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1289 mLastTouchDown = 0;
1290 }
1291 }
1292
1293 void logPointerDownEvent() {
1294 if (LOG_TOUCH_DOWNS) {
1295 // If we are not already timing a down/up sequence
1296 if (mLastTouchDown == 0) {
1297 mLastTouchDown = SystemClock.elapsedRealtime();
1298 mTouchCycles++;
1299 }
1300 }
1301 }
1302
1303 /**
1304 * Prevents the screen from turning on even if it *should* turn on due
1305 * to a subsequent full wake lock being acquired.
1306 * <p>
1307 * This is a temporary hack that allows an activity to "cover up" any
1308 * display glitches that happen during the activity's startup
1309 * sequence. (Specifically, this API was added to work around a
1310 * cosmetic bug in the "incoming call" sequence, where the lock screen
1311 * would flicker briefly before the incoming call UI became visible.)
1312 * TODO: There ought to be a more elegant way of doing this,
1313 * probably by having the PowerManager and ActivityManager
1314 * work together to let apps specify that the screen on/off
1315 * state should be synchronized with the Activity lifecycle.
1316 * <p>
1317 * Note that calling preventScreenOn(true) will NOT turn the screen
1318 * off if it's currently on. (This API only affects *future*
1319 * acquisitions of full wake locks.)
1320 * But calling preventScreenOn(false) WILL turn the screen on if
1321 * it's currently off because of a prior preventScreenOn(true) call.
1322 * <p>
1323 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1324 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1325 * call doesn't occur within 5 seconds, we'll turn the screen back on
1326 * ourselves (and log a warning about it); this prevents a buggy app
1327 * from disabling the screen forever.)
1328 * <p>
1329 * TODO: this feature should really be controlled by a new type of poke
1330 * lock (rather than an IPowerManager call).
1331 */
1332 public void preventScreenOn(boolean prevent) {
1333 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1334
1335 synchronized (mLocks) {
1336 if (prevent) {
1337 // First of all, grab a partial wake lock to
1338 // make sure the CPU stays on during the entire
1339 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1340 mPreventScreenOnPartialLock.acquire();
1341
1342 // Post a forceReenableScreen() call (for 5 seconds in the
1343 // future) to make sure the matching preventScreenOn(false) call
1344 // has happened by then.
1345 mHandler.removeCallbacks(mForceReenableScreenTask);
1346 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1347
1348 // Finally, set the flag that prevents the screen from turning on.
1349 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001350 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 mPreventScreenOn = true;
1352 } else {
1353 // (Re)enable the screen.
1354 mPreventScreenOn = false;
1355
1356 // We're "undoing" a the prior preventScreenOn(true) call, so we
1357 // no longer need the 5-second safeguard.
1358 mHandler.removeCallbacks(mForceReenableScreenTask);
1359
1360 // Forcibly turn on the screen if it's supposed to be on. (This
1361 // handles the case where the screen is currently off because of
1362 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001363 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001365 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1367 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001368 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001370 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 }
1372 }
1373
1374 // Release the partial wake lock that we held during the
1375 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1376 mPreventScreenOnPartialLock.release();
1377 }
1378 }
1379 }
1380
1381 public void setScreenBrightnessOverride(int brightness) {
1382 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1383
Mike Lockwoodf527c712010-06-10 14:12:33 -04001384 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 synchronized (mLocks) {
1386 if (mScreenBrightnessOverride != brightness) {
1387 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001388 if (isScreenOn()) {
1389 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 }
1392 }
1393 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001394
1395 public void setButtonBrightnessOverride(int brightness) {
1396 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1397
Mike Lockwoodf527c712010-06-10 14:12:33 -04001398 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001399 synchronized (mLocks) {
1400 if (mButtonBrightnessOverride != brightness) {
1401 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001402 if (isScreenOn()) {
1403 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1404 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001405 }
1406 }
1407 }
1408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 /**
1410 * Sanity-check that gets called 5 seconds after any call to
1411 * preventScreenOn(true). This ensures that the original call
1412 * is followed promptly by a call to preventScreenOn(false).
1413 */
1414 private void forceReenableScreen() {
1415 // We shouldn't get here at all if mPreventScreenOn is false, since
1416 // we should have already removed any existing
1417 // mForceReenableScreenTask messages...
1418 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001419 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 return;
1421 }
1422
1423 // Uh oh. It's been 5 seconds since a call to
1424 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1425 // This means the app that called preventScreenOn(true) is either
1426 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1427 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1428 // crashed before doing so.)
1429
1430 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001431 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 + "Forcing the screen back on...");
1433 preventScreenOn(false);
1434 }
1435
1436 private Runnable mForceReenableScreenTask = new Runnable() {
1437 public void run() {
1438 forceReenableScreen();
1439 }
1440 };
1441
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001442 private int setScreenStateLocked(boolean on) {
1443 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001444 if (err == 0) {
1445 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1446 if (mUseSoftwareAutoBrightness) {
1447 enableLightSensor(on);
1448 if (!on) {
1449 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001450 mButtonLight.turnOff();
1451 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001452 // clear current value so we will update based on the new conditions
1453 // when the sensor is reenabled.
1454 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001455 // reset our highest light sensor value when the screen turns off
1456 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001457 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001458 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001459 }
1460 return err;
1461 }
1462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 private void setPowerState(int state)
1464 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001465 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 }
1467
Mike Lockwood435eb642009-12-03 08:40:18 -05001468 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 {
1470 synchronized (mLocks) {
1471 int err;
1472
1473 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001474 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001476 + " noChangeLights=" + noChangeLights
1477 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 }
1479
1480 if (noChangeLights) {
1481 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1482 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001483 if (mProximitySensorActive) {
1484 // don't turn on the screen when the proximity sensor lock is held
1485 newState = (newState & ~SCREEN_BRIGHT);
1486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487
1488 if (batteryIsLow()) {
1489 newState |= BATTERY_LOW_BIT;
1490 } else {
1491 newState &= ~BATTERY_LOW_BIT;
1492 }
1493 if (newState == mPowerState) {
1494 return;
1495 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001496
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001497 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 newState |= ALL_BRIGHT;
1499 }
1500
1501 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1502 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1503
Mike Lockwood51b844962009-11-16 21:51:18 -05001504 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001505 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001507 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001509 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001511 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001513 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001515 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1517 }
1518
1519 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001520 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1522 }
1523
1524 if (oldScreenOn != newScreenOn) {
1525 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001526 // When the user presses the power button, we need to always send out the
1527 // notification that it's going to sleep so the keyguard goes on. But
1528 // we can't do that until the screen fades out, so we don't show the keyguard
1529 // too early.
1530 if (mStillNeedSleepNotification) {
1531 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1532 }
1533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 // Turn on the screen UNLESS there was a prior
1535 // preventScreenOn(true) request. (Note that the lifetime
1536 // of a single preventScreenOn() request is limited to 5
1537 // seconds to prevent a buggy app from disabling the
1538 // screen forever; see forceReenableScreen().)
1539 boolean reallyTurnScreenOn = true;
1540 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001541 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 + mPreventScreenOn);
1543 }
1544
1545 if (mPreventScreenOn) {
1546 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001547 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 }
1549 reallyTurnScreenOn = false;
1550 }
1551 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001552 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 long identity = Binder.clearCallingIdentity();
1554 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001555 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 mBatteryStats.noteScreenOn();
1557 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001558 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 } finally {
1560 Binder.restoreCallingIdentity(identity);
1561 }
1562 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001563 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 // But continue as if we really did turn the screen on...
1565 err = 0;
1566 }
1567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 mLastTouchDown = 0;
1569 mTotalTouchDownTime = 0;
1570 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001571 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 mTotalTouchDownTime, mTouchCycles);
1573 if (err == 0) {
1574 mPowerState |= SCREEN_ON_BIT;
1575 sendNotificationLocked(true, -1);
1576 }
1577 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001578 // cancel light sensor task
1579 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 mScreenOffTime = SystemClock.elapsedRealtime();
1581 long identity = Binder.clearCallingIdentity();
1582 try {
1583 mBatteryStats.noteScreenOff();
1584 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001585 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 } finally {
1587 Binder.restoreCallingIdentity(identity);
1588 }
1589 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001590 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001592 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 err = 0;
1595 mLastTouchDown = 0;
1596 }
1597 }
1598 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001599
1600 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 }
1602 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001603
1604 private void updateNativePowerStateLocked() {
1605 nativeSetPowerState(
1606 (mPowerState & SCREEN_ON_BIT) != 0,
1607 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1608 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001609
Mike Lockwood435eb642009-12-03 08:40:18 -05001610 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001612 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001614 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001616 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001618 mScreenOffReason = reason;
1619 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 }
1621 return err;
1622 }
1623
1624 private boolean batteryIsLow() {
1625 return (!mIsPowered &&
1626 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1627 }
1628
The Android Open Source Project10592532009-03-18 17:39:46 -07001629 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001630 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001631 newState = applyButtonState(newState);
1632 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001633 final int realDifference = (newState ^ oldState);
1634 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001636 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 int offMask = 0;
1640 int dimMask = 0;
1641 int onMask = 0;
1642
1643 int preferredBrightness = getPreferredBrightness();
1644 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1647 if (ANIMATE_KEYBOARD_LIGHTS) {
1648 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1649 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001650 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001651 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001653 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001654 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1655 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 }
1657 startAnimation = true;
1658 } else {
1659 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001660 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001662 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 }
1664 }
1665 }
1666
1667 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1668 if (ANIMATE_BUTTON_LIGHTS) {
1669 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1670 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001671 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001672 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001674 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001675 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1676 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 }
1678 startAnimation = true;
1679 } else {
1680 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001681 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001683 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 }
1685 }
1686 }
1687
1688 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1689 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001690 int nominalCurrentValue = -1;
1691 // If there was an actual difference in the light state, then
1692 // figure out the "ideal" current value based on the previous
1693 // state. Otherwise, this is a change due to the brightness
1694 // override, so we want to animate from whatever the current
1695 // value is.
1696 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1697 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1698 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1699 nominalCurrentValue = preferredBrightness;
1700 break;
1701 case SCREEN_ON_BIT:
1702 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1703 break;
1704 case 0:
1705 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1706 break;
1707 case SCREEN_BRIGHT_BIT:
1708 default:
1709 // not possible
1710 nominalCurrentValue = (int)mScreenBrightness.curValue;
1711 break;
1712 }
Joe Onorato128e7292009-03-24 18:41:31 -07001713 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001714 int brightness = preferredBrightness;
1715 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1717 // dim or turn off backlight, depending on if the screen is on
1718 // the scale is because the brightness ramp isn't linear and this biases
1719 // it so the later parts take longer.
1720 final float scale = 1.5f;
1721 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1722 if (ratio > 1.0f) ratio = 1.0f;
1723 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1725 // was bright
1726 steps = ANIM_STEPS;
1727 } else {
1728 // was dim
1729 steps = (int)(ANIM_STEPS*ratio*scale);
1730 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001731 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 if ((oldState & SCREEN_ON_BIT) != 0) {
1734 // was bright
1735 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1736 } else {
1737 // was dim
1738 steps = (int)(ANIM_STEPS*ratio);
1739 }
1740 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1741 // If the "stay on while plugged in" option is
1742 // turned on, then the screen will often not
1743 // automatically turn off while plugged in. To
1744 // still have a sense of when it is inactive, we
1745 // will then count going dim as turning off.
1746 mScreenOffTime = SystemClock.elapsedRealtime();
1747 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001748 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001751 long identity = Binder.clearCallingIdentity();
1752 try {
1753 mBatteryStats.noteScreenBrightness(brightness);
1754 } catch (RemoteException e) {
1755 // Nothing interesting to do.
1756 } finally {
1757 Binder.restoreCallingIdentity(identity);
1758 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001759 if (mScreenBrightness.setTargetLocked(brightness,
1760 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1761 startAnimation = true;
1762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 } else {
1764 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1765 // dim or turn off backlight, depending on if the screen is on
1766 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001767 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001769 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 }
1771 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001772 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 }
1774 }
1775 }
1776
1777 if (startAnimation) {
1778 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001779 Slog.i(TAG, "Scheduling light animator!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 }
1781 mHandler.removeCallbacks(mLightAnimator);
1782 mHandler.post(mLightAnimator);
1783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001786 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001787 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 }
1789 if (dimMask != 0) {
1790 int brightness = Power.BRIGHTNESS_DIM;
1791 if ((newState & BATTERY_LOW_BIT) != 0 &&
1792 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1793 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1794 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001795 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001796 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 }
1798 if (onMask != 0) {
1799 int brightness = getPreferredBrightness();
1800 if ((newState & BATTERY_LOW_BIT) != 0 &&
1801 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1802 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1803 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001804 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001805 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808
The Android Open Source Project10592532009-03-18 17:39:46 -07001809 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001810 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001811 ? LightsService.BRIGHTNESS_MODE_SENSOR
1812 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001813 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001814 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001815 }
1816 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001817 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001818 }
1819 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001820 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
1823
1824 class BrightnessState {
1825 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 boolean initialized;
1828 int targetValue;
1829 float curValue;
1830 float delta;
1831 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 BrightnessState(int m) {
1834 mask = m;
1835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 public void dump(PrintWriter pw, String prefix) {
1838 pw.println(prefix + "animating=" + animating
1839 + " targetValue=" + targetValue
1840 + " curValue=" + curValue
1841 + " delta=" + delta);
1842 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001843
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001844 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001845 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 if (!initialized) {
1847 initialized = true;
1848 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001849 } else if (targetValue == target) {
1850 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 }
1852 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001853 delta = (targetValue -
1854 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1855 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001857 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato8a9b2202010-02-26 18:56:32 -08001858 Slog.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001859 + " target=" + targetValue + " delta=" + delta
1860 + " nominalCurrentValue=" + nominalCurrentValue
1861 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 }
1863 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001864 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 boolean stepLocked() {
1868 if (!animating) return false;
1869 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001870 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 + " target=" + targetValue + " delta=" + delta);
1872 }
1873 curValue += delta;
1874 int curIntValue = (int)curValue;
1875 boolean more = true;
1876 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001877 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 more = false;
1879 } else if (delta > 0) {
1880 if (curIntValue >= targetValue) {
1881 curValue = curIntValue = targetValue;
1882 more = false;
1883 }
1884 } else {
1885 if (curIntValue <= targetValue) {
1886 curValue = curIntValue = targetValue;
1887 more = false;
1888 }
1889 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001890 //Slog.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001891 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 animating = more;
1893 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001894 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001895 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 }
1897 }
1898 return more;
1899 }
1900 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 private class LightAnimator implements Runnable {
1903 public void run() {
1904 synchronized (mLocks) {
1905 long now = SystemClock.uptimeMillis();
1906 boolean more = mScreenBrightness.stepLocked();
1907 if (mKeyboardBrightness.stepLocked()) {
1908 more = true;
1909 }
1910 if (mButtonBrightness.stepLocked()) {
1911 more = true;
1912 }
1913 if (more) {
1914 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1915 }
1916 }
1917 }
1918 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 private int getPreferredBrightness() {
1921 try {
1922 if (mScreenBrightnessOverride >= 0) {
1923 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001924 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001925 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001926 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 }
1928 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1929 SCREEN_BRIGHTNESS);
1930 // Don't let applications turn the screen all the way off
1931 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1932 } catch (SettingNotFoundException snfe) {
1933 return Power.BRIGHTNESS_ON;
1934 }
1935 }
1936
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001937 private int applyButtonState(int state) {
1938 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04001939 if ((state & BATTERY_LOW_BIT) != 0) {
1940 // do not override brightness if the battery is low
1941 return state;
1942 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001943 if (mButtonBrightnessOverride >= 0) {
1944 brightness = mButtonBrightnessOverride;
1945 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
1946 brightness = mLightSensorButtonBrightness;
1947 }
1948 if (brightness > 0) {
1949 return state | BUTTON_BRIGHT_BIT;
1950 } else if (brightness == 0) {
1951 return state & ~BUTTON_BRIGHT_BIT;
1952 } else {
1953 return state;
1954 }
1955 }
1956
1957 private int applyKeyboardState(int state) {
1958 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04001959 if ((state & BATTERY_LOW_BIT) != 0) {
1960 // do not override brightness if the battery is low
1961 return state;
1962 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001963 if (!mKeyboardVisible) {
1964 brightness = 0;
1965 } else if (mButtonBrightnessOverride >= 0) {
1966 brightness = mButtonBrightnessOverride;
1967 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
1968 brightness = mLightSensorKeyboardBrightness;
1969 }
1970 if (brightness > 0) {
1971 return state | KEYBOARD_BRIGHT_BIT;
1972 } else if (brightness == 0) {
1973 return state & ~KEYBOARD_BRIGHT_BIT;
1974 } else {
1975 return state;
1976 }
1977 }
1978
Charles Mendis322591c2009-10-29 11:06:59 -07001979 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 synchronized (mLocks) {
1981 return (mPowerState & SCREEN_ON_BIT) != 0;
1982 }
1983 }
1984
Charles Mendis322591c2009-10-29 11:06:59 -07001985 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 synchronized (mLocks) {
1987 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1988 }
1989 }
1990
Mike Lockwood497087e32009-11-08 18:33:03 -05001991 private boolean isScreenTurningOffLocked() {
1992 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1993 }
1994
Mike Lockwood200b30b2009-09-20 00:23:59 -04001995 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05001996 if (isScreenTurningOffLocked()) {
1997 // cancel animation so userActivity will succeed
1998 mScreenBrightness.animating = false;
1999 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002000 boolean savedActivityAllowed = mUserActivityAllowed;
2001 mUserActivityAllowed = true;
2002 userActivity(SystemClock.uptimeMillis(), false);
2003 mUserActivityAllowed = savedActivityAllowed;
2004 }
2005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2007 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002008 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 }
2010
2011 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002012 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 }
2014
2015 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002016 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 }
2018
2019 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002020 userActivity(time, -1, noChangeLights, eventType, force);
2021 }
2022
2023 /*
2024 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2025 * on with user activity. Don't use this function.
2026 */
2027 public void clearUserActivityTimeout(long now, long timeout) {
2028 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2029 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2030 userActivity(now, timeout, false, OTHER_EVENT, false);
2031 }
2032
2033 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2034 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2036
2037 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002038 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002040 Slog.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 }
2042 return;
2043 }
2044
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002045 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
2046 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
2047 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
2048 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002049 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002050 }
2051 return;
2052 }
2053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 if (false) {
2055 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002056 Slog.d(TAG, "userActivity !!!");//, new RuntimeException());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002058 Slog.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 }
2060 }
2061
2062 synchronized (mLocks) {
2063 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002064 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 + " mUserActivityAllowed=" + mUserActivityAllowed
2066 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002067 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2068 + " mProximitySensorActive=" + mProximitySensorActive
2069 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 }
Mike Lockwood05067122009-10-27 23:07:25 -04002071 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002072 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002073 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002074 return;
2075 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002076 // Disable proximity sensor if if user presses power key while we are in the
2077 // "waiting for proximity sensor to go negative" state.
2078 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2079 mProximitySensorActive = false;
2080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 if (mLastEventTime <= time || force) {
2082 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002083 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002084 // Only turn on button backlights if a button was pressed
2085 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002086 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2088 } else {
2089 // don't clear button/keyboard backlights when the screen is touched.
2090 mUserState |= SCREEN_BRIGHT;
2091 }
2092
Dianne Hackborn617f8772009-03-31 15:04:46 -07002093 int uid = Binder.getCallingUid();
2094 long ident = Binder.clearCallingIdentity();
2095 try {
2096 mBatteryStats.noteUserActivity(uid, eventType);
2097 } catch (RemoteException e) {
2098 // Ignore
2099 } finally {
2100 Binder.restoreCallingIdentity(ident);
2101 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002102
Michael Chane96440f2009-05-06 10:27:36 -07002103 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002104 setPowerState(mUserState | mWakeLockState, noChangeLights,
2105 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002106 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 }
2108 }
2109 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002110
2111 if (mPolicy != null) {
2112 mPolicy.userActivity();
2113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 }
2115
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002116 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2117 try {
2118 int i;
2119 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2120 if (sensorValue < mAutoBrightnessLevels[i]) {
2121 break;
2122 }
2123 }
2124 return values[i];
2125 } catch (Exception e) {
2126 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002127 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002128 return 255;
2129 }
2130 }
2131
Mike Lockwood20f87d72009-11-05 16:08:51 -05002132 private Runnable mProximityTask = new Runnable() {
2133 public void run() {
2134 synchronized (mLocks) {
2135 if (mProximityPendingValue != -1) {
2136 proximityChangedLocked(mProximityPendingValue == 1);
2137 mProximityPendingValue = -1;
2138 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002139 if (mProximityPartialLock.isHeld()) {
2140 mProximityPartialLock.release();
2141 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002142 }
2143 }
2144 };
2145
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002146 private Runnable mAutoBrightnessTask = new Runnable() {
2147 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002148 synchronized (mLocks) {
2149 int value = (int)mLightSensorPendingValue;
2150 if (value >= 0) {
2151 mLightSensorPendingValue = -1;
2152 lightSensorChangedLocked(value);
2153 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002154 }
2155 }
2156 };
2157
Mike Lockwoodb2865412010-02-02 22:40:33 -05002158 private void dockStateChanged(int state) {
2159 synchronized (mLocks) {
2160 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2161 if (mIsDocked) {
2162 mHighestLightSensorValue = -1;
2163 }
2164 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2165 // force lights recalculation
2166 int value = (int)mLightSensorValue;
2167 mLightSensorValue = -1;
2168 lightSensorChangedLocked(value);
2169 }
2170 }
2171 }
2172
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002173 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002174 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002175 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002176 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002177
Mike Lockwoodb2865412010-02-02 22:40:33 -05002178 // do not allow light sensor value to decrease
2179 if (mHighestLightSensorValue < value) {
2180 mHighestLightSensorValue = value;
2181 }
2182
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002183 if (mLightSensorValue != value) {
2184 mLightSensorValue = value;
2185 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002186 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2187 // we only do this if we are undocked, since lighting should be stable when
2188 // stationary in a dock.
2189 int lcdValue = getAutoBrightnessValue(
2190 (mIsDocked ? value : mHighestLightSensorValue),
2191 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002192 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002193 int keyboardValue;
2194 if (mKeyboardVisible) {
2195 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2196 } else {
2197 keyboardValue = 0;
2198 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002199 mLightSensorScreenBrightness = lcdValue;
2200 mLightSensorButtonBrightness = buttonValue;
2201 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002202
2203 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002204 Slog.d(TAG, "lcdValue " + lcdValue);
2205 Slog.d(TAG, "buttonValue " + buttonValue);
2206 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002207 }
2208
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002209 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002210 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002211 if (ANIMATE_SCREEN_LIGHTS) {
2212 if (mScreenBrightness.setTargetLocked(lcdValue,
2213 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2214 (int)mScreenBrightness.curValue)) {
2215 startAnimation = true;
2216 }
2217 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002218 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002219 ? LightsService.BRIGHTNESS_MODE_SENSOR
2220 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002221 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002222 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002223 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002224 if (mButtonBrightnessOverride < 0) {
2225 if (ANIMATE_BUTTON_LIGHTS) {
2226 if (mButtonBrightness.setTargetLocked(buttonValue,
2227 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2228 (int)mButtonBrightness.curValue)) {
2229 startAnimation = true;
2230 }
2231 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002232 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002233 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002234 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002235 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2236 if (ANIMATE_KEYBOARD_LIGHTS) {
2237 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2238 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2239 (int)mKeyboardBrightness.curValue)) {
2240 startAnimation = true;
2241 }
2242 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002243 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002244 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002245 }
2246 if (startAnimation) {
2247 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002248 Slog.i(TAG, "lightSensorChangedLocked scheduling light animator");
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002249 }
2250 mHandler.removeCallbacks(mLightAnimator);
2251 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002252 }
2253 }
2254 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002255 }
2256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257 /**
2258 * The user requested that we go to sleep (probably with the power button).
2259 * This overrides all wake locks that are held.
2260 */
2261 public void goToSleep(long time)
2262 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002263 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2264 }
2265
2266 /**
2267 * The user requested that we go to sleep (probably with the power button).
2268 * This overrides all wake locks that are held.
2269 */
2270 public void goToSleepWithReason(long time, int reason)
2271 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2273 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002274 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 }
2276 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002278 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002279 * Reboot the device immediately, passing 'reason' (may be null)
2280 * to the underlying __reboot system call. Should not return.
2281 */
2282 public void reboot(String reason)
2283 {
2284 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002285
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002286 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2287 throw new IllegalStateException("Too early to call reboot()");
2288 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002289
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002290 final String finalReason = reason;
2291 Runnable runnable = new Runnable() {
2292 public void run() {
2293 synchronized (this) {
2294 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002295 }
2296
San Mehat1e512792010-01-07 10:40:29 -08002297 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002298 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002299 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002300 mHandler.post(runnable);
2301
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002302 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002303 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002304 while (true) {
2305 try {
2306 runnable.wait();
2307 } catch (InterruptedException e) {
2308 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002309 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002310 }
2311 }
2312
Dan Egnor60d87622009-12-16 16:32:58 -08002313 /**
2314 * Crash the runtime (causing a complete restart of the Android framework).
2315 * Requires REBOOT permission. Mostly for testing. Should not return.
2316 */
2317 public void crash(final String message)
2318 {
2319 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2320 Thread t = new Thread("PowerManagerService.crash()") {
2321 public void run() { throw new RuntimeException(message); }
2322 };
2323 try {
2324 t.start();
2325 t.join();
2326 } catch (InterruptedException e) {
2327 Log.wtf(TAG, e);
2328 }
2329 }
2330
Mike Lockwood435eb642009-12-03 08:40:18 -05002331 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332
2333 if (mLastEventTime <= time) {
2334 mLastEventTime = time;
2335 // cancel all of the wake locks
2336 mWakeLockState = SCREEN_OFF;
2337 int N = mLocks.size();
2338 int numCleared = 0;
2339 for (int i=0; i<N; i++) {
2340 WakeLock wl = mLocks.get(i);
2341 if (isScreenLock(wl.flags)) {
2342 mLocks.get(i).activated = false;
2343 numCleared++;
2344 }
2345 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002346 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002347 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002349 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002350 cancelTimerLocked();
2351 }
2352 }
2353
2354 public long timeSinceScreenOn() {
2355 synchronized (mLocks) {
2356 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2357 return 0;
2358 }
2359 return SystemClock.elapsedRealtime() - mScreenOffTime;
2360 }
2361 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002364 synchronized (mLocks) {
2365 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002366 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002367 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002368 if (mKeyboardVisible != visible) {
2369 mKeyboardVisible = visible;
2370 // don't signal user activity if the screen is off; other code
2371 // will take care of turning on due to a true change to the lid
2372 // switch and synchronized with the lock screen.
2373 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002374 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002375 // force recompute of backlight values
2376 if (mLightSensorValue >= 0) {
2377 int value = (int)mLightSensorValue;
2378 mLightSensorValue = -1;
2379 lightSensorChangedLocked(value);
2380 }
2381 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002382 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2383 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002384 }
2385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 }
2387
2388 /**
2389 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002390 * When disabling user activity we also reset user power state so the keyguard can reset its
2391 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 */
2393 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002394 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002395 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 synchronized (mLocks) {
2398 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002399 if (!enabled) {
2400 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2401 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 }
2404 }
2405
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002406 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002407 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002408 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002409 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002410 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002411 // force recompute of backlight values
2412 if (mLightSensorValue >= 0) {
2413 int value = (int)mLightSensorValue;
2414 mLightSensorValue = -1;
2415 lightSensorChangedLocked(value);
2416 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002417 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002418 }
2419 }
2420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 /** Sets the screen off timeouts:
2422 * mKeylightDelay
2423 * mDimDelay
2424 * mScreenOffDelay
2425 * */
2426 private void setScreenOffTimeoutsLocked() {
2427 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002428 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 mDimDelay = -1;
2430 mScreenOffDelay = 0;
2431 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2432 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2433 mDimDelay = -1;
2434 mScreenOffDelay = 0;
2435 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002436 int totalDelay = mScreenOffTimeoutSetting;
2437 if (totalDelay > mMaximumScreenOffTimeout) {
2438 totalDelay = mMaximumScreenOffTimeout;
2439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2441 if (totalDelay < 0) {
2442 mScreenOffDelay = Integer.MAX_VALUE;
2443 } else if (mKeylightDelay < totalDelay) {
2444 // subtract the time that the keylight delay. This will give us the
2445 // remainder of the time that we need to sleep to get the accurate
2446 // screen off timeout.
2447 mScreenOffDelay = totalDelay - mKeylightDelay;
2448 } else {
2449 mScreenOffDelay = 0;
2450 }
2451 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2452 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2453 mScreenOffDelay = LONG_DIM_TIME;
2454 } else {
2455 mDimDelay = -1;
2456 }
2457 }
2458 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002459 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2461 + " mDimScreen=" + mDimScreen);
2462 }
2463 }
2464
2465 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002466 * Refreshes cached secure settings. Called once on startup, and
2467 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 */
Doug Zongker43866e02010-01-07 12:09:54 -08002469 private void updateSettingsValues() {
2470 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002472 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002474 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 }
2476
2477 private class LockList extends ArrayList<WakeLock>
2478 {
2479 void addLock(WakeLock wl)
2480 {
2481 int index = getIndex(wl.binder);
2482 if (index < 0) {
2483 this.add(wl);
2484 }
2485 }
2486
2487 WakeLock removeLock(IBinder binder)
2488 {
2489 int index = getIndex(binder);
2490 if (index >= 0) {
2491 return this.remove(index);
2492 } else {
2493 return null;
2494 }
2495 }
2496
2497 int getIndex(IBinder binder)
2498 {
2499 int N = this.size();
2500 for (int i=0; i<N; i++) {
2501 if (this.get(i).binder == binder) {
2502 return i;
2503 }
2504 }
2505 return -1;
2506 }
2507
2508 int gatherState()
2509 {
2510 int result = 0;
2511 int N = this.size();
2512 for (int i=0; i<N; i++) {
2513 WakeLock wl = this.get(i);
2514 if (wl.activated) {
2515 if (isScreenLock(wl.flags)) {
2516 result |= wl.minState;
2517 }
2518 }
2519 }
2520 return result;
2521 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002522
Michael Chane96440f2009-05-06 10:27:36 -07002523 int reactivateScreenLocksLocked()
2524 {
2525 int result = 0;
2526 int N = this.size();
2527 for (int i=0; i<N; i++) {
2528 WakeLock wl = this.get(i);
2529 if (isScreenLock(wl.flags)) {
2530 wl.activated = true;
2531 result |= wl.minState;
2532 }
2533 }
2534 return result;
2535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 }
2537
2538 void setPolicy(WindowManagerPolicy p) {
2539 synchronized (mLocks) {
2540 mPolicy = p;
2541 mLocks.notifyAll();
2542 }
2543 }
2544
2545 WindowManagerPolicy getPolicyLocked() {
2546 while (mPolicy == null || !mDoneBooting) {
2547 try {
2548 mLocks.wait();
2549 } catch (InterruptedException e) {
2550 // Ignore
2551 }
2552 }
2553 return mPolicy;
2554 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002557 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2558 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2559 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002560 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002561 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002562 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002563 }
2564
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002565 // wait until sensors are enabled before turning on screen.
2566 // some devices will not activate the light sensor properly on boot
2567 // unless we do this.
2568 if (mUseSoftwareAutoBrightness) {
2569 // turn the screen on
2570 setPowerState(SCREEN_BRIGHT);
2571 } else {
2572 // turn everything on
2573 setPowerState(ALL_BRIGHT);
2574 }
2575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002577 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002579
Dianne Hackborn617f8772009-03-31 15:04:46 -07002580 long identity = Binder.clearCallingIdentity();
2581 try {
2582 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2583 mBatteryStats.noteScreenOn();
2584 } catch (RemoteException e) {
2585 // Nothing interesting to do.
2586 } finally {
2587 Binder.restoreCallingIdentity(identity);
2588 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002589 }
2590 }
2591
2592 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002593 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002594 synchronized (mLocks) {
2595 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2597 updateWakeLockLocked();
2598 mLocks.notifyAll();
2599 }
2600 }
2601
2602 public void monitor() {
2603 synchronized (mLocks) { }
2604 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002605
2606 public int getSupportedWakeLockFlags() {
2607 int result = PowerManager.PARTIAL_WAKE_LOCK
2608 | PowerManager.FULL_WAKE_LOCK
2609 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2610
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002611 if (mProximitySensor != null) {
2612 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2613 }
2614
2615 return result;
2616 }
2617
Mike Lockwood237a2992009-09-15 14:42:16 -04002618 public void setBacklightBrightness(int brightness) {
2619 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2620 // Don't let applications turn the screen all the way off
2621 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002622 mLcdLight.setBrightness(brightness);
2623 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2624 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002625 long identity = Binder.clearCallingIdentity();
2626 try {
2627 mBatteryStats.noteScreenBrightness(brightness);
2628 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002629 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
Mike Lockwood237a2992009-09-15 14:42:16 -04002630 } finally {
2631 Binder.restoreCallingIdentity(identity);
2632 }
2633
2634 // update our animation state
2635 if (ANIMATE_SCREEN_LIGHTS) {
2636 mScreenBrightness.curValue = brightness;
2637 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002638 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002639 }
2640 if (ANIMATE_KEYBOARD_LIGHTS) {
2641 mKeyboardBrightness.curValue = brightness;
2642 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002643 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002644 }
2645 if (ANIMATE_BUTTON_LIGHTS) {
2646 mButtonBrightness.curValue = brightness;
2647 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002648 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002649 }
2650 }
2651
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002652 public void setAttentionLight(boolean on, int color) {
2653 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002654 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002655 }
2656
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002657 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002658 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002659 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002660 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002661 if (!mProximitySensorEnabled) {
2662 // clear calling identity so sensor manager battery stats are accurate
2663 long identity = Binder.clearCallingIdentity();
2664 try {
2665 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2666 SensorManager.SENSOR_DELAY_NORMAL);
2667 mProximitySensorEnabled = true;
2668 } finally {
2669 Binder.restoreCallingIdentity(identity);
2670 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002671 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002672 }
2673
2674 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002675 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002676 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002677 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002678 if (mProximitySensorEnabled) {
2679 // clear calling identity so sensor manager battery stats are accurate
2680 long identity = Binder.clearCallingIdentity();
2681 try {
2682 mSensorManager.unregisterListener(mProximityListener);
2683 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002684 if (mProximityPartialLock.isHeld()) {
2685 mProximityPartialLock.release();
2686 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002687 mProximitySensorEnabled = false;
2688 } finally {
2689 Binder.restoreCallingIdentity(identity);
2690 }
2691 if (mProximitySensorActive) {
2692 mProximitySensorActive = false;
2693 forceUserActivityLocked();
2694 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002695 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002696 }
2697
Mike Lockwood20f87d72009-11-05 16:08:51 -05002698 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002699 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002700 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002701 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002702 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002703 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002704 return;
2705 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002706 if (active) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002707 goToSleepLocked(SystemClock.uptimeMillis(),
2708 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002709 mProximitySensorActive = true;
2710 } else {
2711 // proximity sensor negative events trigger as user activity.
2712 // temporarily set mUserActivityAllowed to true so this will work
2713 // even when the keyguard is on.
2714 mProximitySensorActive = false;
2715 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002716
2717 if (mProximityWakeLockCount == 0) {
2718 // disable sensor if we have no listeners left after proximity negative
2719 disableProximityLockLocked();
2720 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002721 }
2722 }
2723
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002724 private void enableLightSensor(boolean enable) {
2725 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002726 Slog.d(TAG, "enableLightSensor " + enable);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002727 }
2728 if (mSensorManager != null && mLightSensorEnabled != enable) {
2729 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002730 // clear calling identity so sensor manager battery stats are accurate
2731 long identity = Binder.clearCallingIdentity();
2732 try {
2733 if (enable) {
2734 mSensorManager.registerListener(mLightListener, mLightSensor,
2735 SensorManager.SENSOR_DELAY_NORMAL);
2736 } else {
2737 mSensorManager.unregisterListener(mLightListener);
2738 mHandler.removeCallbacks(mAutoBrightnessTask);
2739 }
2740 } finally {
2741 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002742 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002743 }
2744 }
2745
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002746 SensorEventListener mProximityListener = new SensorEventListener() {
2747 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002748 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002749 synchronized (mLocks) {
2750 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002751 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2752 mLastProximityEventTime = milliseconds;
2753 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002754 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002755
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002756 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002757 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2758 distance < mProximitySensor.getMaximumRange());
2759
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002760 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002761 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002762 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002763 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2764 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2765 mProximityPendingValue = (active ? 1 : 0);
2766 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002767 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002768 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002769 // process the value immediately
2770 mProximityPendingValue = -1;
2771 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002772 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002773
2774 // update mProximityPartialLock state
2775 boolean held = mProximityPartialLock.isHeld();
2776 if (!held && proximityTaskQueued) {
2777 // hold wakelock until mProximityTask runs
2778 mProximityPartialLock.acquire();
2779 } else if (held && !proximityTaskQueued) {
2780 mProximityPartialLock.release();
2781 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002782 }
2783 }
2784
2785 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2786 // ignore
2787 }
2788 };
2789
2790 SensorEventListener mLightListener = new SensorEventListener() {
2791 public void onSensorChanged(SensorEvent event) {
2792 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002793 // ignore light sensor while screen is turning off
2794 if (isScreenTurningOffLocked()) {
2795 return;
2796 }
2797
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002798 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002799 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002800 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002801 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002802 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002803 mHandler.removeCallbacks(mAutoBrightnessTask);
2804 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002805 if (mLightSensorValue == -1 ||
2806 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2807 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002808 lightSensorChangedLocked(value);
2809 } else {
2810 // delay processing to debounce the sensor
2811 mLightSensorPendingValue = value;
2812 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2813 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002814 } else {
2815 mLightSensorPendingValue = -1;
2816 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002817 }
2818 }
2819
2820 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2821 // ignore
2822 }
2823 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824}