blob: 11b966ee87ef38f47cdce0aa3e0b98364506bb19 [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
Mike Lockwood4984e732009-11-01 08:16:33 -0500560 if (mUseSoftwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400561 // turn the screen on
562 setPowerState(SCREEN_BRIGHT);
563 } else {
564 // turn everything on
565 setPowerState(ALL_BRIGHT);
566 }
Dan Murphy951764b2009-08-27 14:59:03 -0500567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 synchronized (mHandlerThread) {
569 mInitComplete = true;
570 mHandlerThread.notifyAll();
571 }
572 }
573
574 private class WakeLock implements IBinder.DeathRecipient
575 {
576 WakeLock(int f, IBinder b, String t, int u) {
577 super();
578 flags = f;
579 binder = b;
580 tag = t;
581 uid = u == MY_UID ? Process.SYSTEM_UID : u;
582 if (u != MY_UID || (
583 !"KEEP_SCREEN_ON_FLAG".equals(tag)
584 && !"KeyInputQueue".equals(tag))) {
585 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
586 ? BatteryStats.WAKE_TYPE_PARTIAL
587 : BatteryStats.WAKE_TYPE_FULL;
588 } else {
589 monitorType = -1;
590 }
591 try {
592 b.linkToDeath(this, 0);
593 } catch (RemoteException e) {
594 binderDied();
595 }
596 }
597 public void binderDied() {
598 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500599 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 }
601 }
602 final int flags;
603 final IBinder binder;
604 final String tag;
605 final int uid;
606 final int monitorType;
607 boolean activated = true;
608 int minState;
609 }
610
611 private void updateWakeLockLocked() {
612 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
613 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
614 mStayOnWhilePluggedInScreenDimLock.acquire();
615 mStayOnWhilePluggedInPartialLock.acquire();
616 } else {
617 mStayOnWhilePluggedInScreenDimLock.release();
618 mStayOnWhilePluggedInPartialLock.release();
619 }
620 }
621
622 private boolean isScreenLock(int flags)
623 {
624 int n = flags & LOCK_MASK;
625 return n == PowerManager.FULL_WAKE_LOCK
626 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
627 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
628 }
629
630 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700632 if (uid != Process.myUid()) {
633 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 long ident = Binder.clearCallingIdentity();
636 try {
637 synchronized (mLocks) {
638 acquireWakeLockLocked(flags, lock, uid, tag);
639 }
640 } finally {
641 Binder.restoreCallingIdentity(ident);
642 }
643 }
644
645 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
646 int acquireUid = -1;
647 String acquireName = null;
648 int acquireType = -1;
649
650 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800651 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 }
653
654 int index = mLocks.getIndex(lock);
655 WakeLock wl;
656 boolean newlock;
657 if (index < 0) {
658 wl = new WakeLock(flags, lock, tag, uid);
659 switch (wl.flags & LOCK_MASK)
660 {
661 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500662 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400663 wl.minState = SCREEN_BRIGHT;
664 } else {
665 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 break;
668 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
669 wl.minState = SCREEN_BRIGHT;
670 break;
671 case PowerManager.SCREEN_DIM_WAKE_LOCK:
672 wl.minState = SCREEN_DIM;
673 break;
674 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700675 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 break;
677 default:
678 // just log and bail. we're in the server, so don't
679 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800680 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 + " flags=" + flags);
682 return;
683 }
684 mLocks.addLock(wl);
685 newlock = true;
686 } else {
687 wl = mLocks.get(index);
688 newlock = false;
689 }
690 if (isScreenLock(flags)) {
691 // if this causes a wakeup, we reactivate all of the locks and
692 // set it to whatever they want. otherwise, we modulate that
693 // by the current state so we never turn it more on than
694 // it already is.
695 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700696 int oldWakeLockState = mWakeLockState;
697 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800699 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700700 + " mWakeLockState=0x"
701 + Integer.toHexString(mWakeLockState)
702 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 } else {
705 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800706 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 + " mLocks.gatherState()=0x"
708 + Integer.toHexString(mLocks.gatherState())
709 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
710 }
711 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
712 }
713 setPowerState(mWakeLockState | mUserState);
714 }
715 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
716 if (newlock) {
717 mPartialCount++;
718 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800719 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 }
721 }
722 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700723 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500724 mProximityWakeLockCount++;
725 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700726 enableProximityLockLocked();
727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 }
729 if (newlock) {
730 acquireUid = wl.uid;
731 acquireName = wl.tag;
732 acquireType = wl.monitorType;
733 }
734
735 if (acquireType >= 0) {
736 try {
737 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
738 } catch (RemoteException e) {
739 // Ignore
740 }
741 }
742 }
743
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500744 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700745 int uid = Binder.getCallingUid();
746 if (uid != Process.myUid()) {
747 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749
750 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500751 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 }
753 }
754
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500755 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 int releaseUid;
757 String releaseName;
758 int releaseType;
759
760 WakeLock wl = mLocks.removeLock(lock);
761 if (wl == null) {
762 return;
763 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800766 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
768 }
769
770 if (isScreenLock(wl.flags)) {
771 mWakeLockState = mLocks.gatherState();
772 // goes in the middle to reduce flicker
773 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
774 userActivity(SystemClock.uptimeMillis(), false);
775 }
776 setPowerState(mWakeLockState | mUserState);
777 }
778 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
779 mPartialCount--;
780 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800781 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 Power.releaseWakeLock(PARTIAL_NAME);
783 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700784 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500785 mProximityWakeLockCount--;
786 if (mProximityWakeLockCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500787 if (mProximitySensorActive &&
788 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500789 // wait for proximity sensor to go negative before disabling sensor
790 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800791 Slog.d(TAG, "waiting for proximity sensor to go negative");
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500792 }
793 } else {
794 disableProximityLockLocked();
795 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 }
798 // Unlink the lock from the binder.
799 wl.binder.unlinkToDeath(wl, 0);
800 releaseUid = wl.uid;
801 releaseName = wl.tag;
802 releaseType = wl.monitorType;
803
804 if (releaseType >= 0) {
805 long origId = Binder.clearCallingIdentity();
806 try {
807 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
808 } catch (RemoteException e) {
809 // Ignore
810 } finally {
811 Binder.restoreCallingIdentity(origId);
812 }
813 }
814 }
815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 private class PokeLock implements IBinder.DeathRecipient
817 {
818 PokeLock(int p, IBinder b, String t) {
819 super();
820 this.pokey = p;
821 this.binder = b;
822 this.tag = t;
823 try {
824 b.linkToDeath(this, 0);
825 } catch (RemoteException e) {
826 binderDied();
827 }
828 }
829 public void binderDied() {
830 setPokeLock(0, this.binder, this.tag);
831 }
832 int pokey;
833 IBinder binder;
834 String tag;
835 boolean awakeOnSet;
836 }
837
838 public void setPokeLock(int pokey, IBinder token, String tag) {
839 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
840 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800841 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 return;
843 }
844
845 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
846 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
847 + " and POKE_LOCK_MEDIUM_TIMEOUT");
848 }
849
850 synchronized (mLocks) {
851 if (pokey != 0) {
852 PokeLock p = mPokeLocks.get(token);
853 int oldPokey = 0;
854 if (p != null) {
855 oldPokey = p.pokey;
856 p.pokey = pokey;
857 } else {
858 p = new PokeLock(pokey, token, tag);
859 mPokeLocks.put(token, p);
860 }
861 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
862 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
863 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
864 p.awakeOnSet = true;
865 }
866 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700867 PokeLock rLock = mPokeLocks.remove(token);
868 if (rLock != null) {
869 token.unlinkToDeath(rLock, 0);
870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 }
872
873 int oldPokey = mPokey;
874 int cumulative = 0;
875 boolean oldAwakeOnSet = mPokeAwakeOnSet;
876 boolean awakeOnSet = false;
877 for (PokeLock p: mPokeLocks.values()) {
878 cumulative |= p.pokey;
879 if (p.awakeOnSet) {
880 awakeOnSet = true;
881 }
882 }
883 mPokey = cumulative;
884 mPokeAwakeOnSet = awakeOnSet;
885
886 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
887 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 if (oldCumulativeTimeout != newCumulativeTimeout) {
890 setScreenOffTimeoutsLocked();
891 // reset the countdown timer, but use the existing nextState so it doesn't
892 // change anything
893 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
894 }
895 }
896 }
897
898 private static String lockType(int type)
899 {
900 switch (type)
901 {
902 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700903 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700905 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700907 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700909 return "PARTIAL_WAKE_LOCK ";
910 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
911 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 default:
David Brown251faa62009-08-02 22:04:36 -0700913 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 }
915 }
916
917 private static String dumpPowerState(int state) {
918 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
919 ? "KEYBOARD_BRIGHT_BIT " : "")
920 + (((state & SCREEN_BRIGHT_BIT) != 0)
921 ? "SCREEN_BRIGHT_BIT " : "")
922 + (((state & SCREEN_ON_BIT) != 0)
923 ? "SCREEN_ON_BIT " : "")
924 + (((state & BATTERY_LOW_BIT) != 0)
925 ? "BATTERY_LOW_BIT " : "");
926 }
927
928 @Override
929 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
930 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
931 != PackageManager.PERMISSION_GRANTED) {
932 pw.println("Permission Denial: can't dump PowerManager from from pid="
933 + Binder.getCallingPid()
934 + ", uid=" + Binder.getCallingUid());
935 return;
936 }
937
938 long now = SystemClock.uptimeMillis();
939
Mike Lockwoodca44df82010-02-25 13:48:49 -0500940 synchronized (mLocks) {
941 pw.println("Power Manager State:");
942 pw.println(" mIsPowered=" + mIsPowered
943 + " mPowerState=" + mPowerState
944 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
945 + " ms");
946 pw.println(" mPartialCount=" + mPartialCount);
947 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
948 pw.println(" mUserState=" + dumpPowerState(mUserState));
949 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
950 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
951 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
952 + " " + ((mNextTimeout-now)/1000) + "s from now");
953 pw.println(" mDimScreen=" + mDimScreen
954 + " mStayOnConditions=" + mStayOnConditions);
955 pw.println(" mScreenOffReason=" + mScreenOffReason
956 + " mUserState=" + mUserState);
957 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
958 + ',' + mBroadcastQueue[2] + "}");
959 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
960 + ',' + mBroadcastWhy[2] + "}");
961 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
962 pw.println(" mKeyboardVisible=" + mKeyboardVisible
963 + " mUserActivityAllowed=" + mUserActivityAllowed);
964 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
965 + " mScreenOffDelay=" + mScreenOffDelay);
966 pw.println(" mPreventScreenOn=" + mPreventScreenOn
967 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
968 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
969 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
970 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
971 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
972 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
973 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
974 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
975 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
976 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
977 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
978 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
979 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
980 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
981 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
982 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
983 pw.println(" mLightSensorValue=" + mLightSensorValue
984 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
985 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
986 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
987 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
988 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
989 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
990 mScreenBrightness.dump(pw, " mScreenBrightness: ");
991 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
992 mButtonBrightness.dump(pw, " mButtonBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800993
Mike Lockwoodca44df82010-02-25 13:48:49 -0500994 int N = mLocks.size();
995 pw.println();
996 pw.println("mLocks.size=" + N + ":");
997 for (int i=0; i<N; i++) {
998 WakeLock wl = mLocks.get(i);
999 String type = lockType(wl.flags & LOCK_MASK);
1000 String acquireCausesWakeup = "";
1001 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1002 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1003 }
1004 String activated = "";
1005 if (wl.activated) {
1006 activated = " activated";
1007 }
1008 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
1009 + activated + " (minState=" + wl.minState + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001011
1012 pw.println();
1013 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1014 for (PokeLock p: mPokeLocks.values()) {
1015 pw.println(" poke lock '" + p.tag + "':"
1016 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
1017 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
1018 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
1019 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
1020 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1021 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1022 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1023 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001025
Mike Lockwoodca44df82010-02-25 13:48:49 -05001026 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 }
1029
1030 private void setTimeoutLocked(long now, int nextState)
1031 {
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001032 if (mBootCompleted) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 mHandler.removeCallbacks(mTimeoutTask);
1034 mTimeoutTask.nextState = nextState;
1035 long when = now;
1036 switch (nextState)
1037 {
1038 case SCREEN_BRIGHT:
1039 when += mKeylightDelay;
1040 break;
1041 case SCREEN_DIM:
1042 if (mDimDelay >= 0) {
1043 when += mDimDelay;
1044 break;
1045 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001046 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
1048 case SCREEN_OFF:
1049 synchronized (mLocks) {
1050 when += mScreenOffDelay;
1051 }
1052 break;
1053 }
1054 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001055 Slog.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 + " when=" + when);
1057 }
1058 mHandler.postAtTime(mTimeoutTask, when);
1059 mNextTimeout = when; // for debugging
1060 }
1061 }
1062
1063 private void cancelTimerLocked()
1064 {
1065 mHandler.removeCallbacks(mTimeoutTask);
1066 mTimeoutTask.nextState = -1;
1067 }
1068
1069 private class TimeoutTask implements Runnable
1070 {
1071 int nextState; // access should be synchronized on mLocks
1072 public void run()
1073 {
1074 synchronized (mLocks) {
1075 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001076 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 }
1078
1079 if (nextState == -1) {
1080 return;
1081 }
1082
1083 mUserState = this.nextState;
1084 setPowerState(this.nextState | mWakeLockState);
1085
1086 long now = SystemClock.uptimeMillis();
1087
1088 switch (this.nextState)
1089 {
1090 case SCREEN_BRIGHT:
1091 if (mDimDelay >= 0) {
1092 setTimeoutLocked(now, SCREEN_DIM);
1093 break;
1094 }
1095 case SCREEN_DIM:
1096 setTimeoutLocked(now, SCREEN_OFF);
1097 break;
1098 }
1099 }
1100 }
1101 }
1102
1103 private void sendNotificationLocked(boolean on, int why)
1104 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001105 if (!on) {
1106 mStillNeedSleepNotification = false;
1107 }
1108
Joe Onorato128e7292009-03-24 18:41:31 -07001109 // Add to the queue.
1110 int index = 0;
1111 while (mBroadcastQueue[index] != -1) {
1112 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 }
Joe Onorato128e7292009-03-24 18:41:31 -07001114 mBroadcastQueue[index] = on ? 1 : 0;
1115 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116
Joe Onorato128e7292009-03-24 18:41:31 -07001117 // If we added it position 2, then there is a pair that can be stripped.
1118 // If we added it position 1 and we're turning the screen off, we can strip
1119 // the pair and do nothing, because the screen is already off, and therefore
1120 // keyguard has already been enabled.
1121 // However, if we added it at position 1 and we're turning it on, then position
1122 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1123 // on, so have to run the queue then.
1124 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001125 // While we're collapsing them, if it's going off, and the new reason
1126 // is more significant than the first, then use the new one.
1127 if (!on && mBroadcastWhy[0] > why) {
1128 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001129 }
1130 mBroadcastQueue[0] = on ? 1 : 0;
1131 mBroadcastQueue[1] = -1;
1132 mBroadcastQueue[2] = -1;
1133 index = 0;
1134 }
1135 if (index == 1 && !on) {
1136 mBroadcastQueue[0] = -1;
1137 mBroadcastQueue[1] = -1;
1138 index = -1;
1139 // The wake lock was being held, but we're not actually going to do any
1140 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001141 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001143 }
1144
1145 // Now send the message.
1146 if (index >= 0) {
1147 // Acquire the broadcast wake lock before changing the power
1148 // state. It will be release after the broadcast is sent.
1149 // We always increment the ref count for each notification in the queue
1150 // and always decrement when that notification is handled.
1151 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001152 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001153 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 }
1155 }
1156
1157 private Runnable mNotificationTask = new Runnable()
1158 {
1159 public void run()
1160 {
Joe Onorato128e7292009-03-24 18:41:31 -07001161 while (true) {
1162 int value;
1163 int why;
1164 WindowManagerPolicy policy;
1165 synchronized (mLocks) {
1166 value = mBroadcastQueue[0];
1167 why = mBroadcastWhy[0];
1168 for (int i=0; i<2; i++) {
1169 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1170 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1171 }
1172 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 }
Joe Onorato128e7292009-03-24 18:41:31 -07001174 if (value == 1) {
1175 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001176
Joe Onorato128e7292009-03-24 18:41:31 -07001177 policy.screenTurnedOn();
1178 try {
1179 ActivityManagerNative.getDefault().wakingUp();
1180 } catch (RemoteException e) {
1181 // ignore it
1182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183
Joe Onorato128e7292009-03-24 18:41:31 -07001184 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001185 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001186 }
1187 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1188 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1189 mScreenOnBroadcastDone, mHandler, 0, null, null);
1190 } else {
1191 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001192 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001193 mBroadcastWakeLock.mCount);
1194 mBroadcastWakeLock.release();
1195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 }
1197 }
Joe Onorato128e7292009-03-24 18:41:31 -07001198 else if (value == 0) {
1199 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001200
Joe Onorato128e7292009-03-24 18:41:31 -07001201 policy.screenTurnedOff(why);
1202 try {
1203 ActivityManagerNative.getDefault().goingToSleep();
1204 } catch (RemoteException e) {
1205 // ignore it.
1206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207
Joe Onorato128e7292009-03-24 18:41:31 -07001208 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1209 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1210 mScreenOffBroadcastDone, mHandler, 0, null, null);
1211 } else {
1212 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001213 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001214 mBroadcastWakeLock.mCount);
1215 mBroadcastWakeLock.release();
1216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 }
1218 }
Joe Onorato128e7292009-03-24 18:41:31 -07001219 else {
1220 // If we're in this case, then this handler is running for a previous
1221 // paired transaction. mBroadcastWakeLock will already have been released.
1222 break;
1223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 }
1225 }
1226 };
1227
1228 long mScreenOnStart;
1229 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1230 public void onReceive(Context context, Intent intent) {
1231 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001232 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1234 mBroadcastWakeLock.release();
1235 }
1236 }
1237 };
1238
1239 long mScreenOffStart;
1240 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1241 public void onReceive(Context context, Intent intent) {
1242 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001243 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1245 mBroadcastWakeLock.release();
1246 }
1247 }
1248 };
1249
1250 void logPointerUpEvent() {
1251 if (LOG_TOUCH_DOWNS) {
1252 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1253 mLastTouchDown = 0;
1254 }
1255 }
1256
1257 void logPointerDownEvent() {
1258 if (LOG_TOUCH_DOWNS) {
1259 // If we are not already timing a down/up sequence
1260 if (mLastTouchDown == 0) {
1261 mLastTouchDown = SystemClock.elapsedRealtime();
1262 mTouchCycles++;
1263 }
1264 }
1265 }
1266
1267 /**
1268 * Prevents the screen from turning on even if it *should* turn on due
1269 * to a subsequent full wake lock being acquired.
1270 * <p>
1271 * This is a temporary hack that allows an activity to "cover up" any
1272 * display glitches that happen during the activity's startup
1273 * sequence. (Specifically, this API was added to work around a
1274 * cosmetic bug in the "incoming call" sequence, where the lock screen
1275 * would flicker briefly before the incoming call UI became visible.)
1276 * TODO: There ought to be a more elegant way of doing this,
1277 * probably by having the PowerManager and ActivityManager
1278 * work together to let apps specify that the screen on/off
1279 * state should be synchronized with the Activity lifecycle.
1280 * <p>
1281 * Note that calling preventScreenOn(true) will NOT turn the screen
1282 * off if it's currently on. (This API only affects *future*
1283 * acquisitions of full wake locks.)
1284 * But calling preventScreenOn(false) WILL turn the screen on if
1285 * it's currently off because of a prior preventScreenOn(true) call.
1286 * <p>
1287 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1288 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1289 * call doesn't occur within 5 seconds, we'll turn the screen back on
1290 * ourselves (and log a warning about it); this prevents a buggy app
1291 * from disabling the screen forever.)
1292 * <p>
1293 * TODO: this feature should really be controlled by a new type of poke
1294 * lock (rather than an IPowerManager call).
1295 */
1296 public void preventScreenOn(boolean prevent) {
1297 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1298
1299 synchronized (mLocks) {
1300 if (prevent) {
1301 // First of all, grab a partial wake lock to
1302 // make sure the CPU stays on during the entire
1303 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1304 mPreventScreenOnPartialLock.acquire();
1305
1306 // Post a forceReenableScreen() call (for 5 seconds in the
1307 // future) to make sure the matching preventScreenOn(false) call
1308 // has happened by then.
1309 mHandler.removeCallbacks(mForceReenableScreenTask);
1310 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1311
1312 // Finally, set the flag that prevents the screen from turning on.
1313 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001314 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 mPreventScreenOn = true;
1316 } else {
1317 // (Re)enable the screen.
1318 mPreventScreenOn = false;
1319
1320 // We're "undoing" a the prior preventScreenOn(true) call, so we
1321 // no longer need the 5-second safeguard.
1322 mHandler.removeCallbacks(mForceReenableScreenTask);
1323
1324 // Forcibly turn on the screen if it's supposed to be on. (This
1325 // handles the case where the screen is currently off because of
1326 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001327 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001329 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1331 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001332 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001334 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
1336 }
1337
1338 // Release the partial wake lock that we held during the
1339 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1340 mPreventScreenOnPartialLock.release();
1341 }
1342 }
1343 }
1344
1345 public void setScreenBrightnessOverride(int brightness) {
1346 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1347
1348 synchronized (mLocks) {
1349 if (mScreenBrightnessOverride != brightness) {
1350 mScreenBrightnessOverride = brightness;
1351 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1352 }
1353 }
1354 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001355
1356 public void setButtonBrightnessOverride(int brightness) {
1357 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1358
1359 synchronized (mLocks) {
1360 if (mButtonBrightnessOverride != brightness) {
1361 mButtonBrightnessOverride = brightness;
1362 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1363 }
1364 }
1365 }
1366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 /**
1368 * Sanity-check that gets called 5 seconds after any call to
1369 * preventScreenOn(true). This ensures that the original call
1370 * is followed promptly by a call to preventScreenOn(false).
1371 */
1372 private void forceReenableScreen() {
1373 // We shouldn't get here at all if mPreventScreenOn is false, since
1374 // we should have already removed any existing
1375 // mForceReenableScreenTask messages...
1376 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001377 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 return;
1379 }
1380
1381 // Uh oh. It's been 5 seconds since a call to
1382 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1383 // This means the app that called preventScreenOn(true) is either
1384 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1385 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1386 // crashed before doing so.)
1387
1388 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001389 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 + "Forcing the screen back on...");
1391 preventScreenOn(false);
1392 }
1393
1394 private Runnable mForceReenableScreenTask = new Runnable() {
1395 public void run() {
1396 forceReenableScreen();
1397 }
1398 };
1399
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001400 private int setScreenStateLocked(boolean on) {
1401 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001402 if (err == 0) {
1403 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1404 if (mUseSoftwareAutoBrightness) {
1405 enableLightSensor(on);
1406 if (!on) {
1407 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001408 mButtonLight.turnOff();
1409 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001410 // clear current value so we will update based on the new conditions
1411 // when the sensor is reenabled.
1412 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001413 // reset our highest light sensor value when the screen turns off
1414 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001415 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001416 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001417 }
1418 return err;
1419 }
1420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 private void setPowerState(int state)
1422 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001423 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
1425
Mike Lockwood435eb642009-12-03 08:40:18 -05001426 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 {
1428 synchronized (mLocks) {
1429 int err;
1430
1431 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001432 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001434 + " noChangeLights=" + noChangeLights
1435 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 }
1437
1438 if (noChangeLights) {
1439 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1440 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001441 if (mProximitySensorActive) {
1442 // don't turn on the screen when the proximity sensor lock is held
1443 newState = (newState & ~SCREEN_BRIGHT);
1444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445
1446 if (batteryIsLow()) {
1447 newState |= BATTERY_LOW_BIT;
1448 } else {
1449 newState &= ~BATTERY_LOW_BIT;
1450 }
1451 if (newState == mPowerState) {
1452 return;
1453 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001454
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001455 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 newState |= ALL_BRIGHT;
1457 }
1458
1459 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1460 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1461
Mike Lockwood51b84492009-11-16 21:51:18 -05001462 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001463 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001465 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001467 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001469 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001471 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001473 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1475 }
1476
1477 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001478 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1480 }
1481
1482 if (oldScreenOn != newScreenOn) {
1483 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001484 // When the user presses the power button, we need to always send out the
1485 // notification that it's going to sleep so the keyguard goes on. But
1486 // we can't do that until the screen fades out, so we don't show the keyguard
1487 // too early.
1488 if (mStillNeedSleepNotification) {
1489 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1490 }
1491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 // Turn on the screen UNLESS there was a prior
1493 // preventScreenOn(true) request. (Note that the lifetime
1494 // of a single preventScreenOn() request is limited to 5
1495 // seconds to prevent a buggy app from disabling the
1496 // screen forever; see forceReenableScreen().)
1497 boolean reallyTurnScreenOn = true;
1498 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001499 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 + mPreventScreenOn);
1501 }
1502
1503 if (mPreventScreenOn) {
1504 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001505 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
1507 reallyTurnScreenOn = false;
1508 }
1509 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001510 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 long identity = Binder.clearCallingIdentity();
1512 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001513 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 mBatteryStats.noteScreenOn();
1515 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001516 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 } finally {
1518 Binder.restoreCallingIdentity(identity);
1519 }
1520 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001521 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 // But continue as if we really did turn the screen on...
1523 err = 0;
1524 }
1525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 mLastTouchDown = 0;
1527 mTotalTouchDownTime = 0;
1528 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001529 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 mTotalTouchDownTime, mTouchCycles);
1531 if (err == 0) {
1532 mPowerState |= SCREEN_ON_BIT;
1533 sendNotificationLocked(true, -1);
1534 }
1535 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001536 // cancel light sensor task
1537 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 mScreenOffTime = SystemClock.elapsedRealtime();
1539 long identity = Binder.clearCallingIdentity();
1540 try {
1541 mBatteryStats.noteScreenOff();
1542 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001543 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 } finally {
1545 Binder.restoreCallingIdentity(identity);
1546 }
1547 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001548 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001550 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 err = 0;
1553 mLastTouchDown = 0;
1554 }
1555 }
1556 }
1557 }
1558 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001559
Mike Lockwood435eb642009-12-03 08:40:18 -05001560 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001562 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001564 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001566 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001568 mScreenOffReason = reason;
1569 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 }
1571 return err;
1572 }
1573
1574 private boolean batteryIsLow() {
1575 return (!mIsPowered &&
1576 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1577 }
1578
The Android Open Source Project10592532009-03-18 17:39:46 -07001579 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001580 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001581 newState = applyButtonState(newState);
1582 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001583 final int realDifference = (newState ^ oldState);
1584 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001586 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 int offMask = 0;
1590 int dimMask = 0;
1591 int onMask = 0;
1592
1593 int preferredBrightness = getPreferredBrightness();
1594 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1597 if (ANIMATE_KEYBOARD_LIGHTS) {
1598 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1599 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001600 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001601 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001603 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001604 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1605 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 }
1607 startAnimation = true;
1608 } else {
1609 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001610 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001612 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 }
1614 }
1615 }
1616
1617 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1618 if (ANIMATE_BUTTON_LIGHTS) {
1619 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1620 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001621 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001622 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001624 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001625 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1626 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 }
1628 startAnimation = true;
1629 } else {
1630 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001631 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001633 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 }
1635 }
1636 }
1637
1638 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1639 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001640 int nominalCurrentValue = -1;
1641 // If there was an actual difference in the light state, then
1642 // figure out the "ideal" current value based on the previous
1643 // state. Otherwise, this is a change due to the brightness
1644 // override, so we want to animate from whatever the current
1645 // value is.
1646 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1647 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1648 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1649 nominalCurrentValue = preferredBrightness;
1650 break;
1651 case SCREEN_ON_BIT:
1652 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1653 break;
1654 case 0:
1655 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1656 break;
1657 case SCREEN_BRIGHT_BIT:
1658 default:
1659 // not possible
1660 nominalCurrentValue = (int)mScreenBrightness.curValue;
1661 break;
1662 }
Joe Onorato128e7292009-03-24 18:41:31 -07001663 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001664 int brightness = preferredBrightness;
1665 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1667 // dim or turn off backlight, depending on if the screen is on
1668 // the scale is because the brightness ramp isn't linear and this biases
1669 // it so the later parts take longer.
1670 final float scale = 1.5f;
1671 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1672 if (ratio > 1.0f) ratio = 1.0f;
1673 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1675 // was bright
1676 steps = ANIM_STEPS;
1677 } else {
1678 // was dim
1679 steps = (int)(ANIM_STEPS*ratio*scale);
1680 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001681 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 if ((oldState & SCREEN_ON_BIT) != 0) {
1684 // was bright
1685 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1686 } else {
1687 // was dim
1688 steps = (int)(ANIM_STEPS*ratio);
1689 }
1690 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1691 // If the "stay on while plugged in" option is
1692 // turned on, then the screen will often not
1693 // automatically turn off while plugged in. To
1694 // still have a sense of when it is inactive, we
1695 // will then count going dim as turning off.
1696 mScreenOffTime = SystemClock.elapsedRealtime();
1697 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001698 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001701 long identity = Binder.clearCallingIdentity();
1702 try {
1703 mBatteryStats.noteScreenBrightness(brightness);
1704 } catch (RemoteException e) {
1705 // Nothing interesting to do.
1706 } finally {
1707 Binder.restoreCallingIdentity(identity);
1708 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001709 if (mScreenBrightness.setTargetLocked(brightness,
1710 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1711 startAnimation = true;
1712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 } else {
1714 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1715 // dim or turn off backlight, depending on if the screen is on
1716 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001717 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001719 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 }
1721 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001722 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 }
1724 }
1725 }
1726
1727 if (startAnimation) {
1728 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001729 Slog.i(TAG, "Scheduling light animator!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 }
1731 mHandler.removeCallbacks(mLightAnimator);
1732 mHandler.post(mLightAnimator);
1733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 if (offMask != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001736 //Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001737 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
1739 if (dimMask != 0) {
1740 int brightness = Power.BRIGHTNESS_DIM;
1741 if ((newState & BATTERY_LOW_BIT) != 0 &&
1742 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1743 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1744 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001745 //Slog.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001746 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 }
1748 if (onMask != 0) {
1749 int brightness = getPreferredBrightness();
1750 if ((newState & BATTERY_LOW_BIT) != 0 &&
1751 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1752 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1753 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001754 //Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001755 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758
The Android Open Source Project10592532009-03-18 17:39:46 -07001759 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001760 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001761 ? LightsService.BRIGHTNESS_MODE_SENSOR
1762 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001763 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001764 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001765 }
1766 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001767 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001768 }
1769 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001770 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 }
1773
1774 class BrightnessState {
1775 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 boolean initialized;
1778 int targetValue;
1779 float curValue;
1780 float delta;
1781 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 BrightnessState(int m) {
1784 mask = m;
1785 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 public void dump(PrintWriter pw, String prefix) {
1788 pw.println(prefix + "animating=" + animating
1789 + " targetValue=" + targetValue
1790 + " curValue=" + curValue
1791 + " delta=" + delta);
1792 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001793
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001794 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001795 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 if (!initialized) {
1797 initialized = true;
1798 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001799 } else if (targetValue == target) {
1800 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 }
1802 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001803 delta = (targetValue -
1804 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1805 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001807 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato8a9b2202010-02-26 18:56:32 -08001808 Slog.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001809 + " target=" + targetValue + " delta=" + delta
1810 + " nominalCurrentValue=" + nominalCurrentValue
1811 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 }
1813 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001814 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 boolean stepLocked() {
1818 if (!animating) return false;
1819 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001820 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 + " target=" + targetValue + " delta=" + delta);
1822 }
1823 curValue += delta;
1824 int curIntValue = (int)curValue;
1825 boolean more = true;
1826 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001827 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 more = false;
1829 } else if (delta > 0) {
1830 if (curIntValue >= targetValue) {
1831 curValue = curIntValue = targetValue;
1832 more = false;
1833 }
1834 } else {
1835 if (curIntValue <= targetValue) {
1836 curValue = curIntValue = targetValue;
1837 more = false;
1838 }
1839 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001840 //Slog.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001841 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 animating = more;
1843 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001844 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001845 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 }
1847 }
1848 return more;
1849 }
1850 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 private class LightAnimator implements Runnable {
1853 public void run() {
1854 synchronized (mLocks) {
1855 long now = SystemClock.uptimeMillis();
1856 boolean more = mScreenBrightness.stepLocked();
1857 if (mKeyboardBrightness.stepLocked()) {
1858 more = true;
1859 }
1860 if (mButtonBrightness.stepLocked()) {
1861 more = true;
1862 }
1863 if (more) {
1864 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1865 }
1866 }
1867 }
1868 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 private int getPreferredBrightness() {
1871 try {
1872 if (mScreenBrightnessOverride >= 0) {
1873 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001874 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001875 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001876 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 }
1878 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1879 SCREEN_BRIGHTNESS);
1880 // Don't let applications turn the screen all the way off
1881 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1882 } catch (SettingNotFoundException snfe) {
1883 return Power.BRIGHTNESS_ON;
1884 }
1885 }
1886
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001887 private int applyButtonState(int state) {
1888 int brightness = -1;
1889 if (mButtonBrightnessOverride >= 0) {
1890 brightness = mButtonBrightnessOverride;
1891 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
1892 brightness = mLightSensorButtonBrightness;
1893 }
1894 if (brightness > 0) {
1895 return state | BUTTON_BRIGHT_BIT;
1896 } else if (brightness == 0) {
1897 return state & ~BUTTON_BRIGHT_BIT;
1898 } else {
1899 return state;
1900 }
1901 }
1902
1903 private int applyKeyboardState(int state) {
1904 int brightness = -1;
1905 if (!mKeyboardVisible) {
1906 brightness = 0;
1907 } else if (mButtonBrightnessOverride >= 0) {
1908 brightness = mButtonBrightnessOverride;
1909 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
1910 brightness = mLightSensorKeyboardBrightness;
1911 }
1912 if (brightness > 0) {
1913 return state | KEYBOARD_BRIGHT_BIT;
1914 } else if (brightness == 0) {
1915 return state & ~KEYBOARD_BRIGHT_BIT;
1916 } else {
1917 return state;
1918 }
1919 }
1920
Charles Mendis322591c2009-10-29 11:06:59 -07001921 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001922 synchronized (mLocks) {
1923 return (mPowerState & SCREEN_ON_BIT) != 0;
1924 }
1925 }
1926
Charles Mendis322591c2009-10-29 11:06:59 -07001927 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 synchronized (mLocks) {
1929 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1930 }
1931 }
1932
Mike Lockwood497087e32009-11-08 18:33:03 -05001933 private boolean isScreenTurningOffLocked() {
1934 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1935 }
1936
Mike Lockwood200b30b2009-09-20 00:23:59 -04001937 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05001938 if (isScreenTurningOffLocked()) {
1939 // cancel animation so userActivity will succeed
1940 mScreenBrightness.animating = false;
1941 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04001942 boolean savedActivityAllowed = mUserActivityAllowed;
1943 mUserActivityAllowed = true;
1944 userActivity(SystemClock.uptimeMillis(), false);
1945 mUserActivityAllowed = savedActivityAllowed;
1946 }
1947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1949 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1950 userActivity(time, noChangeLights, OTHER_EVENT, force);
1951 }
1952
1953 public void userActivity(long time, boolean noChangeLights) {
1954 userActivity(time, noChangeLights, OTHER_EVENT, false);
1955 }
1956
1957 public void userActivity(long time, boolean noChangeLights, int eventType) {
1958 userActivity(time, noChangeLights, eventType, false);
1959 }
1960
1961 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1962 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1963
1964 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001965 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001967 Slog.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 }
1969 return;
1970 }
1971
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001972 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1973 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1974 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1975 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001976 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001977 }
1978 return;
1979 }
1980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 if (false) {
1982 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001983 Slog.d(TAG, "userActivity !!!");//, new RuntimeException());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001985 Slog.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 }
1987 }
1988
1989 synchronized (mLocks) {
1990 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001991 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 + " mUserActivityAllowed=" + mUserActivityAllowed
1993 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001994 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1995 + " mProximitySensorActive=" + mProximitySensorActive
1996 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 }
Mike Lockwood05067122009-10-27 23:07:25 -04001998 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05001999 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002000 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002001 return;
2002 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002003 // Disable proximity sensor if if user presses power key while we are in the
2004 // "waiting for proximity sensor to go negative" state.
2005 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2006 mProximitySensorActive = false;
2007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 if (mLastEventTime <= time || force) {
2009 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002010 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002011 // Only turn on button backlights if a button was pressed
2012 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002013 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2015 } else {
2016 // don't clear button/keyboard backlights when the screen is touched.
2017 mUserState |= SCREEN_BRIGHT;
2018 }
2019
Dianne Hackborn617f8772009-03-31 15:04:46 -07002020 int uid = Binder.getCallingUid();
2021 long ident = Binder.clearCallingIdentity();
2022 try {
2023 mBatteryStats.noteUserActivity(uid, eventType);
2024 } catch (RemoteException e) {
2025 // Ignore
2026 } finally {
2027 Binder.restoreCallingIdentity(ident);
2028 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002029
Michael Chane96440f2009-05-06 10:27:36 -07002030 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002031 setPowerState(mUserState | mWakeLockState, noChangeLights,
2032 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 setTimeoutLocked(time, SCREEN_BRIGHT);
2034 }
2035 }
2036 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002037
2038 if (mPolicy != null) {
2039 mPolicy.userActivity();
2040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 }
2042
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002043 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2044 try {
2045 int i;
2046 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2047 if (sensorValue < mAutoBrightnessLevels[i]) {
2048 break;
2049 }
2050 }
2051 return values[i];
2052 } catch (Exception e) {
2053 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002054 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002055 return 255;
2056 }
2057 }
2058
Mike Lockwood20f87d72009-11-05 16:08:51 -05002059 private Runnable mProximityTask = new Runnable() {
2060 public void run() {
2061 synchronized (mLocks) {
2062 if (mProximityPendingValue != -1) {
2063 proximityChangedLocked(mProximityPendingValue == 1);
2064 mProximityPendingValue = -1;
2065 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002066 if (mProximityPartialLock.isHeld()) {
2067 mProximityPartialLock.release();
2068 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002069 }
2070 }
2071 };
2072
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002073 private Runnable mAutoBrightnessTask = new Runnable() {
2074 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002075 synchronized (mLocks) {
2076 int value = (int)mLightSensorPendingValue;
2077 if (value >= 0) {
2078 mLightSensorPendingValue = -1;
2079 lightSensorChangedLocked(value);
2080 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002081 }
2082 }
2083 };
2084
Mike Lockwoodb2865412010-02-02 22:40:33 -05002085 private void dockStateChanged(int state) {
2086 synchronized (mLocks) {
2087 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2088 if (mIsDocked) {
2089 mHighestLightSensorValue = -1;
2090 }
2091 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2092 // force lights recalculation
2093 int value = (int)mLightSensorValue;
2094 mLightSensorValue = -1;
2095 lightSensorChangedLocked(value);
2096 }
2097 }
2098 }
2099
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002100 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002101 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002102 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002103 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002104
Mike Lockwoodb2865412010-02-02 22:40:33 -05002105 // do not allow light sensor value to decrease
2106 if (mHighestLightSensorValue < value) {
2107 mHighestLightSensorValue = value;
2108 }
2109
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002110 if (mLightSensorValue != value) {
2111 mLightSensorValue = value;
2112 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002113 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2114 // we only do this if we are undocked, since lighting should be stable when
2115 // stationary in a dock.
2116 int lcdValue = getAutoBrightnessValue(
2117 (mIsDocked ? value : mHighestLightSensorValue),
2118 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002119 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002120 int keyboardValue;
2121 if (mKeyboardVisible) {
2122 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2123 } else {
2124 keyboardValue = 0;
2125 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002126 mLightSensorScreenBrightness = lcdValue;
2127 mLightSensorButtonBrightness = buttonValue;
2128 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002129
2130 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002131 Slog.d(TAG, "lcdValue " + lcdValue);
2132 Slog.d(TAG, "buttonValue " + buttonValue);
2133 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002134 }
2135
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002136 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002137 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002138 if (ANIMATE_SCREEN_LIGHTS) {
2139 if (mScreenBrightness.setTargetLocked(lcdValue,
2140 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2141 (int)mScreenBrightness.curValue)) {
2142 startAnimation = true;
2143 }
2144 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002145 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002146 ? LightsService.BRIGHTNESS_MODE_SENSOR
2147 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002148 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002149 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002150 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002151 if (mButtonBrightnessOverride < 0) {
2152 if (ANIMATE_BUTTON_LIGHTS) {
2153 if (mButtonBrightness.setTargetLocked(buttonValue,
2154 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2155 (int)mButtonBrightness.curValue)) {
2156 startAnimation = true;
2157 }
2158 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002159 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002160 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002161 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002162 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2163 if (ANIMATE_KEYBOARD_LIGHTS) {
2164 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2165 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2166 (int)mKeyboardBrightness.curValue)) {
2167 startAnimation = true;
2168 }
2169 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002170 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002171 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002172 }
2173 if (startAnimation) {
2174 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002175 Slog.i(TAG, "lightSensorChangedLocked scheduling light animator");
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002176 }
2177 mHandler.removeCallbacks(mLightAnimator);
2178 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002179 }
2180 }
2181 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002182 }
2183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 /**
2185 * The user requested that we go to sleep (probably with the power button).
2186 * This overrides all wake locks that are held.
2187 */
2188 public void goToSleep(long time)
2189 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002190 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2191 }
2192
2193 /**
2194 * The user requested that we go to sleep (probably with the power button).
2195 * This overrides all wake locks that are held.
2196 */
2197 public void goToSleepWithReason(long time, int reason)
2198 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2200 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002201 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 }
2203 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002206 * Reboot the device immediately, passing 'reason' (may be null)
2207 * to the underlying __reboot system call. Should not return.
2208 */
2209 public void reboot(String reason)
2210 {
2211 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002212
San Mehat1e512792010-01-07 10:40:29 -08002213 /*
2214 * Manually shutdown the MountService to ensure media is
2215 * put into a safe state.
2216 */
2217 IMountService mSvc = IMountService.Stub.asInterface(
2218 ServiceManager.getService("mount"));
2219
2220 if (mSvc != null) {
2221 try {
2222 mSvc.shutdown();
2223 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002224 Slog.e(TAG, "MountService shutdown failed", e);
San Mehat1e512792010-01-07 10:40:29 -08002225 }
2226 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002227 Slog.w(TAG, "MountService unavailable for shutdown");
San Mehat1e512792010-01-07 10:40:29 -08002228 }
San Mehat14e69af2010-01-06 14:58:18 -08002229
Doug Zongker50a21f42009-11-19 12:49:53 -08002230 try {
2231 Power.reboot(reason);
2232 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002233 Slog.e(TAG, "reboot failed", e);
Doug Zongker50a21f42009-11-19 12:49:53 -08002234 }
2235 }
2236
Dan Egnor60d87622009-12-16 16:32:58 -08002237 /**
2238 * Crash the runtime (causing a complete restart of the Android framework).
2239 * Requires REBOOT permission. Mostly for testing. Should not return.
2240 */
2241 public void crash(final String message)
2242 {
2243 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2244 Thread t = new Thread("PowerManagerService.crash()") {
2245 public void run() { throw new RuntimeException(message); }
2246 };
2247 try {
2248 t.start();
2249 t.join();
2250 } catch (InterruptedException e) {
2251 Log.wtf(TAG, e);
2252 }
2253 }
2254
Mike Lockwood435eb642009-12-03 08:40:18 -05002255 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256
2257 if (mLastEventTime <= time) {
2258 mLastEventTime = time;
2259 // cancel all of the wake locks
2260 mWakeLockState = SCREEN_OFF;
2261 int N = mLocks.size();
2262 int numCleared = 0;
2263 for (int i=0; i<N; i++) {
2264 WakeLock wl = mLocks.get(i);
2265 if (isScreenLock(wl.flags)) {
2266 mLocks.get(i).activated = false;
2267 numCleared++;
2268 }
2269 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002270 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002271 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002273 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 cancelTimerLocked();
2275 }
2276 }
2277
2278 public long timeSinceScreenOn() {
2279 synchronized (mLocks) {
2280 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2281 return 0;
2282 }
2283 return SystemClock.elapsedRealtime() - mScreenOffTime;
2284 }
2285 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002288 synchronized (mLocks) {
2289 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002290 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002291 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002292 if (mKeyboardVisible != visible) {
2293 mKeyboardVisible = visible;
2294 // don't signal user activity if the screen is off; other code
2295 // will take care of turning on due to a true change to the lid
2296 // switch and synchronized with the lock screen.
2297 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002298 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002299 // force recompute of backlight values
2300 if (mLightSensorValue >= 0) {
2301 int value = (int)mLightSensorValue;
2302 mLightSensorValue = -1;
2303 lightSensorChangedLocked(value);
2304 }
2305 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002306 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2307 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002308 }
2309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 }
2311
2312 /**
2313 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002314 * When disabling user activity we also reset user power state so the keyguard can reset its
2315 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002316 */
2317 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002318 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002319 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 synchronized (mLocks) {
2322 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002323 if (!enabled) {
2324 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2325 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327 }
2328 }
2329
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002330 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002331 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002332 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002333 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002334 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002335 // force recompute of backlight values
2336 if (mLightSensorValue >= 0) {
2337 int value = (int)mLightSensorValue;
2338 mLightSensorValue = -1;
2339 lightSensorChangedLocked(value);
2340 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002341 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002342 }
2343 }
2344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 /** Sets the screen off timeouts:
2346 * mKeylightDelay
2347 * mDimDelay
2348 * mScreenOffDelay
2349 * */
2350 private void setScreenOffTimeoutsLocked() {
2351 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002352 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 mDimDelay = -1;
2354 mScreenOffDelay = 0;
2355 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2356 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2357 mDimDelay = -1;
2358 mScreenOffDelay = 0;
2359 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002360 int totalDelay = mScreenOffTimeoutSetting;
2361 if (totalDelay > mMaximumScreenOffTimeout) {
2362 totalDelay = mMaximumScreenOffTimeout;
2363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2365 if (totalDelay < 0) {
2366 mScreenOffDelay = Integer.MAX_VALUE;
2367 } else if (mKeylightDelay < totalDelay) {
2368 // subtract the time that the keylight delay. This will give us the
2369 // remainder of the time that we need to sleep to get the accurate
2370 // screen off timeout.
2371 mScreenOffDelay = totalDelay - mKeylightDelay;
2372 } else {
2373 mScreenOffDelay = 0;
2374 }
2375 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2376 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2377 mScreenOffDelay = LONG_DIM_TIME;
2378 } else {
2379 mDimDelay = -1;
2380 }
2381 }
2382 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002383 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2385 + " mDimScreen=" + mDimScreen);
2386 }
2387 }
2388
2389 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002390 * Refreshes cached secure settings. Called once on startup, and
2391 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 */
Doug Zongker43866e02010-01-07 12:09:54 -08002393 private void updateSettingsValues() {
2394 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002396 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002398 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002399 }
2400
2401 private class LockList extends ArrayList<WakeLock>
2402 {
2403 void addLock(WakeLock wl)
2404 {
2405 int index = getIndex(wl.binder);
2406 if (index < 0) {
2407 this.add(wl);
2408 }
2409 }
2410
2411 WakeLock removeLock(IBinder binder)
2412 {
2413 int index = getIndex(binder);
2414 if (index >= 0) {
2415 return this.remove(index);
2416 } else {
2417 return null;
2418 }
2419 }
2420
2421 int getIndex(IBinder binder)
2422 {
2423 int N = this.size();
2424 for (int i=0; i<N; i++) {
2425 if (this.get(i).binder == binder) {
2426 return i;
2427 }
2428 }
2429 return -1;
2430 }
2431
2432 int gatherState()
2433 {
2434 int result = 0;
2435 int N = this.size();
2436 for (int i=0; i<N; i++) {
2437 WakeLock wl = this.get(i);
2438 if (wl.activated) {
2439 if (isScreenLock(wl.flags)) {
2440 result |= wl.minState;
2441 }
2442 }
2443 }
2444 return result;
2445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002446
Michael Chane96440f2009-05-06 10:27:36 -07002447 int reactivateScreenLocksLocked()
2448 {
2449 int result = 0;
2450 int N = this.size();
2451 for (int i=0; i<N; i++) {
2452 WakeLock wl = this.get(i);
2453 if (isScreenLock(wl.flags)) {
2454 wl.activated = true;
2455 result |= wl.minState;
2456 }
2457 }
2458 return result;
2459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 }
2461
2462 void setPolicy(WindowManagerPolicy p) {
2463 synchronized (mLocks) {
2464 mPolicy = p;
2465 mLocks.notifyAll();
2466 }
2467 }
2468
2469 WindowManagerPolicy getPolicyLocked() {
2470 while (mPolicy == null || !mDoneBooting) {
2471 try {
2472 mLocks.wait();
2473 } catch (InterruptedException e) {
2474 // Ignore
2475 }
2476 }
2477 return mPolicy;
2478 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002481 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2482 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2483 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002484 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002485 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002486 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002487 }
2488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002490 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002492 long identity = Binder.clearCallingIdentity();
2493 try {
2494 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2495 mBatteryStats.noteScreenOn();
2496 } catch (RemoteException e) {
2497 // Nothing interesting to do.
2498 } finally {
2499 Binder.restoreCallingIdentity(identity);
2500 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002501 }
2502 }
2503
2504 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002505 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002506 synchronized (mLocks) {
2507 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2509 updateWakeLockLocked();
2510 mLocks.notifyAll();
2511 }
2512 }
2513
2514 public void monitor() {
2515 synchronized (mLocks) { }
2516 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002517
2518 public int getSupportedWakeLockFlags() {
2519 int result = PowerManager.PARTIAL_WAKE_LOCK
2520 | PowerManager.FULL_WAKE_LOCK
2521 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2522
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002523 if (mProximitySensor != null) {
2524 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2525 }
2526
2527 return result;
2528 }
2529
Mike Lockwood237a2992009-09-15 14:42:16 -04002530 public void setBacklightBrightness(int brightness) {
2531 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2532 // Don't let applications turn the screen all the way off
2533 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002534 mLcdLight.setBrightness(brightness);
2535 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2536 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002537 long identity = Binder.clearCallingIdentity();
2538 try {
2539 mBatteryStats.noteScreenBrightness(brightness);
2540 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002541 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
Mike Lockwood237a2992009-09-15 14:42:16 -04002542 } finally {
2543 Binder.restoreCallingIdentity(identity);
2544 }
2545
2546 // update our animation state
2547 if (ANIMATE_SCREEN_LIGHTS) {
2548 mScreenBrightness.curValue = brightness;
2549 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002550 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002551 }
2552 if (ANIMATE_KEYBOARD_LIGHTS) {
2553 mKeyboardBrightness.curValue = brightness;
2554 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002555 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002556 }
2557 if (ANIMATE_BUTTON_LIGHTS) {
2558 mButtonBrightness.curValue = brightness;
2559 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002560 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002561 }
2562 }
2563
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002564 public void setAttentionLight(boolean on, int color) {
2565 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002566 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002567 }
2568
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002569 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002570 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002571 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002572 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002573 if (!mProximitySensorEnabled) {
2574 // clear calling identity so sensor manager battery stats are accurate
2575 long identity = Binder.clearCallingIdentity();
2576 try {
2577 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2578 SensorManager.SENSOR_DELAY_NORMAL);
2579 mProximitySensorEnabled = true;
2580 } finally {
2581 Binder.restoreCallingIdentity(identity);
2582 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002583 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002584 }
2585
2586 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002587 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002588 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002589 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002590 if (mProximitySensorEnabled) {
2591 // clear calling identity so sensor manager battery stats are accurate
2592 long identity = Binder.clearCallingIdentity();
2593 try {
2594 mSensorManager.unregisterListener(mProximityListener);
2595 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002596 if (mProximityPartialLock.isHeld()) {
2597 mProximityPartialLock.release();
2598 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002599 mProximitySensorEnabled = false;
2600 } finally {
2601 Binder.restoreCallingIdentity(identity);
2602 }
2603 if (mProximitySensorActive) {
2604 mProximitySensorActive = false;
2605 forceUserActivityLocked();
2606 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002607 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002608 }
2609
Mike Lockwood20f87d72009-11-05 16:08:51 -05002610 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002611 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002612 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002613 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002614 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002615 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002616 return;
2617 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002618 if (active) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002619 goToSleepLocked(SystemClock.uptimeMillis(),
2620 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002621 mProximitySensorActive = true;
2622 } else {
2623 // proximity sensor negative events trigger as user activity.
2624 // temporarily set mUserActivityAllowed to true so this will work
2625 // even when the keyguard is on.
2626 mProximitySensorActive = false;
2627 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002628
2629 if (mProximityWakeLockCount == 0) {
2630 // disable sensor if we have no listeners left after proximity negative
2631 disableProximityLockLocked();
2632 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002633 }
2634 }
2635
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002636 private void enableLightSensor(boolean enable) {
2637 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002638 Slog.d(TAG, "enableLightSensor " + enable);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002639 }
2640 if (mSensorManager != null && mLightSensorEnabled != enable) {
2641 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002642 // clear calling identity so sensor manager battery stats are accurate
2643 long identity = Binder.clearCallingIdentity();
2644 try {
2645 if (enable) {
2646 mSensorManager.registerListener(mLightListener, mLightSensor,
2647 SensorManager.SENSOR_DELAY_NORMAL);
2648 } else {
2649 mSensorManager.unregisterListener(mLightListener);
2650 mHandler.removeCallbacks(mAutoBrightnessTask);
2651 }
2652 } finally {
2653 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002654 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002655 }
2656 }
2657
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002658 SensorEventListener mProximityListener = new SensorEventListener() {
2659 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002660 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002661 synchronized (mLocks) {
2662 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002663 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2664 mLastProximityEventTime = milliseconds;
2665 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002666 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002667
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002668 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002669 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2670 distance < mProximitySensor.getMaximumRange());
2671
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002672 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002673 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002674 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002675 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2676 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2677 mProximityPendingValue = (active ? 1 : 0);
2678 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002679 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002680 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002681 // process the value immediately
2682 mProximityPendingValue = -1;
2683 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002684 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002685
2686 // update mProximityPartialLock state
2687 boolean held = mProximityPartialLock.isHeld();
2688 if (!held && proximityTaskQueued) {
2689 // hold wakelock until mProximityTask runs
2690 mProximityPartialLock.acquire();
2691 } else if (held && !proximityTaskQueued) {
2692 mProximityPartialLock.release();
2693 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002694 }
2695 }
2696
2697 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2698 // ignore
2699 }
2700 };
2701
2702 SensorEventListener mLightListener = new SensorEventListener() {
2703 public void onSensorChanged(SensorEvent event) {
2704 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002705 // ignore light sensor while screen is turning off
2706 if (isScreenTurningOffLocked()) {
2707 return;
2708 }
2709
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002710 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002711 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002712 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002713 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002714 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002715 mHandler.removeCallbacks(mAutoBrightnessTask);
2716 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002717 if (mLightSensorValue == -1 ||
2718 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2719 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002720 lightSensorChangedLocked(value);
2721 } else {
2722 // delay processing to debounce the sensor
2723 mLightSensorPendingValue = value;
2724 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2725 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002726 } else {
2727 mLightSensorPendingValue = -1;
2728 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002729 }
2730 }
2731
2732 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2733 // ignore
2734 }
2735 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736}