blob: 0189c60742ce633077baec6b707012a4ed83a2c7 [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;
20import com.android.server.am.BatteryStatsService;
21
22import android.app.ActivityManagerNative;
23import android.app.IActivityManager;
24import android.content.BroadcastReceiver;
25import android.content.ContentQueryMap;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070031import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080032import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070034import android.hardware.Sensor;
35import android.hardware.SensorEvent;
36import android.hardware.SensorEventListener;
37import android.hardware.SensorManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.os.BatteryStats;
39import android.os.Binder;
Doug Zongker43866e02010-01-07 12:09:54 -080040import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.Handler;
42import android.os.HandlerThread;
43import android.os.IBinder;
San Mehatb1043402010-02-05 08:26:50 -080044import android.os.storage.IMountService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import 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);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250
251 /*
252 static PrintStream mLog;
253 static {
254 try {
255 mLog = new PrintStream("/data/power.log");
256 }
257 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800258 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 }
260 }
261 static class Log {
262 static void d(String tag, String s) {
263 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800264 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 }
266 static void i(String tag, String s) {
267 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800268 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 }
270 static void w(String tag, String s) {
271 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800272 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 }
274 static void e(String tag, String s) {
275 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800276 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 }
278 }
279 */
280
281 /**
282 * This class works around a deadlock between the lock in PowerManager.WakeLock
283 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
284 * mToken object so it can be accessed from any thread, but it calls into here
285 * with its lock held. This class is essentially a reimplementation of
286 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
287 * only call it with our own locks held.
288 */
289 private class UnsynchronizedWakeLock {
290 int mFlags;
291 String mTag;
292 IBinder mToken;
293 int mCount = 0;
294 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500295 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296
297 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
298 mFlags = flags;
299 mTag = tag;
300 mToken = new Binder();
301 mRefCounted = refCounted;
302 }
303
304 public void acquire() {
305 if (!mRefCounted || mCount++ == 0) {
306 long ident = Binder.clearCallingIdentity();
307 try {
308 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
309 MY_UID, mTag);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500310 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 } finally {
312 Binder.restoreCallingIdentity(ident);
313 }
314 }
315 }
316
317 public void release() {
318 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500319 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500320 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 }
322 if (mCount < 0) {
323 throw new RuntimeException("WakeLock under-locked " + mTag);
324 }
325 }
326
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500327 public boolean isHeld()
328 {
329 return mHeld;
330 }
331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 public String toString() {
333 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500334 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 }
336 }
337
338 private final class BatteryReceiver extends BroadcastReceiver {
339 @Override
340 public void onReceive(Context context, Intent intent) {
341 synchronized (mLocks) {
342 boolean wasPowered = mIsPowered;
343 mIsPowered = mBatteryService.isPowered();
344
345 if (mIsPowered != wasPowered) {
346 // update mStayOnWhilePluggedIn wake lock
347 updateWakeLockLocked();
348
349 // treat plugging and unplugging the devices as a user activity.
350 // users find it disconcerting when they unplug the device
351 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500352 // to avoid turning on the screen when unplugging, we only trigger
353 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 // temporarily set mUserActivityAllowed to true so this will work
355 // even when the keyguard is on.
356 synchronized (mLocks) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500357 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0) {
358 forceUserActivityLocked();
359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 }
361 }
362 }
363 }
364 }
365
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500366 private final class BootCompletedReceiver extends BroadcastReceiver {
367 @Override
368 public void onReceive(Context context, Intent intent) {
369 bootCompleted();
370 }
371 }
372
Mike Lockwoodb2865412010-02-02 22:40:33 -0500373 private final class DockReceiver extends BroadcastReceiver {
374 @Override
375 public void onReceive(Context context, Intent intent) {
376 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
377 Intent.EXTRA_DOCK_STATE_UNDOCKED);
378 dockStateChanged(state);
379 }
380 }
381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 /**
383 * Set the setting that determines whether the device stays on when plugged in.
384 * The argument is a bit string, with each bit specifying a power source that,
385 * when the device is connected to that source, causes the device to stay on.
386 * See {@link android.os.BatteryManager} for the list of power sources that
387 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
388 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
389 * @param val an {@code int} containing the bits that specify which power sources
390 * should cause the device to stay on.
391 */
392 public void setStayOnSetting(int val) {
393 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
394 Settings.System.putInt(mContext.getContentResolver(),
395 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
396 }
397
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800398 public void setMaximumScreenOffTimeount(int timeMs) {
399 mContext.enforceCallingOrSelfPermission(
400 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
401 synchronized (mLocks) {
402 mMaximumScreenOffTimeout = timeMs;
403 // recalculate everything
404 setScreenOffTimeoutsLocked();
405 }
406 }
407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 private class SettingsObserver implements Observer {
409 private int getInt(String name) {
410 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
411 }
412
413 public void update(Observable o, Object arg) {
414 synchronized (mLocks) {
415 // STAY_ON_WHILE_PLUGGED_IN
416 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
417 updateWakeLockLocked();
418
419 // SCREEN_OFF_TIMEOUT
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800420 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421
422 // DIM_SCREEN
423 //mDimScreen = getInt(DIM_SCREEN) != 0;
424
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700425 // SCREEN_BRIGHTNESS_MODE
426 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 // recalculate everything
429 setScreenOffTimeoutsLocked();
430 }
431 }
432 }
433
434 PowerManagerService()
435 {
436 // Hack to get our uid... should have a func for this.
437 long token = Binder.clearCallingIdentity();
438 MY_UID = Binder.getCallingUid();
439 Binder.restoreCallingIdentity(token);
440
441 // XXX remove this when the kernel doesn't timeout wake locks
442 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
443
444 // assume nothing is on yet
445 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 // Add ourself to the Watchdog monitors.
448 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 }
450
451 private ContentQueryMap mSettings;
452
Mike Lockwood3a322132009-11-24 00:30:52 -0500453 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700454 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500455 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 mContext = context;
457 mActivityService = activity;
458 mBatteryStats = BatteryStatsService.getService();
459 mBatteryService = battery;
460
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500461 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
462 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
463 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
464 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 mHandlerThread = new HandlerThread("PowerManagerService") {
467 @Override
468 protected void onLooperPrepared() {
469 super.onLooperPrepared();
470 initInThread();
471 }
472 };
473 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 synchronized (mHandlerThread) {
476 while (!mInitComplete) {
477 try {
478 mHandlerThread.wait();
479 } catch (InterruptedException e) {
480 // Ignore
481 }
482 }
483 }
484 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 void initInThread() {
487 mHandler = new Handler();
488
489 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700490 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
492 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
493 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
494 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
495 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
496 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500497 mProximityPartialLock = new UnsynchronizedWakeLock(
498 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499
500 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
501 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
502 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
503 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
504
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700505 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400506
507 // read settings for auto-brightness
508 mUseSoftwareAutoBrightness = resources.getBoolean(
509 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400510 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700511 mAutoBrightnessLevels = resources.getIntArray(
512 com.android.internal.R.array.config_autoBrightnessLevels);
513 mLcdBacklightValues = resources.getIntArray(
514 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
515 mButtonBacklightValues = resources.getIntArray(
516 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
517 mKeyboardBacklightValues = resources.getIntArray(
518 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500519 mLightSensorWarmupTime = resources.getInteger(
520 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700521 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700522
523 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
525 "(" + Settings.System.NAME + "=?) or ("
526 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700527 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700529 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
530 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 null);
532 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
533 SettingsObserver settingsObserver = new SettingsObserver();
534 mSettings.addObserver(settingsObserver);
535
536 // pretend that the settings changed so we will get their initial state
537 settingsObserver.update(mSettings, null);
538
539 // register for the battery changed notifications
540 IntentFilter filter = new IntentFilter();
541 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
542 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500543 filter = new IntentFilter();
544 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
545 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500546 filter = new IntentFilter();
547 filter.addAction(Intent.ACTION_DOCK_EVENT);
548 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549
Doug Zongker43866e02010-01-07 12:09:54 -0800550 // Listen for secure settings changes
551 mContext.getContentResolver().registerContentObserver(
552 Settings.Secure.CONTENT_URI, true,
553 new ContentObserver(new Handler()) {
554 public void onChange(boolean selfChange) {
555 updateSettingsValues();
556 }
557 });
558 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 synchronized (mHandlerThread) {
561 mInitComplete = true;
562 mHandlerThread.notifyAll();
563 }
564 }
565
566 private class WakeLock implements IBinder.DeathRecipient
567 {
568 WakeLock(int f, IBinder b, String t, int u) {
569 super();
570 flags = f;
571 binder = b;
572 tag = t;
573 uid = u == MY_UID ? Process.SYSTEM_UID : u;
574 if (u != MY_UID || (
575 !"KEEP_SCREEN_ON_FLAG".equals(tag)
576 && !"KeyInputQueue".equals(tag))) {
577 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
578 ? BatteryStats.WAKE_TYPE_PARTIAL
579 : BatteryStats.WAKE_TYPE_FULL;
580 } else {
581 monitorType = -1;
582 }
583 try {
584 b.linkToDeath(this, 0);
585 } catch (RemoteException e) {
586 binderDied();
587 }
588 }
589 public void binderDied() {
590 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500591 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 }
593 }
594 final int flags;
595 final IBinder binder;
596 final String tag;
597 final int uid;
598 final int monitorType;
599 boolean activated = true;
600 int minState;
601 }
602
603 private void updateWakeLockLocked() {
604 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
605 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
606 mStayOnWhilePluggedInScreenDimLock.acquire();
607 mStayOnWhilePluggedInPartialLock.acquire();
608 } else {
609 mStayOnWhilePluggedInScreenDimLock.release();
610 mStayOnWhilePluggedInPartialLock.release();
611 }
612 }
613
614 private boolean isScreenLock(int flags)
615 {
616 int n = flags & LOCK_MASK;
617 return n == PowerManager.FULL_WAKE_LOCK
618 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
619 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
620 }
621
622 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700624 if (uid != Process.myUid()) {
625 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 long ident = Binder.clearCallingIdentity();
628 try {
629 synchronized (mLocks) {
630 acquireWakeLockLocked(flags, lock, uid, tag);
631 }
632 } finally {
633 Binder.restoreCallingIdentity(ident);
634 }
635 }
636
637 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
638 int acquireUid = -1;
639 String acquireName = null;
640 int acquireType = -1;
641
642 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800643 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 }
645
646 int index = mLocks.getIndex(lock);
647 WakeLock wl;
648 boolean newlock;
649 if (index < 0) {
650 wl = new WakeLock(flags, lock, tag, uid);
651 switch (wl.flags & LOCK_MASK)
652 {
653 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500654 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400655 wl.minState = SCREEN_BRIGHT;
656 } else {
657 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 break;
660 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
661 wl.minState = SCREEN_BRIGHT;
662 break;
663 case PowerManager.SCREEN_DIM_WAKE_LOCK:
664 wl.minState = SCREEN_DIM;
665 break;
666 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700667 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 break;
669 default:
670 // just log and bail. we're in the server, so don't
671 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800672 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 + " flags=" + flags);
674 return;
675 }
676 mLocks.addLock(wl);
677 newlock = true;
678 } else {
679 wl = mLocks.get(index);
680 newlock = false;
681 }
682 if (isScreenLock(flags)) {
683 // if this causes a wakeup, we reactivate all of the locks and
684 // set it to whatever they want. otherwise, we modulate that
685 // by the current state so we never turn it more on than
686 // it already is.
687 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700688 int oldWakeLockState = mWakeLockState;
689 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800691 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700692 + " mWakeLockState=0x"
693 + Integer.toHexString(mWakeLockState)
694 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 } else {
697 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800698 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 + " mLocks.gatherState()=0x"
700 + Integer.toHexString(mLocks.gatherState())
701 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
702 }
703 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
704 }
705 setPowerState(mWakeLockState | mUserState);
706 }
707 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
708 if (newlock) {
709 mPartialCount++;
710 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800711 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 }
713 }
714 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700715 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500716 mProximityWakeLockCount++;
717 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700718 enableProximityLockLocked();
719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 }
721 if (newlock) {
722 acquireUid = wl.uid;
723 acquireName = wl.tag;
724 acquireType = wl.monitorType;
725 }
726
727 if (acquireType >= 0) {
728 try {
729 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
730 } catch (RemoteException e) {
731 // Ignore
732 }
733 }
734 }
735
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500736 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700737 int uid = Binder.getCallingUid();
738 if (uid != Process.myUid()) {
739 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741
742 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500743 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 }
745 }
746
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500747 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 int releaseUid;
749 String releaseName;
750 int releaseType;
751
752 WakeLock wl = mLocks.removeLock(lock);
753 if (wl == null) {
754 return;
755 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800758 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
760 }
761
762 if (isScreenLock(wl.flags)) {
763 mWakeLockState = mLocks.gatherState();
764 // goes in the middle to reduce flicker
765 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
766 userActivity(SystemClock.uptimeMillis(), false);
767 }
768 setPowerState(mWakeLockState | mUserState);
769 }
770 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
771 mPartialCount--;
772 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800773 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 Power.releaseWakeLock(PARTIAL_NAME);
775 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700776 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500777 mProximityWakeLockCount--;
778 if (mProximityWakeLockCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500779 if (mProximitySensorActive &&
780 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500781 // wait for proximity sensor to go negative before disabling sensor
782 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800783 Slog.d(TAG, "waiting for proximity sensor to go negative");
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500784 }
785 } else {
786 disableProximityLockLocked();
787 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 }
790 // Unlink the lock from the binder.
791 wl.binder.unlinkToDeath(wl, 0);
792 releaseUid = wl.uid;
793 releaseName = wl.tag;
794 releaseType = wl.monitorType;
795
796 if (releaseType >= 0) {
797 long origId = Binder.clearCallingIdentity();
798 try {
799 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
800 } catch (RemoteException e) {
801 // Ignore
802 } finally {
803 Binder.restoreCallingIdentity(origId);
804 }
805 }
806 }
807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 private class PokeLock implements IBinder.DeathRecipient
809 {
810 PokeLock(int p, IBinder b, String t) {
811 super();
812 this.pokey = p;
813 this.binder = b;
814 this.tag = t;
815 try {
816 b.linkToDeath(this, 0);
817 } catch (RemoteException e) {
818 binderDied();
819 }
820 }
821 public void binderDied() {
822 setPokeLock(0, this.binder, this.tag);
823 }
824 int pokey;
825 IBinder binder;
826 String tag;
827 boolean awakeOnSet;
828 }
829
830 public void setPokeLock(int pokey, IBinder token, String tag) {
831 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
832 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800833 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 return;
835 }
836
837 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
838 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
839 + " and POKE_LOCK_MEDIUM_TIMEOUT");
840 }
841
842 synchronized (mLocks) {
843 if (pokey != 0) {
844 PokeLock p = mPokeLocks.get(token);
845 int oldPokey = 0;
846 if (p != null) {
847 oldPokey = p.pokey;
848 p.pokey = pokey;
849 } else {
850 p = new PokeLock(pokey, token, tag);
851 mPokeLocks.put(token, p);
852 }
853 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
854 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
855 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
856 p.awakeOnSet = true;
857 }
858 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700859 PokeLock rLock = mPokeLocks.remove(token);
860 if (rLock != null) {
861 token.unlinkToDeath(rLock, 0);
862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 }
864
865 int oldPokey = mPokey;
866 int cumulative = 0;
867 boolean oldAwakeOnSet = mPokeAwakeOnSet;
868 boolean awakeOnSet = false;
869 for (PokeLock p: mPokeLocks.values()) {
870 cumulative |= p.pokey;
871 if (p.awakeOnSet) {
872 awakeOnSet = true;
873 }
874 }
875 mPokey = cumulative;
876 mPokeAwakeOnSet = awakeOnSet;
877
878 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
879 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 if (oldCumulativeTimeout != newCumulativeTimeout) {
882 setScreenOffTimeoutsLocked();
883 // reset the countdown timer, but use the existing nextState so it doesn't
884 // change anything
885 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
886 }
887 }
888 }
889
890 private static String lockType(int type)
891 {
892 switch (type)
893 {
894 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700895 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700897 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700899 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700901 return "PARTIAL_WAKE_LOCK ";
902 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
903 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 default:
David Brown251faa62009-08-02 22:04:36 -0700905 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 }
907 }
908
909 private static String dumpPowerState(int state) {
910 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
911 ? "KEYBOARD_BRIGHT_BIT " : "")
912 + (((state & SCREEN_BRIGHT_BIT) != 0)
913 ? "SCREEN_BRIGHT_BIT " : "")
914 + (((state & SCREEN_ON_BIT) != 0)
915 ? "SCREEN_ON_BIT " : "")
916 + (((state & BATTERY_LOW_BIT) != 0)
917 ? "BATTERY_LOW_BIT " : "");
918 }
919
920 @Override
921 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
922 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
923 != PackageManager.PERMISSION_GRANTED) {
924 pw.println("Permission Denial: can't dump PowerManager from from pid="
925 + Binder.getCallingPid()
926 + ", uid=" + Binder.getCallingUid());
927 return;
928 }
929
930 long now = SystemClock.uptimeMillis();
931
Mike Lockwoodca44df82010-02-25 13:48:49 -0500932 synchronized (mLocks) {
933 pw.println("Power Manager State:");
934 pw.println(" mIsPowered=" + mIsPowered
935 + " mPowerState=" + mPowerState
936 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
937 + " ms");
938 pw.println(" mPartialCount=" + mPartialCount);
939 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
940 pw.println(" mUserState=" + dumpPowerState(mUserState));
941 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
942 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
943 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
944 + " " + ((mNextTimeout-now)/1000) + "s from now");
945 pw.println(" mDimScreen=" + mDimScreen
946 + " mStayOnConditions=" + mStayOnConditions);
947 pw.println(" mScreenOffReason=" + mScreenOffReason
948 + " mUserState=" + mUserState);
949 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
950 + ',' + mBroadcastQueue[2] + "}");
951 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
952 + ',' + mBroadcastWhy[2] + "}");
953 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
954 pw.println(" mKeyboardVisible=" + mKeyboardVisible
955 + " mUserActivityAllowed=" + mUserActivityAllowed);
956 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
957 + " mScreenOffDelay=" + mScreenOffDelay);
958 pw.println(" mPreventScreenOn=" + mPreventScreenOn
959 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
960 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
961 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
962 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
963 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
964 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
965 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
966 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
967 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
968 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
969 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
970 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
971 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
972 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
973 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
974 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
975 pw.println(" mLightSensorValue=" + mLightSensorValue
976 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
977 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
978 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
979 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
980 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
981 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
982 mScreenBrightness.dump(pw, " mScreenBrightness: ");
983 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
984 mButtonBrightness.dump(pw, " mButtonBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800985
Mike Lockwoodca44df82010-02-25 13:48:49 -0500986 int N = mLocks.size();
987 pw.println();
988 pw.println("mLocks.size=" + N + ":");
989 for (int i=0; i<N; i++) {
990 WakeLock wl = mLocks.get(i);
991 String type = lockType(wl.flags & LOCK_MASK);
992 String acquireCausesWakeup = "";
993 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
994 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
995 }
996 String activated = "";
997 if (wl.activated) {
998 activated = " activated";
999 }
1000 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
1001 + activated + " (minState=" + wl.minState + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001003
1004 pw.println();
1005 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1006 for (PokeLock p: mPokeLocks.values()) {
1007 pw.println(" poke lock '" + p.tag + "':"
1008 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
1009 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
1010 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
1011 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
1012 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1013 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1014 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1015 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001017
Mike Lockwoodca44df82010-02-25 13:48:49 -05001018 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
1021
1022 private void setTimeoutLocked(long now, int nextState)
1023 {
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001024 if (mBootCompleted) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 mHandler.removeCallbacks(mTimeoutTask);
1026 mTimeoutTask.nextState = nextState;
1027 long when = now;
1028 switch (nextState)
1029 {
1030 case SCREEN_BRIGHT:
1031 when += mKeylightDelay;
1032 break;
1033 case SCREEN_DIM:
1034 if (mDimDelay >= 0) {
1035 when += mDimDelay;
1036 break;
1037 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001038 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 }
1040 case SCREEN_OFF:
1041 synchronized (mLocks) {
1042 when += mScreenOffDelay;
1043 }
1044 break;
1045 }
1046 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001047 Slog.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 + " when=" + when);
1049 }
1050 mHandler.postAtTime(mTimeoutTask, when);
1051 mNextTimeout = when; // for debugging
1052 }
1053 }
1054
1055 private void cancelTimerLocked()
1056 {
1057 mHandler.removeCallbacks(mTimeoutTask);
1058 mTimeoutTask.nextState = -1;
1059 }
1060
1061 private class TimeoutTask implements Runnable
1062 {
1063 int nextState; // access should be synchronized on mLocks
1064 public void run()
1065 {
1066 synchronized (mLocks) {
1067 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001068 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 }
1070
1071 if (nextState == -1) {
1072 return;
1073 }
1074
1075 mUserState = this.nextState;
1076 setPowerState(this.nextState | mWakeLockState);
1077
1078 long now = SystemClock.uptimeMillis();
1079
1080 switch (this.nextState)
1081 {
1082 case SCREEN_BRIGHT:
1083 if (mDimDelay >= 0) {
1084 setTimeoutLocked(now, SCREEN_DIM);
1085 break;
1086 }
1087 case SCREEN_DIM:
1088 setTimeoutLocked(now, SCREEN_OFF);
1089 break;
1090 }
1091 }
1092 }
1093 }
1094
1095 private void sendNotificationLocked(boolean on, int why)
1096 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001097 if (!on) {
1098 mStillNeedSleepNotification = false;
1099 }
1100
Joe Onorato128e7292009-03-24 18:41:31 -07001101 // Add to the queue.
1102 int index = 0;
1103 while (mBroadcastQueue[index] != -1) {
1104 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 }
Joe Onorato128e7292009-03-24 18:41:31 -07001106 mBroadcastQueue[index] = on ? 1 : 0;
1107 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108
Joe Onorato128e7292009-03-24 18:41:31 -07001109 // If we added it position 2, then there is a pair that can be stripped.
1110 // If we added it position 1 and we're turning the screen off, we can strip
1111 // the pair and do nothing, because the screen is already off, and therefore
1112 // keyguard has already been enabled.
1113 // However, if we added it at position 1 and we're turning it on, then position
1114 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1115 // on, so have to run the queue then.
1116 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001117 // While we're collapsing them, if it's going off, and the new reason
1118 // is more significant than the first, then use the new one.
1119 if (!on && mBroadcastWhy[0] > why) {
1120 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001121 }
1122 mBroadcastQueue[0] = on ? 1 : 0;
1123 mBroadcastQueue[1] = -1;
1124 mBroadcastQueue[2] = -1;
1125 index = 0;
1126 }
1127 if (index == 1 && !on) {
1128 mBroadcastQueue[0] = -1;
1129 mBroadcastQueue[1] = -1;
1130 index = -1;
1131 // The wake lock was being held, but we're not actually going to do any
1132 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001133 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001135 }
1136
1137 // Now send the message.
1138 if (index >= 0) {
1139 // Acquire the broadcast wake lock before changing the power
1140 // state. It will be release after the broadcast is sent.
1141 // We always increment the ref count for each notification in the queue
1142 // and always decrement when that notification is handled.
1143 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001144 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001145 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 }
1147 }
1148
1149 private Runnable mNotificationTask = new Runnable()
1150 {
1151 public void run()
1152 {
Joe Onorato128e7292009-03-24 18:41:31 -07001153 while (true) {
1154 int value;
1155 int why;
1156 WindowManagerPolicy policy;
1157 synchronized (mLocks) {
1158 value = mBroadcastQueue[0];
1159 why = mBroadcastWhy[0];
1160 for (int i=0; i<2; i++) {
1161 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1162 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1163 }
1164 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 }
Joe Onorato128e7292009-03-24 18:41:31 -07001166 if (value == 1) {
1167 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001168
Joe Onorato128e7292009-03-24 18:41:31 -07001169 policy.screenTurnedOn();
1170 try {
1171 ActivityManagerNative.getDefault().wakingUp();
1172 } catch (RemoteException e) {
1173 // ignore it
1174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175
Joe Onorato128e7292009-03-24 18:41:31 -07001176 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001177 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001178 }
1179 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1180 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1181 mScreenOnBroadcastDone, mHandler, 0, null, null);
1182 } else {
1183 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001184 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001185 mBroadcastWakeLock.mCount);
1186 mBroadcastWakeLock.release();
1187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 }
1189 }
Joe Onorato128e7292009-03-24 18:41:31 -07001190 else if (value == 0) {
1191 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001192
Joe Onorato128e7292009-03-24 18:41:31 -07001193 policy.screenTurnedOff(why);
1194 try {
1195 ActivityManagerNative.getDefault().goingToSleep();
1196 } catch (RemoteException e) {
1197 // ignore it.
1198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199
Joe Onorato128e7292009-03-24 18:41:31 -07001200 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1201 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1202 mScreenOffBroadcastDone, mHandler, 0, null, null);
1203 } else {
1204 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001205 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001206 mBroadcastWakeLock.mCount);
1207 mBroadcastWakeLock.release();
1208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 }
1210 }
Joe Onorato128e7292009-03-24 18:41:31 -07001211 else {
1212 // If we're in this case, then this handler is running for a previous
1213 // paired transaction. mBroadcastWakeLock will already have been released.
1214 break;
1215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 }
1217 }
1218 };
1219
1220 long mScreenOnStart;
1221 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1222 public void onReceive(Context context, Intent intent) {
1223 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001224 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1226 mBroadcastWakeLock.release();
1227 }
1228 }
1229 };
1230
1231 long mScreenOffStart;
1232 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1233 public void onReceive(Context context, Intent intent) {
1234 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001235 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1237 mBroadcastWakeLock.release();
1238 }
1239 }
1240 };
1241
1242 void logPointerUpEvent() {
1243 if (LOG_TOUCH_DOWNS) {
1244 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1245 mLastTouchDown = 0;
1246 }
1247 }
1248
1249 void logPointerDownEvent() {
1250 if (LOG_TOUCH_DOWNS) {
1251 // If we are not already timing a down/up sequence
1252 if (mLastTouchDown == 0) {
1253 mLastTouchDown = SystemClock.elapsedRealtime();
1254 mTouchCycles++;
1255 }
1256 }
1257 }
1258
1259 /**
1260 * Prevents the screen from turning on even if it *should* turn on due
1261 * to a subsequent full wake lock being acquired.
1262 * <p>
1263 * This is a temporary hack that allows an activity to "cover up" any
1264 * display glitches that happen during the activity's startup
1265 * sequence. (Specifically, this API was added to work around a
1266 * cosmetic bug in the "incoming call" sequence, where the lock screen
1267 * would flicker briefly before the incoming call UI became visible.)
1268 * TODO: There ought to be a more elegant way of doing this,
1269 * probably by having the PowerManager and ActivityManager
1270 * work together to let apps specify that the screen on/off
1271 * state should be synchronized with the Activity lifecycle.
1272 * <p>
1273 * Note that calling preventScreenOn(true) will NOT turn the screen
1274 * off if it's currently on. (This API only affects *future*
1275 * acquisitions of full wake locks.)
1276 * But calling preventScreenOn(false) WILL turn the screen on if
1277 * it's currently off because of a prior preventScreenOn(true) call.
1278 * <p>
1279 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1280 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1281 * call doesn't occur within 5 seconds, we'll turn the screen back on
1282 * ourselves (and log a warning about it); this prevents a buggy app
1283 * from disabling the screen forever.)
1284 * <p>
1285 * TODO: this feature should really be controlled by a new type of poke
1286 * lock (rather than an IPowerManager call).
1287 */
1288 public void preventScreenOn(boolean prevent) {
1289 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1290
1291 synchronized (mLocks) {
1292 if (prevent) {
1293 // First of all, grab a partial wake lock to
1294 // make sure the CPU stays on during the entire
1295 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1296 mPreventScreenOnPartialLock.acquire();
1297
1298 // Post a forceReenableScreen() call (for 5 seconds in the
1299 // future) to make sure the matching preventScreenOn(false) call
1300 // has happened by then.
1301 mHandler.removeCallbacks(mForceReenableScreenTask);
1302 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1303
1304 // Finally, set the flag that prevents the screen from turning on.
1305 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001306 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 mPreventScreenOn = true;
1308 } else {
1309 // (Re)enable the screen.
1310 mPreventScreenOn = false;
1311
1312 // We're "undoing" a the prior preventScreenOn(true) call, so we
1313 // no longer need the 5-second safeguard.
1314 mHandler.removeCallbacks(mForceReenableScreenTask);
1315
1316 // Forcibly turn on the screen if it's supposed to be on. (This
1317 // handles the case where the screen is currently off because of
1318 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001319 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001321 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1323 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001324 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001326 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 }
1328 }
1329
1330 // Release the partial wake lock that we held during the
1331 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1332 mPreventScreenOnPartialLock.release();
1333 }
1334 }
1335 }
1336
1337 public void setScreenBrightnessOverride(int brightness) {
1338 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1339
1340 synchronized (mLocks) {
1341 if (mScreenBrightnessOverride != brightness) {
1342 mScreenBrightnessOverride = brightness;
1343 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1344 }
1345 }
1346 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001347
1348 public void setButtonBrightnessOverride(int brightness) {
1349 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1350
1351 synchronized (mLocks) {
1352 if (mButtonBrightnessOverride != brightness) {
1353 mButtonBrightnessOverride = brightness;
1354 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1355 }
1356 }
1357 }
1358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 /**
1360 * Sanity-check that gets called 5 seconds after any call to
1361 * preventScreenOn(true). This ensures that the original call
1362 * is followed promptly by a call to preventScreenOn(false).
1363 */
1364 private void forceReenableScreen() {
1365 // We shouldn't get here at all if mPreventScreenOn is false, since
1366 // we should have already removed any existing
1367 // mForceReenableScreenTask messages...
1368 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001369 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 return;
1371 }
1372
1373 // Uh oh. It's been 5 seconds since a call to
1374 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1375 // This means the app that called preventScreenOn(true) is either
1376 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1377 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1378 // crashed before doing so.)
1379
1380 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001381 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 + "Forcing the screen back on...");
1383 preventScreenOn(false);
1384 }
1385
1386 private Runnable mForceReenableScreenTask = new Runnable() {
1387 public void run() {
1388 forceReenableScreen();
1389 }
1390 };
1391
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001392 private int setScreenStateLocked(boolean on) {
1393 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001394 if (err == 0) {
1395 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1396 if (mUseSoftwareAutoBrightness) {
1397 enableLightSensor(on);
1398 if (!on) {
1399 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001400 mButtonLight.turnOff();
1401 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001402 // clear current value so we will update based on the new conditions
1403 // when the sensor is reenabled.
1404 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001405 // reset our highest light sensor value when the screen turns off
1406 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001407 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001408 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001409 }
1410 return err;
1411 }
1412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 private void setPowerState(int state)
1414 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001415 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
1417
Mike Lockwood435eb642009-12-03 08:40:18 -05001418 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 {
1420 synchronized (mLocks) {
1421 int err;
1422
1423 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001424 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001426 + " noChangeLights=" + noChangeLights
1427 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429
1430 if (noChangeLights) {
1431 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1432 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001433 if (mProximitySensorActive) {
1434 // don't turn on the screen when the proximity sensor lock is held
1435 newState = (newState & ~SCREEN_BRIGHT);
1436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437
1438 if (batteryIsLow()) {
1439 newState |= BATTERY_LOW_BIT;
1440 } else {
1441 newState &= ~BATTERY_LOW_BIT;
1442 }
1443 if (newState == mPowerState) {
1444 return;
1445 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001446
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001447 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 newState |= ALL_BRIGHT;
1449 }
1450
1451 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1452 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1453
Mike Lockwood51b84492009-11-16 21:51:18 -05001454 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001455 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001457 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001459 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001461 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001463 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001465 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1467 }
1468
1469 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001470 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1472 }
1473
1474 if (oldScreenOn != newScreenOn) {
1475 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001476 // When the user presses the power button, we need to always send out the
1477 // notification that it's going to sleep so the keyguard goes on. But
1478 // we can't do that until the screen fades out, so we don't show the keyguard
1479 // too early.
1480 if (mStillNeedSleepNotification) {
1481 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1482 }
1483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 // Turn on the screen UNLESS there was a prior
1485 // preventScreenOn(true) request. (Note that the lifetime
1486 // of a single preventScreenOn() request is limited to 5
1487 // seconds to prevent a buggy app from disabling the
1488 // screen forever; see forceReenableScreen().)
1489 boolean reallyTurnScreenOn = true;
1490 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001491 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 + mPreventScreenOn);
1493 }
1494
1495 if (mPreventScreenOn) {
1496 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001497 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 }
1499 reallyTurnScreenOn = false;
1500 }
1501 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001502 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 long identity = Binder.clearCallingIdentity();
1504 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001505 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 mBatteryStats.noteScreenOn();
1507 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001508 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 } finally {
1510 Binder.restoreCallingIdentity(identity);
1511 }
1512 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001513 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 // But continue as if we really did turn the screen on...
1515 err = 0;
1516 }
1517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 mLastTouchDown = 0;
1519 mTotalTouchDownTime = 0;
1520 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001521 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 mTotalTouchDownTime, mTouchCycles);
1523 if (err == 0) {
1524 mPowerState |= SCREEN_ON_BIT;
1525 sendNotificationLocked(true, -1);
1526 }
1527 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001528 // cancel light sensor task
1529 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 mScreenOffTime = SystemClock.elapsedRealtime();
1531 long identity = Binder.clearCallingIdentity();
1532 try {
1533 mBatteryStats.noteScreenOff();
1534 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001535 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 } finally {
1537 Binder.restoreCallingIdentity(identity);
1538 }
1539 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001540 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001542 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 err = 0;
1545 mLastTouchDown = 0;
1546 }
1547 }
1548 }
1549 }
1550 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001551
Mike Lockwood435eb642009-12-03 08:40:18 -05001552 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001554 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001556 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001558 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001560 mScreenOffReason = reason;
1561 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 }
1563 return err;
1564 }
1565
1566 private boolean batteryIsLow() {
1567 return (!mIsPowered &&
1568 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1569 }
1570
The Android Open Source Project10592532009-03-18 17:39:46 -07001571 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001572 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001573 newState = applyButtonState(newState);
1574 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001575 final int realDifference = (newState ^ oldState);
1576 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001578 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 int offMask = 0;
1582 int dimMask = 0;
1583 int onMask = 0;
1584
1585 int preferredBrightness = getPreferredBrightness();
1586 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1589 if (ANIMATE_KEYBOARD_LIGHTS) {
1590 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1591 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001592 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001593 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001595 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001596 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1597 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 }
1599 startAnimation = true;
1600 } else {
1601 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001602 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001604 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 }
1606 }
1607 }
1608
1609 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1610 if (ANIMATE_BUTTON_LIGHTS) {
1611 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1612 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001613 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001614 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001616 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001617 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1618 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 }
1620 startAnimation = true;
1621 } else {
1622 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001623 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001625 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 }
1627 }
1628 }
1629
1630 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1631 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001632 int nominalCurrentValue = -1;
1633 // If there was an actual difference in the light state, then
1634 // figure out the "ideal" current value based on the previous
1635 // state. Otherwise, this is a change due to the brightness
1636 // override, so we want to animate from whatever the current
1637 // value is.
1638 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1639 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1640 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1641 nominalCurrentValue = preferredBrightness;
1642 break;
1643 case SCREEN_ON_BIT:
1644 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1645 break;
1646 case 0:
1647 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1648 break;
1649 case SCREEN_BRIGHT_BIT:
1650 default:
1651 // not possible
1652 nominalCurrentValue = (int)mScreenBrightness.curValue;
1653 break;
1654 }
Joe Onorato128e7292009-03-24 18:41:31 -07001655 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001656 int brightness = preferredBrightness;
1657 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1659 // dim or turn off backlight, depending on if the screen is on
1660 // the scale is because the brightness ramp isn't linear and this biases
1661 // it so the later parts take longer.
1662 final float scale = 1.5f;
1663 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1664 if (ratio > 1.0f) ratio = 1.0f;
1665 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1667 // was bright
1668 steps = ANIM_STEPS;
1669 } else {
1670 // was dim
1671 steps = (int)(ANIM_STEPS*ratio*scale);
1672 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001673 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 if ((oldState & SCREEN_ON_BIT) != 0) {
1676 // was bright
1677 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1678 } else {
1679 // was dim
1680 steps = (int)(ANIM_STEPS*ratio);
1681 }
1682 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1683 // If the "stay on while plugged in" option is
1684 // turned on, then the screen will often not
1685 // automatically turn off while plugged in. To
1686 // still have a sense of when it is inactive, we
1687 // will then count going dim as turning off.
1688 mScreenOffTime = SystemClock.elapsedRealtime();
1689 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001690 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001693 long identity = Binder.clearCallingIdentity();
1694 try {
1695 mBatteryStats.noteScreenBrightness(brightness);
1696 } catch (RemoteException e) {
1697 // Nothing interesting to do.
1698 } finally {
1699 Binder.restoreCallingIdentity(identity);
1700 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001701 if (mScreenBrightness.setTargetLocked(brightness,
1702 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1703 startAnimation = true;
1704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 } else {
1706 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1707 // dim or turn off backlight, depending on if the screen is on
1708 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001709 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001711 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 }
1713 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001714 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 }
1716 }
1717 }
1718
1719 if (startAnimation) {
1720 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001721 Slog.i(TAG, "Scheduling light animator!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 }
1723 mHandler.removeCallbacks(mLightAnimator);
1724 mHandler.post(mLightAnimator);
1725 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 if (offMask != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001728 //Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001729 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 }
1731 if (dimMask != 0) {
1732 int brightness = Power.BRIGHTNESS_DIM;
1733 if ((newState & BATTERY_LOW_BIT) != 0 &&
1734 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1735 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1736 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001737 //Slog.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001738 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 }
1740 if (onMask != 0) {
1741 int brightness = getPreferredBrightness();
1742 if ((newState & BATTERY_LOW_BIT) != 0 &&
1743 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1744 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1745 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001746 //Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001747 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750
The Android Open Source Project10592532009-03-18 17:39:46 -07001751 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001752 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001753 ? LightsService.BRIGHTNESS_MODE_SENSOR
1754 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001755 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001756 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001757 }
1758 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001759 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001760 }
1761 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001762 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 }
1765
1766 class BrightnessState {
1767 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 boolean initialized;
1770 int targetValue;
1771 float curValue;
1772 float delta;
1773 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 BrightnessState(int m) {
1776 mask = m;
1777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 public void dump(PrintWriter pw, String prefix) {
1780 pw.println(prefix + "animating=" + animating
1781 + " targetValue=" + targetValue
1782 + " curValue=" + curValue
1783 + " delta=" + delta);
1784 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001785
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001786 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001787 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 if (!initialized) {
1789 initialized = true;
1790 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001791 } else if (targetValue == target) {
1792 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 }
1794 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001795 delta = (targetValue -
1796 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1797 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001799 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato8a9b2202010-02-26 18:56:32 -08001800 Slog.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001801 + " target=" + targetValue + " delta=" + delta
1802 + " nominalCurrentValue=" + nominalCurrentValue
1803 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 }
1805 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001806 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 boolean stepLocked() {
1810 if (!animating) return false;
1811 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001812 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 + " target=" + targetValue + " delta=" + delta);
1814 }
1815 curValue += delta;
1816 int curIntValue = (int)curValue;
1817 boolean more = true;
1818 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001819 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 more = false;
1821 } else if (delta > 0) {
1822 if (curIntValue >= targetValue) {
1823 curValue = curIntValue = targetValue;
1824 more = false;
1825 }
1826 } else {
1827 if (curIntValue <= targetValue) {
1828 curValue = curIntValue = targetValue;
1829 more = false;
1830 }
1831 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001832 //Slog.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001833 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 animating = more;
1835 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001836 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001837 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 }
1839 }
1840 return more;
1841 }
1842 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 private class LightAnimator implements Runnable {
1845 public void run() {
1846 synchronized (mLocks) {
1847 long now = SystemClock.uptimeMillis();
1848 boolean more = mScreenBrightness.stepLocked();
1849 if (mKeyboardBrightness.stepLocked()) {
1850 more = true;
1851 }
1852 if (mButtonBrightness.stepLocked()) {
1853 more = true;
1854 }
1855 if (more) {
1856 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1857 }
1858 }
1859 }
1860 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 private int getPreferredBrightness() {
1863 try {
1864 if (mScreenBrightnessOverride >= 0) {
1865 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001866 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001867 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001868 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 }
1870 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1871 SCREEN_BRIGHTNESS);
1872 // Don't let applications turn the screen all the way off
1873 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1874 } catch (SettingNotFoundException snfe) {
1875 return Power.BRIGHTNESS_ON;
1876 }
1877 }
1878
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001879 private int applyButtonState(int state) {
1880 int brightness = -1;
1881 if (mButtonBrightnessOverride >= 0) {
1882 brightness = mButtonBrightnessOverride;
1883 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
1884 brightness = mLightSensorButtonBrightness;
1885 }
1886 if (brightness > 0) {
1887 return state | BUTTON_BRIGHT_BIT;
1888 } else if (brightness == 0) {
1889 return state & ~BUTTON_BRIGHT_BIT;
1890 } else {
1891 return state;
1892 }
1893 }
1894
1895 private int applyKeyboardState(int state) {
1896 int brightness = -1;
1897 if (!mKeyboardVisible) {
1898 brightness = 0;
1899 } else if (mButtonBrightnessOverride >= 0) {
1900 brightness = mButtonBrightnessOverride;
1901 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
1902 brightness = mLightSensorKeyboardBrightness;
1903 }
1904 if (brightness > 0) {
1905 return state | KEYBOARD_BRIGHT_BIT;
1906 } else if (brightness == 0) {
1907 return state & ~KEYBOARD_BRIGHT_BIT;
1908 } else {
1909 return state;
1910 }
1911 }
1912
Charles Mendis322591c2009-10-29 11:06:59 -07001913 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 synchronized (mLocks) {
1915 return (mPowerState & SCREEN_ON_BIT) != 0;
1916 }
1917 }
1918
Charles Mendis322591c2009-10-29 11:06:59 -07001919 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 synchronized (mLocks) {
1921 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1922 }
1923 }
1924
Mike Lockwood497087e32009-11-08 18:33:03 -05001925 private boolean isScreenTurningOffLocked() {
1926 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1927 }
1928
Mike Lockwood200b30b2009-09-20 00:23:59 -04001929 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05001930 if (isScreenTurningOffLocked()) {
1931 // cancel animation so userActivity will succeed
1932 mScreenBrightness.animating = false;
1933 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04001934 boolean savedActivityAllowed = mUserActivityAllowed;
1935 mUserActivityAllowed = true;
1936 userActivity(SystemClock.uptimeMillis(), false);
1937 mUserActivityAllowed = savedActivityAllowed;
1938 }
1939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1941 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1942 userActivity(time, noChangeLights, OTHER_EVENT, force);
1943 }
1944
1945 public void userActivity(long time, boolean noChangeLights) {
1946 userActivity(time, noChangeLights, OTHER_EVENT, false);
1947 }
1948
1949 public void userActivity(long time, boolean noChangeLights, int eventType) {
1950 userActivity(time, noChangeLights, eventType, false);
1951 }
1952
1953 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1954 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1955
1956 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001957 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001959 Slog.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 }
1961 return;
1962 }
1963
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001964 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1965 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1966 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1967 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001968 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001969 }
1970 return;
1971 }
1972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 if (false) {
1974 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001975 Slog.d(TAG, "userActivity !!!");//, new RuntimeException());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001977 Slog.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
1979 }
1980
1981 synchronized (mLocks) {
1982 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001983 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 + " mUserActivityAllowed=" + mUserActivityAllowed
1985 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001986 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1987 + " mProximitySensorActive=" + mProximitySensorActive
1988 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 }
Mike Lockwood05067122009-10-27 23:07:25 -04001990 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05001991 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001992 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04001993 return;
1994 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05001995 // Disable proximity sensor if if user presses power key while we are in the
1996 // "waiting for proximity sensor to go negative" state.
1997 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
1998 mProximitySensorActive = false;
1999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 if (mLastEventTime <= time || force) {
2001 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002002 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002003 // Only turn on button backlights if a button was pressed
2004 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002005 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2007 } else {
2008 // don't clear button/keyboard backlights when the screen is touched.
2009 mUserState |= SCREEN_BRIGHT;
2010 }
2011
Dianne Hackborn617f8772009-03-31 15:04:46 -07002012 int uid = Binder.getCallingUid();
2013 long ident = Binder.clearCallingIdentity();
2014 try {
2015 mBatteryStats.noteUserActivity(uid, eventType);
2016 } catch (RemoteException e) {
2017 // Ignore
2018 } finally {
2019 Binder.restoreCallingIdentity(ident);
2020 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002021
Michael Chane96440f2009-05-06 10:27:36 -07002022 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002023 setPowerState(mUserState | mWakeLockState, noChangeLights,
2024 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 setTimeoutLocked(time, SCREEN_BRIGHT);
2026 }
2027 }
2028 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002029
2030 if (mPolicy != null) {
2031 mPolicy.userActivity();
2032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 }
2034
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002035 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2036 try {
2037 int i;
2038 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2039 if (sensorValue < mAutoBrightnessLevels[i]) {
2040 break;
2041 }
2042 }
2043 return values[i];
2044 } catch (Exception e) {
2045 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002046 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002047 return 255;
2048 }
2049 }
2050
Mike Lockwood20f87d72009-11-05 16:08:51 -05002051 private Runnable mProximityTask = new Runnable() {
2052 public void run() {
2053 synchronized (mLocks) {
2054 if (mProximityPendingValue != -1) {
2055 proximityChangedLocked(mProximityPendingValue == 1);
2056 mProximityPendingValue = -1;
2057 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002058 if (mProximityPartialLock.isHeld()) {
2059 mProximityPartialLock.release();
2060 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002061 }
2062 }
2063 };
2064
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002065 private Runnable mAutoBrightnessTask = new Runnable() {
2066 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002067 synchronized (mLocks) {
2068 int value = (int)mLightSensorPendingValue;
2069 if (value >= 0) {
2070 mLightSensorPendingValue = -1;
2071 lightSensorChangedLocked(value);
2072 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002073 }
2074 }
2075 };
2076
Mike Lockwoodb2865412010-02-02 22:40:33 -05002077 private void dockStateChanged(int state) {
2078 synchronized (mLocks) {
2079 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2080 if (mIsDocked) {
2081 mHighestLightSensorValue = -1;
2082 }
2083 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2084 // force lights recalculation
2085 int value = (int)mLightSensorValue;
2086 mLightSensorValue = -1;
2087 lightSensorChangedLocked(value);
2088 }
2089 }
2090 }
2091
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002092 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002093 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002094 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002095 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002096
Mike Lockwoodb2865412010-02-02 22:40:33 -05002097 // do not allow light sensor value to decrease
2098 if (mHighestLightSensorValue < value) {
2099 mHighestLightSensorValue = value;
2100 }
2101
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002102 if (mLightSensorValue != value) {
2103 mLightSensorValue = value;
2104 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002105 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2106 // we only do this if we are undocked, since lighting should be stable when
2107 // stationary in a dock.
2108 int lcdValue = getAutoBrightnessValue(
2109 (mIsDocked ? value : mHighestLightSensorValue),
2110 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002111 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002112 int keyboardValue;
2113 if (mKeyboardVisible) {
2114 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2115 } else {
2116 keyboardValue = 0;
2117 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002118 mLightSensorScreenBrightness = lcdValue;
2119 mLightSensorButtonBrightness = buttonValue;
2120 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002121
2122 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002123 Slog.d(TAG, "lcdValue " + lcdValue);
2124 Slog.d(TAG, "buttonValue " + buttonValue);
2125 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002126 }
2127
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002128 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002129 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002130 if (ANIMATE_SCREEN_LIGHTS) {
2131 if (mScreenBrightness.setTargetLocked(lcdValue,
2132 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2133 (int)mScreenBrightness.curValue)) {
2134 startAnimation = true;
2135 }
2136 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002137 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002138 ? LightsService.BRIGHTNESS_MODE_SENSOR
2139 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002140 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002141 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002142 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002143 if (mButtonBrightnessOverride < 0) {
2144 if (ANIMATE_BUTTON_LIGHTS) {
2145 if (mButtonBrightness.setTargetLocked(buttonValue,
2146 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2147 (int)mButtonBrightness.curValue)) {
2148 startAnimation = true;
2149 }
2150 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002151 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002152 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002153 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002154 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2155 if (ANIMATE_KEYBOARD_LIGHTS) {
2156 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2157 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2158 (int)mKeyboardBrightness.curValue)) {
2159 startAnimation = true;
2160 }
2161 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002162 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002163 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002164 }
2165 if (startAnimation) {
2166 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002167 Slog.i(TAG, "lightSensorChangedLocked scheduling light animator");
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002168 }
2169 mHandler.removeCallbacks(mLightAnimator);
2170 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002171 }
2172 }
2173 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002174 }
2175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 /**
2177 * The user requested that we go to sleep (probably with the power button).
2178 * This overrides all wake locks that are held.
2179 */
2180 public void goToSleep(long time)
2181 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002182 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2183 }
2184
2185 /**
2186 * The user requested that we go to sleep (probably with the power button).
2187 * This overrides all wake locks that are held.
2188 */
2189 public void goToSleepWithReason(long time, int reason)
2190 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2192 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002193 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 }
2195 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002198 * Reboot the device immediately, passing 'reason' (may be null)
2199 * to the underlying __reboot system call. Should not return.
2200 */
2201 public void reboot(String reason)
2202 {
2203 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002204
San Mehat1e512792010-01-07 10:40:29 -08002205 /*
2206 * Manually shutdown the MountService to ensure media is
2207 * put into a safe state.
2208 */
2209 IMountService mSvc = IMountService.Stub.asInterface(
2210 ServiceManager.getService("mount"));
2211
2212 if (mSvc != null) {
2213 try {
2214 mSvc.shutdown();
2215 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002216 Slog.e(TAG, "MountService shutdown failed", e);
San Mehat1e512792010-01-07 10:40:29 -08002217 }
2218 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002219 Slog.w(TAG, "MountService unavailable for shutdown");
San Mehat1e512792010-01-07 10:40:29 -08002220 }
San Mehat14e69af2010-01-06 14:58:18 -08002221
Doug Zongker50a21f42009-11-19 12:49:53 -08002222 try {
2223 Power.reboot(reason);
2224 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002225 Slog.e(TAG, "reboot failed", e);
Doug Zongker50a21f42009-11-19 12:49:53 -08002226 }
2227 }
2228
Dan Egnor60d87622009-12-16 16:32:58 -08002229 /**
2230 * Crash the runtime (causing a complete restart of the Android framework).
2231 * Requires REBOOT permission. Mostly for testing. Should not return.
2232 */
2233 public void crash(final String message)
2234 {
2235 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2236 Thread t = new Thread("PowerManagerService.crash()") {
2237 public void run() { throw new RuntimeException(message); }
2238 };
2239 try {
2240 t.start();
2241 t.join();
2242 } catch (InterruptedException e) {
2243 Log.wtf(TAG, e);
2244 }
2245 }
2246
Mike Lockwood435eb642009-12-03 08:40:18 -05002247 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248
2249 if (mLastEventTime <= time) {
2250 mLastEventTime = time;
2251 // cancel all of the wake locks
2252 mWakeLockState = SCREEN_OFF;
2253 int N = mLocks.size();
2254 int numCleared = 0;
2255 for (int i=0; i<N; i++) {
2256 WakeLock wl = mLocks.get(i);
2257 if (isScreenLock(wl.flags)) {
2258 mLocks.get(i).activated = false;
2259 numCleared++;
2260 }
2261 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002262 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002263 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002265 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 cancelTimerLocked();
2267 }
2268 }
2269
2270 public long timeSinceScreenOn() {
2271 synchronized (mLocks) {
2272 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2273 return 0;
2274 }
2275 return SystemClock.elapsedRealtime() - mScreenOffTime;
2276 }
2277 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002280 synchronized (mLocks) {
2281 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002282 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002283 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002284 if (mKeyboardVisible != visible) {
2285 mKeyboardVisible = visible;
2286 // don't signal user activity if the screen is off; other code
2287 // will take care of turning on due to a true change to the lid
2288 // switch and synchronized with the lock screen.
2289 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002290 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002291 // force recompute of backlight values
2292 if (mLightSensorValue >= 0) {
2293 int value = (int)mLightSensorValue;
2294 mLightSensorValue = -1;
2295 lightSensorChangedLocked(value);
2296 }
2297 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002298 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2299 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002300 }
2301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002302 }
2303
2304 /**
2305 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002306 * When disabling user activity we also reset user power state so the keyguard can reset its
2307 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 */
2309 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002310 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002311 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002313 synchronized (mLocks) {
2314 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002315 if (!enabled) {
2316 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2317 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 }
2320 }
2321
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002322 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002323 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002324 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002325 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002326 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002327 // force recompute of backlight values
2328 if (mLightSensorValue >= 0) {
2329 int value = (int)mLightSensorValue;
2330 mLightSensorValue = -1;
2331 lightSensorChangedLocked(value);
2332 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002333 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002334 }
2335 }
2336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 /** Sets the screen off timeouts:
2338 * mKeylightDelay
2339 * mDimDelay
2340 * mScreenOffDelay
2341 * */
2342 private void setScreenOffTimeoutsLocked() {
2343 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002344 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 mDimDelay = -1;
2346 mScreenOffDelay = 0;
2347 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2348 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2349 mDimDelay = -1;
2350 mScreenOffDelay = 0;
2351 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002352 int totalDelay = mScreenOffTimeoutSetting;
2353 if (totalDelay > mMaximumScreenOffTimeout) {
2354 totalDelay = mMaximumScreenOffTimeout;
2355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2357 if (totalDelay < 0) {
2358 mScreenOffDelay = Integer.MAX_VALUE;
2359 } else if (mKeylightDelay < totalDelay) {
2360 // subtract the time that the keylight delay. This will give us the
2361 // remainder of the time that we need to sleep to get the accurate
2362 // screen off timeout.
2363 mScreenOffDelay = totalDelay - mKeylightDelay;
2364 } else {
2365 mScreenOffDelay = 0;
2366 }
2367 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2368 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2369 mScreenOffDelay = LONG_DIM_TIME;
2370 } else {
2371 mDimDelay = -1;
2372 }
2373 }
2374 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002375 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2377 + " mDimScreen=" + mDimScreen);
2378 }
2379 }
2380
2381 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002382 * Refreshes cached secure settings. Called once on startup, and
2383 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 */
Doug Zongker43866e02010-01-07 12:09:54 -08002385 private void updateSettingsValues() {
2386 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002388 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002390 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 }
2392
2393 private class LockList extends ArrayList<WakeLock>
2394 {
2395 void addLock(WakeLock wl)
2396 {
2397 int index = getIndex(wl.binder);
2398 if (index < 0) {
2399 this.add(wl);
2400 }
2401 }
2402
2403 WakeLock removeLock(IBinder binder)
2404 {
2405 int index = getIndex(binder);
2406 if (index >= 0) {
2407 return this.remove(index);
2408 } else {
2409 return null;
2410 }
2411 }
2412
2413 int getIndex(IBinder binder)
2414 {
2415 int N = this.size();
2416 for (int i=0; i<N; i++) {
2417 if (this.get(i).binder == binder) {
2418 return i;
2419 }
2420 }
2421 return -1;
2422 }
2423
2424 int gatherState()
2425 {
2426 int result = 0;
2427 int N = this.size();
2428 for (int i=0; i<N; i++) {
2429 WakeLock wl = this.get(i);
2430 if (wl.activated) {
2431 if (isScreenLock(wl.flags)) {
2432 result |= wl.minState;
2433 }
2434 }
2435 }
2436 return result;
2437 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002438
Michael Chane96440f2009-05-06 10:27:36 -07002439 int reactivateScreenLocksLocked()
2440 {
2441 int result = 0;
2442 int N = this.size();
2443 for (int i=0; i<N; i++) {
2444 WakeLock wl = this.get(i);
2445 if (isScreenLock(wl.flags)) {
2446 wl.activated = true;
2447 result |= wl.minState;
2448 }
2449 }
2450 return result;
2451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 }
2453
2454 void setPolicy(WindowManagerPolicy p) {
2455 synchronized (mLocks) {
2456 mPolicy = p;
2457 mLocks.notifyAll();
2458 }
2459 }
2460
2461 WindowManagerPolicy getPolicyLocked() {
2462 while (mPolicy == null || !mDoneBooting) {
2463 try {
2464 mLocks.wait();
2465 } catch (InterruptedException e) {
2466 // Ignore
2467 }
2468 }
2469 return mPolicy;
2470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002473 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2474 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2475 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002476 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002477 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002478 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002479 }
2480
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002481 // wait until sensors are enabled before turning on screen.
2482 // some devices will not activate the light sensor properly on boot
2483 // unless we do this.
2484 if (mUseSoftwareAutoBrightness) {
2485 // turn the screen on
2486 setPowerState(SCREEN_BRIGHT);
2487 } else {
2488 // turn everything on
2489 setPowerState(ALL_BRIGHT);
2490 }
2491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002493 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002495
Dianne Hackborn617f8772009-03-31 15:04:46 -07002496 long identity = Binder.clearCallingIdentity();
2497 try {
2498 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2499 mBatteryStats.noteScreenOn();
2500 } catch (RemoteException e) {
2501 // Nothing interesting to do.
2502 } finally {
2503 Binder.restoreCallingIdentity(identity);
2504 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002505 }
2506 }
2507
2508 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002509 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002510 synchronized (mLocks) {
2511 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2513 updateWakeLockLocked();
2514 mLocks.notifyAll();
2515 }
2516 }
2517
2518 public void monitor() {
2519 synchronized (mLocks) { }
2520 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002521
2522 public int getSupportedWakeLockFlags() {
2523 int result = PowerManager.PARTIAL_WAKE_LOCK
2524 | PowerManager.FULL_WAKE_LOCK
2525 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2526
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002527 if (mProximitySensor != null) {
2528 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2529 }
2530
2531 return result;
2532 }
2533
Mike Lockwood237a2992009-09-15 14:42:16 -04002534 public void setBacklightBrightness(int brightness) {
2535 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2536 // Don't let applications turn the screen all the way off
2537 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002538 mLcdLight.setBrightness(brightness);
2539 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2540 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002541 long identity = Binder.clearCallingIdentity();
2542 try {
2543 mBatteryStats.noteScreenBrightness(brightness);
2544 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002545 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
Mike Lockwood237a2992009-09-15 14:42:16 -04002546 } finally {
2547 Binder.restoreCallingIdentity(identity);
2548 }
2549
2550 // update our animation state
2551 if (ANIMATE_SCREEN_LIGHTS) {
2552 mScreenBrightness.curValue = brightness;
2553 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002554 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002555 }
2556 if (ANIMATE_KEYBOARD_LIGHTS) {
2557 mKeyboardBrightness.curValue = brightness;
2558 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002559 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002560 }
2561 if (ANIMATE_BUTTON_LIGHTS) {
2562 mButtonBrightness.curValue = brightness;
2563 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002564 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002565 }
2566 }
2567
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002568 public void setAttentionLight(boolean on, int color) {
2569 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002570 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002571 }
2572
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002573 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002574 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002575 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002576 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002577 if (!mProximitySensorEnabled) {
2578 // clear calling identity so sensor manager battery stats are accurate
2579 long identity = Binder.clearCallingIdentity();
2580 try {
2581 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2582 SensorManager.SENSOR_DELAY_NORMAL);
2583 mProximitySensorEnabled = true;
2584 } finally {
2585 Binder.restoreCallingIdentity(identity);
2586 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002587 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002588 }
2589
2590 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002591 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002592 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002593 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002594 if (mProximitySensorEnabled) {
2595 // clear calling identity so sensor manager battery stats are accurate
2596 long identity = Binder.clearCallingIdentity();
2597 try {
2598 mSensorManager.unregisterListener(mProximityListener);
2599 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002600 if (mProximityPartialLock.isHeld()) {
2601 mProximityPartialLock.release();
2602 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002603 mProximitySensorEnabled = false;
2604 } finally {
2605 Binder.restoreCallingIdentity(identity);
2606 }
2607 if (mProximitySensorActive) {
2608 mProximitySensorActive = false;
2609 forceUserActivityLocked();
2610 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002611 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002612 }
2613
Mike Lockwood20f87d72009-11-05 16:08:51 -05002614 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002615 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002616 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002617 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002618 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002619 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002620 return;
2621 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002622 if (active) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002623 goToSleepLocked(SystemClock.uptimeMillis(),
2624 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002625 mProximitySensorActive = true;
2626 } else {
2627 // proximity sensor negative events trigger as user activity.
2628 // temporarily set mUserActivityAllowed to true so this will work
2629 // even when the keyguard is on.
2630 mProximitySensorActive = false;
2631 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002632
2633 if (mProximityWakeLockCount == 0) {
2634 // disable sensor if we have no listeners left after proximity negative
2635 disableProximityLockLocked();
2636 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002637 }
2638 }
2639
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002640 private void enableLightSensor(boolean enable) {
2641 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002642 Slog.d(TAG, "enableLightSensor " + enable);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002643 }
2644 if (mSensorManager != null && mLightSensorEnabled != enable) {
2645 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002646 // clear calling identity so sensor manager battery stats are accurate
2647 long identity = Binder.clearCallingIdentity();
2648 try {
2649 if (enable) {
2650 mSensorManager.registerListener(mLightListener, mLightSensor,
2651 SensorManager.SENSOR_DELAY_NORMAL);
2652 } else {
2653 mSensorManager.unregisterListener(mLightListener);
2654 mHandler.removeCallbacks(mAutoBrightnessTask);
2655 }
2656 } finally {
2657 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002658 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002659 }
2660 }
2661
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002662 SensorEventListener mProximityListener = new SensorEventListener() {
2663 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002664 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002665 synchronized (mLocks) {
2666 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002667 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2668 mLastProximityEventTime = milliseconds;
2669 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002670 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002671
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002672 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002673 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2674 distance < mProximitySensor.getMaximumRange());
2675
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002676 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002677 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002678 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002679 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2680 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2681 mProximityPendingValue = (active ? 1 : 0);
2682 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002683 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002684 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002685 // process the value immediately
2686 mProximityPendingValue = -1;
2687 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002688 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002689
2690 // update mProximityPartialLock state
2691 boolean held = mProximityPartialLock.isHeld();
2692 if (!held && proximityTaskQueued) {
2693 // hold wakelock until mProximityTask runs
2694 mProximityPartialLock.acquire();
2695 } else if (held && !proximityTaskQueued) {
2696 mProximityPartialLock.release();
2697 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002698 }
2699 }
2700
2701 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2702 // ignore
2703 }
2704 };
2705
2706 SensorEventListener mLightListener = new SensorEventListener() {
2707 public void onSensorChanged(SensorEvent event) {
2708 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002709 // ignore light sensor while screen is turning off
2710 if (isScreenTurningOffLocked()) {
2711 return;
2712 }
2713
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002714 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002715 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002716 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002717 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002718 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002719 mHandler.removeCallbacks(mAutoBrightnessTask);
2720 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002721 if (mLightSensorValue == -1 ||
2722 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2723 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002724 lightSensorChangedLocked(value);
2725 } else {
2726 // delay processing to debounce the sensor
2727 mLightSensorPendingValue = value;
2728 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2729 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002730 } else {
2731 mLightSensorPendingValue = -1;
2732 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002733 }
2734 }
2735
2736 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2737 // ignore
2738 }
2739 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740}