blob: d3efa1222dabc92610206e96f3f5bd2ec2a896d4 [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.
352 // temporarily set mUserActivityAllowed to true so this will work
353 // even when the keyguard is on.
354 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400355 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 }
357 }
358 }
359 }
360 }
361
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500362 private final class BootCompletedReceiver extends BroadcastReceiver {
363 @Override
364 public void onReceive(Context context, Intent intent) {
365 bootCompleted();
366 }
367 }
368
Mike Lockwoodb2865412010-02-02 22:40:33 -0500369 private final class DockReceiver extends BroadcastReceiver {
370 @Override
371 public void onReceive(Context context, Intent intent) {
372 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
373 Intent.EXTRA_DOCK_STATE_UNDOCKED);
374 dockStateChanged(state);
375 }
376 }
377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 /**
379 * Set the setting that determines whether the device stays on when plugged in.
380 * The argument is a bit string, with each bit specifying a power source that,
381 * when the device is connected to that source, causes the device to stay on.
382 * See {@link android.os.BatteryManager} for the list of power sources that
383 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
384 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
385 * @param val an {@code int} containing the bits that specify which power sources
386 * should cause the device to stay on.
387 */
388 public void setStayOnSetting(int val) {
389 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
390 Settings.System.putInt(mContext.getContentResolver(),
391 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
392 }
393
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800394 public void setMaximumScreenOffTimeount(int timeMs) {
395 mContext.enforceCallingOrSelfPermission(
396 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
397 synchronized (mLocks) {
398 mMaximumScreenOffTimeout = timeMs;
399 // recalculate everything
400 setScreenOffTimeoutsLocked();
401 }
402 }
403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 private class SettingsObserver implements Observer {
405 private int getInt(String name) {
406 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
407 }
408
409 public void update(Observable o, Object arg) {
410 synchronized (mLocks) {
411 // STAY_ON_WHILE_PLUGGED_IN
412 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
413 updateWakeLockLocked();
414
415 // SCREEN_OFF_TIMEOUT
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800416 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417
418 // DIM_SCREEN
419 //mDimScreen = getInt(DIM_SCREEN) != 0;
420
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700421 // SCREEN_BRIGHTNESS_MODE
422 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 // recalculate everything
425 setScreenOffTimeoutsLocked();
426 }
427 }
428 }
429
430 PowerManagerService()
431 {
432 // Hack to get our uid... should have a func for this.
433 long token = Binder.clearCallingIdentity();
434 MY_UID = Binder.getCallingUid();
435 Binder.restoreCallingIdentity(token);
436
437 // XXX remove this when the kernel doesn't timeout wake locks
438 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
439
440 // assume nothing is on yet
441 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 // Add ourself to the Watchdog monitors.
444 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 }
446
447 private ContentQueryMap mSettings;
448
Mike Lockwood3a322132009-11-24 00:30:52 -0500449 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700450 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500451 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 mContext = context;
453 mActivityService = activity;
454 mBatteryStats = BatteryStatsService.getService();
455 mBatteryService = battery;
456
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500457 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
458 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
459 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
460 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 mHandlerThread = new HandlerThread("PowerManagerService") {
463 @Override
464 protected void onLooperPrepared() {
465 super.onLooperPrepared();
466 initInThread();
467 }
468 };
469 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 synchronized (mHandlerThread) {
472 while (!mInitComplete) {
473 try {
474 mHandlerThread.wait();
475 } catch (InterruptedException e) {
476 // Ignore
477 }
478 }
479 }
480 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 void initInThread() {
483 mHandler = new Handler();
484
485 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700486 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
488 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
489 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
490 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
491 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
492 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500493 mProximityPartialLock = new UnsynchronizedWakeLock(
494 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495
496 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
497 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
498 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
499 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
500
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700501 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400502
503 // read settings for auto-brightness
504 mUseSoftwareAutoBrightness = resources.getBoolean(
505 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400506 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700507 mAutoBrightnessLevels = resources.getIntArray(
508 com.android.internal.R.array.config_autoBrightnessLevels);
509 mLcdBacklightValues = resources.getIntArray(
510 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
511 mButtonBacklightValues = resources.getIntArray(
512 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
513 mKeyboardBacklightValues = resources.getIntArray(
514 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500515 mLightSensorWarmupTime = resources.getInteger(
516 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700517 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700518
519 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
521 "(" + Settings.System.NAME + "=?) or ("
522 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700523 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700525 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
526 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 null);
528 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
529 SettingsObserver settingsObserver = new SettingsObserver();
530 mSettings.addObserver(settingsObserver);
531
532 // pretend that the settings changed so we will get their initial state
533 settingsObserver.update(mSettings, null);
534
535 // register for the battery changed notifications
536 IntentFilter filter = new IntentFilter();
537 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
538 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500539 filter = new IntentFilter();
540 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
541 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500542 filter = new IntentFilter();
543 filter.addAction(Intent.ACTION_DOCK_EVENT);
544 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545
Doug Zongker43866e02010-01-07 12:09:54 -0800546 // Listen for secure settings changes
547 mContext.getContentResolver().registerContentObserver(
548 Settings.Secure.CONTENT_URI, true,
549 new ContentObserver(new Handler()) {
550 public void onChange(boolean selfChange) {
551 updateSettingsValues();
552 }
553 });
554 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555
Mike Lockwood4984e732009-11-01 08:16:33 -0500556 if (mUseSoftwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400557 // turn the screen on
558 setPowerState(SCREEN_BRIGHT);
559 } else {
560 // turn everything on
561 setPowerState(ALL_BRIGHT);
562 }
Dan Murphy951764b2009-08-27 14:59:03 -0500563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 synchronized (mHandlerThread) {
565 mInitComplete = true;
566 mHandlerThread.notifyAll();
567 }
568 }
569
570 private class WakeLock implements IBinder.DeathRecipient
571 {
572 WakeLock(int f, IBinder b, String t, int u) {
573 super();
574 flags = f;
575 binder = b;
576 tag = t;
577 uid = u == MY_UID ? Process.SYSTEM_UID : u;
578 if (u != MY_UID || (
579 !"KEEP_SCREEN_ON_FLAG".equals(tag)
580 && !"KeyInputQueue".equals(tag))) {
581 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
582 ? BatteryStats.WAKE_TYPE_PARTIAL
583 : BatteryStats.WAKE_TYPE_FULL;
584 } else {
585 monitorType = -1;
586 }
587 try {
588 b.linkToDeath(this, 0);
589 } catch (RemoteException e) {
590 binderDied();
591 }
592 }
593 public void binderDied() {
594 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500595 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 }
597 }
598 final int flags;
599 final IBinder binder;
600 final String tag;
601 final int uid;
602 final int monitorType;
603 boolean activated = true;
604 int minState;
605 }
606
607 private void updateWakeLockLocked() {
608 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
609 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
610 mStayOnWhilePluggedInScreenDimLock.acquire();
611 mStayOnWhilePluggedInPartialLock.acquire();
612 } else {
613 mStayOnWhilePluggedInScreenDimLock.release();
614 mStayOnWhilePluggedInPartialLock.release();
615 }
616 }
617
618 private boolean isScreenLock(int flags)
619 {
620 int n = flags & LOCK_MASK;
621 return n == PowerManager.FULL_WAKE_LOCK
622 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
623 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
624 }
625
626 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700628 if (uid != Process.myUid()) {
629 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 long ident = Binder.clearCallingIdentity();
632 try {
633 synchronized (mLocks) {
634 acquireWakeLockLocked(flags, lock, uid, tag);
635 }
636 } finally {
637 Binder.restoreCallingIdentity(ident);
638 }
639 }
640
641 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
642 int acquireUid = -1;
643 String acquireName = null;
644 int acquireType = -1;
645
646 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800647 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 }
649
650 int index = mLocks.getIndex(lock);
651 WakeLock wl;
652 boolean newlock;
653 if (index < 0) {
654 wl = new WakeLock(flags, lock, tag, uid);
655 switch (wl.flags & LOCK_MASK)
656 {
657 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500658 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400659 wl.minState = SCREEN_BRIGHT;
660 } else {
661 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 break;
664 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
665 wl.minState = SCREEN_BRIGHT;
666 break;
667 case PowerManager.SCREEN_DIM_WAKE_LOCK:
668 wl.minState = SCREEN_DIM;
669 break;
670 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700671 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 break;
673 default:
674 // just log and bail. we're in the server, so don't
675 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800676 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 + " flags=" + flags);
678 return;
679 }
680 mLocks.addLock(wl);
681 newlock = true;
682 } else {
683 wl = mLocks.get(index);
684 newlock = false;
685 }
686 if (isScreenLock(flags)) {
687 // if this causes a wakeup, we reactivate all of the locks and
688 // set it to whatever they want. otherwise, we modulate that
689 // by the current state so we never turn it more on than
690 // it already is.
691 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700692 int oldWakeLockState = mWakeLockState;
693 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800695 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700696 + " mWakeLockState=0x"
697 + Integer.toHexString(mWakeLockState)
698 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 } else {
701 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800702 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 + " mLocks.gatherState()=0x"
704 + Integer.toHexString(mLocks.gatherState())
705 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
706 }
707 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
708 }
709 setPowerState(mWakeLockState | mUserState);
710 }
711 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
712 if (newlock) {
713 mPartialCount++;
714 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800715 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 }
717 }
718 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700719 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500720 mProximityWakeLockCount++;
721 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700722 enableProximityLockLocked();
723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 }
725 if (newlock) {
726 acquireUid = wl.uid;
727 acquireName = wl.tag;
728 acquireType = wl.monitorType;
729 }
730
731 if (acquireType >= 0) {
732 try {
733 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
734 } catch (RemoteException e) {
735 // Ignore
736 }
737 }
738 }
739
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500740 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700741 int uid = Binder.getCallingUid();
742 if (uid != Process.myUid()) {
743 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745
746 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500747 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 }
749 }
750
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500751 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 int releaseUid;
753 String releaseName;
754 int releaseType;
755
756 WakeLock wl = mLocks.removeLock(lock);
757 if (wl == null) {
758 return;
759 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800762 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
764 }
765
766 if (isScreenLock(wl.flags)) {
767 mWakeLockState = mLocks.gatherState();
768 // goes in the middle to reduce flicker
769 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
770 userActivity(SystemClock.uptimeMillis(), false);
771 }
772 setPowerState(mWakeLockState | mUserState);
773 }
774 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
775 mPartialCount--;
776 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800777 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 Power.releaseWakeLock(PARTIAL_NAME);
779 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700780 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500781 mProximityWakeLockCount--;
782 if (mProximityWakeLockCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500783 if (mProximitySensorActive &&
784 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500785 // wait for proximity sensor to go negative before disabling sensor
786 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800787 Slog.d(TAG, "waiting for proximity sensor to go negative");
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500788 }
789 } else {
790 disableProximityLockLocked();
791 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 }
794 // Unlink the lock from the binder.
795 wl.binder.unlinkToDeath(wl, 0);
796 releaseUid = wl.uid;
797 releaseName = wl.tag;
798 releaseType = wl.monitorType;
799
800 if (releaseType >= 0) {
801 long origId = Binder.clearCallingIdentity();
802 try {
803 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
804 } catch (RemoteException e) {
805 // Ignore
806 } finally {
807 Binder.restoreCallingIdentity(origId);
808 }
809 }
810 }
811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 private class PokeLock implements IBinder.DeathRecipient
813 {
814 PokeLock(int p, IBinder b, String t) {
815 super();
816 this.pokey = p;
817 this.binder = b;
818 this.tag = t;
819 try {
820 b.linkToDeath(this, 0);
821 } catch (RemoteException e) {
822 binderDied();
823 }
824 }
825 public void binderDied() {
826 setPokeLock(0, this.binder, this.tag);
827 }
828 int pokey;
829 IBinder binder;
830 String tag;
831 boolean awakeOnSet;
832 }
833
834 public void setPokeLock(int pokey, IBinder token, String tag) {
835 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
836 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800837 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 return;
839 }
840
841 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
842 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
843 + " and POKE_LOCK_MEDIUM_TIMEOUT");
844 }
845
846 synchronized (mLocks) {
847 if (pokey != 0) {
848 PokeLock p = mPokeLocks.get(token);
849 int oldPokey = 0;
850 if (p != null) {
851 oldPokey = p.pokey;
852 p.pokey = pokey;
853 } else {
854 p = new PokeLock(pokey, token, tag);
855 mPokeLocks.put(token, p);
856 }
857 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
858 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
859 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
860 p.awakeOnSet = true;
861 }
862 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700863 PokeLock rLock = mPokeLocks.remove(token);
864 if (rLock != null) {
865 token.unlinkToDeath(rLock, 0);
866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 }
868
869 int oldPokey = mPokey;
870 int cumulative = 0;
871 boolean oldAwakeOnSet = mPokeAwakeOnSet;
872 boolean awakeOnSet = false;
873 for (PokeLock p: mPokeLocks.values()) {
874 cumulative |= p.pokey;
875 if (p.awakeOnSet) {
876 awakeOnSet = true;
877 }
878 }
879 mPokey = cumulative;
880 mPokeAwakeOnSet = awakeOnSet;
881
882 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
883 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 if (oldCumulativeTimeout != newCumulativeTimeout) {
886 setScreenOffTimeoutsLocked();
887 // reset the countdown timer, but use the existing nextState so it doesn't
888 // change anything
889 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
890 }
891 }
892 }
893
894 private static String lockType(int type)
895 {
896 switch (type)
897 {
898 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700899 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700901 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700903 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700905 return "PARTIAL_WAKE_LOCK ";
906 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
907 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 default:
David Brown251faa62009-08-02 22:04:36 -0700909 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 }
911 }
912
913 private static String dumpPowerState(int state) {
914 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
915 ? "KEYBOARD_BRIGHT_BIT " : "")
916 + (((state & SCREEN_BRIGHT_BIT) != 0)
917 ? "SCREEN_BRIGHT_BIT " : "")
918 + (((state & SCREEN_ON_BIT) != 0)
919 ? "SCREEN_ON_BIT " : "")
920 + (((state & BATTERY_LOW_BIT) != 0)
921 ? "BATTERY_LOW_BIT " : "");
922 }
923
924 @Override
925 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
926 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
927 != PackageManager.PERMISSION_GRANTED) {
928 pw.println("Permission Denial: can't dump PowerManager from from pid="
929 + Binder.getCallingPid()
930 + ", uid=" + Binder.getCallingUid());
931 return;
932 }
933
934 long now = SystemClock.uptimeMillis();
935
Mike Lockwoodca44df82010-02-25 13:48:49 -0500936 synchronized (mLocks) {
937 pw.println("Power Manager State:");
938 pw.println(" mIsPowered=" + mIsPowered
939 + " mPowerState=" + mPowerState
940 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
941 + " ms");
942 pw.println(" mPartialCount=" + mPartialCount);
943 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
944 pw.println(" mUserState=" + dumpPowerState(mUserState));
945 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
946 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
947 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
948 + " " + ((mNextTimeout-now)/1000) + "s from now");
949 pw.println(" mDimScreen=" + mDimScreen
950 + " mStayOnConditions=" + mStayOnConditions);
951 pw.println(" mScreenOffReason=" + mScreenOffReason
952 + " mUserState=" + mUserState);
953 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
954 + ',' + mBroadcastQueue[2] + "}");
955 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
956 + ',' + mBroadcastWhy[2] + "}");
957 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
958 pw.println(" mKeyboardVisible=" + mKeyboardVisible
959 + " mUserActivityAllowed=" + mUserActivityAllowed);
960 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
961 + " mScreenOffDelay=" + mScreenOffDelay);
962 pw.println(" mPreventScreenOn=" + mPreventScreenOn
963 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
964 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
965 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
966 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
967 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
968 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
969 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
970 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
971 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
972 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
973 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
974 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
975 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
976 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
977 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
978 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
979 pw.println(" mLightSensorValue=" + mLightSensorValue
980 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
981 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
982 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
983 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
984 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
985 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
986 mScreenBrightness.dump(pw, " mScreenBrightness: ");
987 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
988 mButtonBrightness.dump(pw, " mButtonBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800989
Mike Lockwoodca44df82010-02-25 13:48:49 -0500990 int N = mLocks.size();
991 pw.println();
992 pw.println("mLocks.size=" + N + ":");
993 for (int i=0; i<N; i++) {
994 WakeLock wl = mLocks.get(i);
995 String type = lockType(wl.flags & LOCK_MASK);
996 String acquireCausesWakeup = "";
997 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
998 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
999 }
1000 String activated = "";
1001 if (wl.activated) {
1002 activated = " activated";
1003 }
1004 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
1005 + activated + " (minState=" + wl.minState + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001007
1008 pw.println();
1009 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1010 for (PokeLock p: mPokeLocks.values()) {
1011 pw.println(" poke lock '" + p.tag + "':"
1012 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
1013 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
1014 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
1015 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
1016 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1017 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1018 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1019 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001021
Mike Lockwoodca44df82010-02-25 13:48:49 -05001022 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
1025
1026 private void setTimeoutLocked(long now, int nextState)
1027 {
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001028 if (mBootCompleted) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 mHandler.removeCallbacks(mTimeoutTask);
1030 mTimeoutTask.nextState = nextState;
1031 long when = now;
1032 switch (nextState)
1033 {
1034 case SCREEN_BRIGHT:
1035 when += mKeylightDelay;
1036 break;
1037 case SCREEN_DIM:
1038 if (mDimDelay >= 0) {
1039 when += mDimDelay;
1040 break;
1041 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001042 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 }
1044 case SCREEN_OFF:
1045 synchronized (mLocks) {
1046 when += mScreenOffDelay;
1047 }
1048 break;
1049 }
1050 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001051 Slog.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 + " when=" + when);
1053 }
1054 mHandler.postAtTime(mTimeoutTask, when);
1055 mNextTimeout = when; // for debugging
1056 }
1057 }
1058
1059 private void cancelTimerLocked()
1060 {
1061 mHandler.removeCallbacks(mTimeoutTask);
1062 mTimeoutTask.nextState = -1;
1063 }
1064
1065 private class TimeoutTask implements Runnable
1066 {
1067 int nextState; // access should be synchronized on mLocks
1068 public void run()
1069 {
1070 synchronized (mLocks) {
1071 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001072 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
1074
1075 if (nextState == -1) {
1076 return;
1077 }
1078
1079 mUserState = this.nextState;
1080 setPowerState(this.nextState | mWakeLockState);
1081
1082 long now = SystemClock.uptimeMillis();
1083
1084 switch (this.nextState)
1085 {
1086 case SCREEN_BRIGHT:
1087 if (mDimDelay >= 0) {
1088 setTimeoutLocked(now, SCREEN_DIM);
1089 break;
1090 }
1091 case SCREEN_DIM:
1092 setTimeoutLocked(now, SCREEN_OFF);
1093 break;
1094 }
1095 }
1096 }
1097 }
1098
1099 private void sendNotificationLocked(boolean on, int why)
1100 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001101 if (!on) {
1102 mStillNeedSleepNotification = false;
1103 }
1104
Joe Onorato128e7292009-03-24 18:41:31 -07001105 // Add to the queue.
1106 int index = 0;
1107 while (mBroadcastQueue[index] != -1) {
1108 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 }
Joe Onorato128e7292009-03-24 18:41:31 -07001110 mBroadcastQueue[index] = on ? 1 : 0;
1111 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112
Joe Onorato128e7292009-03-24 18:41:31 -07001113 // If we added it position 2, then there is a pair that can be stripped.
1114 // If we added it position 1 and we're turning the screen off, we can strip
1115 // the pair and do nothing, because the screen is already off, and therefore
1116 // keyguard has already been enabled.
1117 // However, if we added it at position 1 and we're turning it on, then position
1118 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1119 // on, so have to run the queue then.
1120 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001121 // While we're collapsing them, if it's going off, and the new reason
1122 // is more significant than the first, then use the new one.
1123 if (!on && mBroadcastWhy[0] > why) {
1124 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001125 }
1126 mBroadcastQueue[0] = on ? 1 : 0;
1127 mBroadcastQueue[1] = -1;
1128 mBroadcastQueue[2] = -1;
1129 index = 0;
1130 }
1131 if (index == 1 && !on) {
1132 mBroadcastQueue[0] = -1;
1133 mBroadcastQueue[1] = -1;
1134 index = -1;
1135 // The wake lock was being held, but we're not actually going to do any
1136 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001137 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001139 }
1140
1141 // Now send the message.
1142 if (index >= 0) {
1143 // Acquire the broadcast wake lock before changing the power
1144 // state. It will be release after the broadcast is sent.
1145 // We always increment the ref count for each notification in the queue
1146 // and always decrement when that notification is handled.
1147 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001148 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001149 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 }
1151 }
1152
1153 private Runnable mNotificationTask = new Runnable()
1154 {
1155 public void run()
1156 {
Joe Onorato128e7292009-03-24 18:41:31 -07001157 while (true) {
1158 int value;
1159 int why;
1160 WindowManagerPolicy policy;
1161 synchronized (mLocks) {
1162 value = mBroadcastQueue[0];
1163 why = mBroadcastWhy[0];
1164 for (int i=0; i<2; i++) {
1165 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1166 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1167 }
1168 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 }
Joe Onorato128e7292009-03-24 18:41:31 -07001170 if (value == 1) {
1171 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001172
Joe Onorato128e7292009-03-24 18:41:31 -07001173 policy.screenTurnedOn();
1174 try {
1175 ActivityManagerNative.getDefault().wakingUp();
1176 } catch (RemoteException e) {
1177 // ignore it
1178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179
Joe Onorato128e7292009-03-24 18:41:31 -07001180 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001181 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001182 }
1183 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1184 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1185 mScreenOnBroadcastDone, mHandler, 0, null, null);
1186 } else {
1187 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001188 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001189 mBroadcastWakeLock.mCount);
1190 mBroadcastWakeLock.release();
1191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 }
1193 }
Joe Onorato128e7292009-03-24 18:41:31 -07001194 else if (value == 0) {
1195 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001196
Joe Onorato128e7292009-03-24 18:41:31 -07001197 policy.screenTurnedOff(why);
1198 try {
1199 ActivityManagerNative.getDefault().goingToSleep();
1200 } catch (RemoteException e) {
1201 // ignore it.
1202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203
Joe Onorato128e7292009-03-24 18:41:31 -07001204 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1205 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1206 mScreenOffBroadcastDone, mHandler, 0, null, null);
1207 } else {
1208 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001209 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001210 mBroadcastWakeLock.mCount);
1211 mBroadcastWakeLock.release();
1212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 }
1214 }
Joe Onorato128e7292009-03-24 18:41:31 -07001215 else {
1216 // If we're in this case, then this handler is running for a previous
1217 // paired transaction. mBroadcastWakeLock will already have been released.
1218 break;
1219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 }
1221 }
1222 };
1223
1224 long mScreenOnStart;
1225 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1226 public void onReceive(Context context, Intent intent) {
1227 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001228 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1230 mBroadcastWakeLock.release();
1231 }
1232 }
1233 };
1234
1235 long mScreenOffStart;
1236 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1237 public void onReceive(Context context, Intent intent) {
1238 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001239 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1241 mBroadcastWakeLock.release();
1242 }
1243 }
1244 };
1245
1246 void logPointerUpEvent() {
1247 if (LOG_TOUCH_DOWNS) {
1248 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1249 mLastTouchDown = 0;
1250 }
1251 }
1252
1253 void logPointerDownEvent() {
1254 if (LOG_TOUCH_DOWNS) {
1255 // If we are not already timing a down/up sequence
1256 if (mLastTouchDown == 0) {
1257 mLastTouchDown = SystemClock.elapsedRealtime();
1258 mTouchCycles++;
1259 }
1260 }
1261 }
1262
1263 /**
1264 * Prevents the screen from turning on even if it *should* turn on due
1265 * to a subsequent full wake lock being acquired.
1266 * <p>
1267 * This is a temporary hack that allows an activity to "cover up" any
1268 * display glitches that happen during the activity's startup
1269 * sequence. (Specifically, this API was added to work around a
1270 * cosmetic bug in the "incoming call" sequence, where the lock screen
1271 * would flicker briefly before the incoming call UI became visible.)
1272 * TODO: There ought to be a more elegant way of doing this,
1273 * probably by having the PowerManager and ActivityManager
1274 * work together to let apps specify that the screen on/off
1275 * state should be synchronized with the Activity lifecycle.
1276 * <p>
1277 * Note that calling preventScreenOn(true) will NOT turn the screen
1278 * off if it's currently on. (This API only affects *future*
1279 * acquisitions of full wake locks.)
1280 * But calling preventScreenOn(false) WILL turn the screen on if
1281 * it's currently off because of a prior preventScreenOn(true) call.
1282 * <p>
1283 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1284 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1285 * call doesn't occur within 5 seconds, we'll turn the screen back on
1286 * ourselves (and log a warning about it); this prevents a buggy app
1287 * from disabling the screen forever.)
1288 * <p>
1289 * TODO: this feature should really be controlled by a new type of poke
1290 * lock (rather than an IPowerManager call).
1291 */
1292 public void preventScreenOn(boolean prevent) {
1293 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1294
1295 synchronized (mLocks) {
1296 if (prevent) {
1297 // First of all, grab a partial wake lock to
1298 // make sure the CPU stays on during the entire
1299 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1300 mPreventScreenOnPartialLock.acquire();
1301
1302 // Post a forceReenableScreen() call (for 5 seconds in the
1303 // future) to make sure the matching preventScreenOn(false) call
1304 // has happened by then.
1305 mHandler.removeCallbacks(mForceReenableScreenTask);
1306 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1307
1308 // Finally, set the flag that prevents the screen from turning on.
1309 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001310 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 mPreventScreenOn = true;
1312 } else {
1313 // (Re)enable the screen.
1314 mPreventScreenOn = false;
1315
1316 // We're "undoing" a the prior preventScreenOn(true) call, so we
1317 // no longer need the 5-second safeguard.
1318 mHandler.removeCallbacks(mForceReenableScreenTask);
1319
1320 // Forcibly turn on the screen if it's supposed to be on. (This
1321 // handles the case where the screen is currently off because of
1322 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001323 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001325 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1327 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001328 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001330 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 }
1332 }
1333
1334 // Release the partial wake lock that we held during the
1335 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1336 mPreventScreenOnPartialLock.release();
1337 }
1338 }
1339 }
1340
1341 public void setScreenBrightnessOverride(int brightness) {
1342 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1343
1344 synchronized (mLocks) {
1345 if (mScreenBrightnessOverride != brightness) {
1346 mScreenBrightnessOverride = brightness;
1347 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1348 }
1349 }
1350 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001351
1352 public void setButtonBrightnessOverride(int brightness) {
1353 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1354
1355 synchronized (mLocks) {
1356 if (mButtonBrightnessOverride != brightness) {
1357 mButtonBrightnessOverride = brightness;
1358 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1359 }
1360 }
1361 }
1362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 /**
1364 * Sanity-check that gets called 5 seconds after any call to
1365 * preventScreenOn(true). This ensures that the original call
1366 * is followed promptly by a call to preventScreenOn(false).
1367 */
1368 private void forceReenableScreen() {
1369 // We shouldn't get here at all if mPreventScreenOn is false, since
1370 // we should have already removed any existing
1371 // mForceReenableScreenTask messages...
1372 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001373 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 return;
1375 }
1376
1377 // Uh oh. It's been 5 seconds since a call to
1378 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1379 // This means the app that called preventScreenOn(true) is either
1380 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1381 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1382 // crashed before doing so.)
1383
1384 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001385 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 + "Forcing the screen back on...");
1387 preventScreenOn(false);
1388 }
1389
1390 private Runnable mForceReenableScreenTask = new Runnable() {
1391 public void run() {
1392 forceReenableScreen();
1393 }
1394 };
1395
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001396 private int setScreenStateLocked(boolean on) {
1397 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001398 if (err == 0) {
1399 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1400 if (mUseSoftwareAutoBrightness) {
1401 enableLightSensor(on);
1402 if (!on) {
1403 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001404 mButtonLight.turnOff();
1405 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001406 // clear current value so we will update based on the new conditions
1407 // when the sensor is reenabled.
1408 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001409 // reset our highest light sensor value when the screen turns off
1410 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001411 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001412 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001413 }
1414 return err;
1415 }
1416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 private void setPowerState(int state)
1418 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001419 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
1421
Mike Lockwood435eb642009-12-03 08:40:18 -05001422 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 {
1424 synchronized (mLocks) {
1425 int err;
1426
1427 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001428 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001430 + " noChangeLights=" + noChangeLights
1431 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 }
1433
1434 if (noChangeLights) {
1435 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1436 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001437 if (mProximitySensorActive) {
1438 // don't turn on the screen when the proximity sensor lock is held
1439 newState = (newState & ~SCREEN_BRIGHT);
1440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441
1442 if (batteryIsLow()) {
1443 newState |= BATTERY_LOW_BIT;
1444 } else {
1445 newState &= ~BATTERY_LOW_BIT;
1446 }
1447 if (newState == mPowerState) {
1448 return;
1449 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001450
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001451 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 newState |= ALL_BRIGHT;
1453 }
1454
1455 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1456 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1457
Mike Lockwood51b84492009-11-16 21:51:18 -05001458 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001459 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001461 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001463 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001465 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001467 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001469 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1471 }
1472
1473 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001474 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1476 }
1477
1478 if (oldScreenOn != newScreenOn) {
1479 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001480 // When the user presses the power button, we need to always send out the
1481 // notification that it's going to sleep so the keyguard goes on. But
1482 // we can't do that until the screen fades out, so we don't show the keyguard
1483 // too early.
1484 if (mStillNeedSleepNotification) {
1485 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1486 }
1487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 // Turn on the screen UNLESS there was a prior
1489 // preventScreenOn(true) request. (Note that the lifetime
1490 // of a single preventScreenOn() request is limited to 5
1491 // seconds to prevent a buggy app from disabling the
1492 // screen forever; see forceReenableScreen().)
1493 boolean reallyTurnScreenOn = true;
1494 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001495 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 + mPreventScreenOn);
1497 }
1498
1499 if (mPreventScreenOn) {
1500 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001501 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 }
1503 reallyTurnScreenOn = false;
1504 }
1505 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001506 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 long identity = Binder.clearCallingIdentity();
1508 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001509 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 mBatteryStats.noteScreenOn();
1511 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001512 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 } finally {
1514 Binder.restoreCallingIdentity(identity);
1515 }
1516 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001517 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 // But continue as if we really did turn the screen on...
1519 err = 0;
1520 }
1521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 mLastTouchDown = 0;
1523 mTotalTouchDownTime = 0;
1524 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001525 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 mTotalTouchDownTime, mTouchCycles);
1527 if (err == 0) {
1528 mPowerState |= SCREEN_ON_BIT;
1529 sendNotificationLocked(true, -1);
1530 }
1531 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001532 // cancel light sensor task
1533 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 mScreenOffTime = SystemClock.elapsedRealtime();
1535 long identity = Binder.clearCallingIdentity();
1536 try {
1537 mBatteryStats.noteScreenOff();
1538 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001539 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 } finally {
1541 Binder.restoreCallingIdentity(identity);
1542 }
1543 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001544 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001546 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 err = 0;
1549 mLastTouchDown = 0;
1550 }
1551 }
1552 }
1553 }
1554 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001555
Mike Lockwood435eb642009-12-03 08:40:18 -05001556 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001558 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001560 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001562 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001564 mScreenOffReason = reason;
1565 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 }
1567 return err;
1568 }
1569
1570 private boolean batteryIsLow() {
1571 return (!mIsPowered &&
1572 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1573 }
1574
The Android Open Source Project10592532009-03-18 17:39:46 -07001575 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001576 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001577 newState = applyButtonState(newState);
1578 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001579 final int realDifference = (newState ^ oldState);
1580 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001582 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 int offMask = 0;
1586 int dimMask = 0;
1587 int onMask = 0;
1588
1589 int preferredBrightness = getPreferredBrightness();
1590 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1593 if (ANIMATE_KEYBOARD_LIGHTS) {
1594 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1595 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001596 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001597 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001599 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001600 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1601 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 }
1603 startAnimation = true;
1604 } else {
1605 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001606 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001608 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
1610 }
1611 }
1612
1613 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1614 if (ANIMATE_BUTTON_LIGHTS) {
1615 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1616 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001617 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001618 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001620 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001621 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1622 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 }
1624 startAnimation = true;
1625 } else {
1626 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001627 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001629 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 }
1631 }
1632 }
1633
1634 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1635 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001636 int nominalCurrentValue = -1;
1637 // If there was an actual difference in the light state, then
1638 // figure out the "ideal" current value based on the previous
1639 // state. Otherwise, this is a change due to the brightness
1640 // override, so we want to animate from whatever the current
1641 // value is.
1642 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1643 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1644 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1645 nominalCurrentValue = preferredBrightness;
1646 break;
1647 case SCREEN_ON_BIT:
1648 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1649 break;
1650 case 0:
1651 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1652 break;
1653 case SCREEN_BRIGHT_BIT:
1654 default:
1655 // not possible
1656 nominalCurrentValue = (int)mScreenBrightness.curValue;
1657 break;
1658 }
Joe Onorato128e7292009-03-24 18:41:31 -07001659 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001660 int brightness = preferredBrightness;
1661 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1663 // dim or turn off backlight, depending on if the screen is on
1664 // the scale is because the brightness ramp isn't linear and this biases
1665 // it so the later parts take longer.
1666 final float scale = 1.5f;
1667 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1668 if (ratio > 1.0f) ratio = 1.0f;
1669 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1671 // was bright
1672 steps = ANIM_STEPS;
1673 } else {
1674 // was dim
1675 steps = (int)(ANIM_STEPS*ratio*scale);
1676 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001677 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 if ((oldState & SCREEN_ON_BIT) != 0) {
1680 // was bright
1681 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1682 } else {
1683 // was dim
1684 steps = (int)(ANIM_STEPS*ratio);
1685 }
1686 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1687 // If the "stay on while plugged in" option is
1688 // turned on, then the screen will often not
1689 // automatically turn off while plugged in. To
1690 // still have a sense of when it is inactive, we
1691 // will then count going dim as turning off.
1692 mScreenOffTime = SystemClock.elapsedRealtime();
1693 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001694 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001697 long identity = Binder.clearCallingIdentity();
1698 try {
1699 mBatteryStats.noteScreenBrightness(brightness);
1700 } catch (RemoteException e) {
1701 // Nothing interesting to do.
1702 } finally {
1703 Binder.restoreCallingIdentity(identity);
1704 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001705 if (mScreenBrightness.setTargetLocked(brightness,
1706 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1707 startAnimation = true;
1708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 } else {
1710 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1711 // dim or turn off backlight, depending on if the screen is on
1712 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001713 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001715 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 }
1717 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001718 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 }
1720 }
1721 }
1722
1723 if (startAnimation) {
1724 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001725 Slog.i(TAG, "Scheduling light animator!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 }
1727 mHandler.removeCallbacks(mLightAnimator);
1728 mHandler.post(mLightAnimator);
1729 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 if (offMask != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001732 //Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001733 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 }
1735 if (dimMask != 0) {
1736 int brightness = Power.BRIGHTNESS_DIM;
1737 if ((newState & BATTERY_LOW_BIT) != 0 &&
1738 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1739 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1740 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001741 //Slog.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001742 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 }
1744 if (onMask != 0) {
1745 int brightness = getPreferredBrightness();
1746 if ((newState & BATTERY_LOW_BIT) != 0 &&
1747 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1748 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1749 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001750 //Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001751 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754
The Android Open Source Project10592532009-03-18 17:39:46 -07001755 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001756 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001757 ? LightsService.BRIGHTNESS_MODE_SENSOR
1758 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001759 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001760 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001761 }
1762 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001763 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001764 }
1765 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001766 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 }
1769
1770 class BrightnessState {
1771 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 boolean initialized;
1774 int targetValue;
1775 float curValue;
1776 float delta;
1777 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 BrightnessState(int m) {
1780 mask = m;
1781 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 public void dump(PrintWriter pw, String prefix) {
1784 pw.println(prefix + "animating=" + animating
1785 + " targetValue=" + targetValue
1786 + " curValue=" + curValue
1787 + " delta=" + delta);
1788 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001789
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001790 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001791 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 if (!initialized) {
1793 initialized = true;
1794 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001795 } else if (targetValue == target) {
1796 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 }
1798 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001799 delta = (targetValue -
1800 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1801 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001803 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato8a9b2202010-02-26 18:56:32 -08001804 Slog.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001805 + " target=" + targetValue + " delta=" + delta
1806 + " nominalCurrentValue=" + nominalCurrentValue
1807 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 }
1809 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001810 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 boolean stepLocked() {
1814 if (!animating) return false;
1815 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001816 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 + " target=" + targetValue + " delta=" + delta);
1818 }
1819 curValue += delta;
1820 int curIntValue = (int)curValue;
1821 boolean more = true;
1822 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001823 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 more = false;
1825 } else if (delta > 0) {
1826 if (curIntValue >= targetValue) {
1827 curValue = curIntValue = targetValue;
1828 more = false;
1829 }
1830 } else {
1831 if (curIntValue <= targetValue) {
1832 curValue = curIntValue = targetValue;
1833 more = false;
1834 }
1835 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001836 //Slog.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001837 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 animating = more;
1839 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001840 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001841 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
1843 }
1844 return more;
1845 }
1846 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 private class LightAnimator implements Runnable {
1849 public void run() {
1850 synchronized (mLocks) {
1851 long now = SystemClock.uptimeMillis();
1852 boolean more = mScreenBrightness.stepLocked();
1853 if (mKeyboardBrightness.stepLocked()) {
1854 more = true;
1855 }
1856 if (mButtonBrightness.stepLocked()) {
1857 more = true;
1858 }
1859 if (more) {
1860 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1861 }
1862 }
1863 }
1864 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 private int getPreferredBrightness() {
1867 try {
1868 if (mScreenBrightnessOverride >= 0) {
1869 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001870 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001871 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001872 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 }
1874 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1875 SCREEN_BRIGHTNESS);
1876 // Don't let applications turn the screen all the way off
1877 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1878 } catch (SettingNotFoundException snfe) {
1879 return Power.BRIGHTNESS_ON;
1880 }
1881 }
1882
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001883 private int applyButtonState(int state) {
1884 int brightness = -1;
1885 if (mButtonBrightnessOverride >= 0) {
1886 brightness = mButtonBrightnessOverride;
1887 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
1888 brightness = mLightSensorButtonBrightness;
1889 }
1890 if (brightness > 0) {
1891 return state | BUTTON_BRIGHT_BIT;
1892 } else if (brightness == 0) {
1893 return state & ~BUTTON_BRIGHT_BIT;
1894 } else {
1895 return state;
1896 }
1897 }
1898
1899 private int applyKeyboardState(int state) {
1900 int brightness = -1;
1901 if (!mKeyboardVisible) {
1902 brightness = 0;
1903 } else if (mButtonBrightnessOverride >= 0) {
1904 brightness = mButtonBrightnessOverride;
1905 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
1906 brightness = mLightSensorKeyboardBrightness;
1907 }
1908 if (brightness > 0) {
1909 return state | KEYBOARD_BRIGHT_BIT;
1910 } else if (brightness == 0) {
1911 return state & ~KEYBOARD_BRIGHT_BIT;
1912 } else {
1913 return state;
1914 }
1915 }
1916
Charles Mendis322591c2009-10-29 11:06:59 -07001917 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 synchronized (mLocks) {
1919 return (mPowerState & SCREEN_ON_BIT) != 0;
1920 }
1921 }
1922
Charles Mendis322591c2009-10-29 11:06:59 -07001923 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 synchronized (mLocks) {
1925 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1926 }
1927 }
1928
Mike Lockwood497087e32009-11-08 18:33:03 -05001929 private boolean isScreenTurningOffLocked() {
1930 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1931 }
1932
Mike Lockwood200b30b2009-09-20 00:23:59 -04001933 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05001934 if (isScreenTurningOffLocked()) {
1935 // cancel animation so userActivity will succeed
1936 mScreenBrightness.animating = false;
1937 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04001938 boolean savedActivityAllowed = mUserActivityAllowed;
1939 mUserActivityAllowed = true;
1940 userActivity(SystemClock.uptimeMillis(), false);
1941 mUserActivityAllowed = savedActivityAllowed;
1942 }
1943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1945 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1946 userActivity(time, noChangeLights, OTHER_EVENT, force);
1947 }
1948
1949 public void userActivity(long time, boolean noChangeLights) {
1950 userActivity(time, noChangeLights, OTHER_EVENT, false);
1951 }
1952
1953 public void userActivity(long time, boolean noChangeLights, int eventType) {
1954 userActivity(time, noChangeLights, eventType, false);
1955 }
1956
1957 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1958 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1959
1960 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001961 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001963 Slog.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 }
1965 return;
1966 }
1967
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001968 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1969 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1970 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1971 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001972 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001973 }
1974 return;
1975 }
1976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 if (false) {
1978 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001979 Slog.d(TAG, "userActivity !!!");//, new RuntimeException());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001981 Slog.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 }
1983 }
1984
1985 synchronized (mLocks) {
1986 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001987 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 + " mUserActivityAllowed=" + mUserActivityAllowed
1989 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001990 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1991 + " mProximitySensorActive=" + mProximitySensorActive
1992 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 }
Mike Lockwood05067122009-10-27 23:07:25 -04001994 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05001995 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001996 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04001997 return;
1998 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05001999 // Disable proximity sensor if if user presses power key while we are in the
2000 // "waiting for proximity sensor to go negative" state.
2001 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2002 mProximitySensorActive = false;
2003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 if (mLastEventTime <= time || force) {
2005 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002006 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002007 // Only turn on button backlights if a button was pressed
2008 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002009 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2011 } else {
2012 // don't clear button/keyboard backlights when the screen is touched.
2013 mUserState |= SCREEN_BRIGHT;
2014 }
2015
Dianne Hackborn617f8772009-03-31 15:04:46 -07002016 int uid = Binder.getCallingUid();
2017 long ident = Binder.clearCallingIdentity();
2018 try {
2019 mBatteryStats.noteUserActivity(uid, eventType);
2020 } catch (RemoteException e) {
2021 // Ignore
2022 } finally {
2023 Binder.restoreCallingIdentity(ident);
2024 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002025
Michael Chane96440f2009-05-06 10:27:36 -07002026 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002027 setPowerState(mUserState | mWakeLockState, noChangeLights,
2028 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 setTimeoutLocked(time, SCREEN_BRIGHT);
2030 }
2031 }
2032 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002033
2034 if (mPolicy != null) {
2035 mPolicy.userActivity();
2036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 }
2038
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002039 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2040 try {
2041 int i;
2042 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2043 if (sensorValue < mAutoBrightnessLevels[i]) {
2044 break;
2045 }
2046 }
2047 return values[i];
2048 } catch (Exception e) {
2049 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002050 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002051 return 255;
2052 }
2053 }
2054
Mike Lockwood20f87d72009-11-05 16:08:51 -05002055 private Runnable mProximityTask = new Runnable() {
2056 public void run() {
2057 synchronized (mLocks) {
2058 if (mProximityPendingValue != -1) {
2059 proximityChangedLocked(mProximityPendingValue == 1);
2060 mProximityPendingValue = -1;
2061 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002062 if (mProximityPartialLock.isHeld()) {
2063 mProximityPartialLock.release();
2064 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002065 }
2066 }
2067 };
2068
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002069 private Runnable mAutoBrightnessTask = new Runnable() {
2070 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002071 synchronized (mLocks) {
2072 int value = (int)mLightSensorPendingValue;
2073 if (value >= 0) {
2074 mLightSensorPendingValue = -1;
2075 lightSensorChangedLocked(value);
2076 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002077 }
2078 }
2079 };
2080
Mike Lockwoodb2865412010-02-02 22:40:33 -05002081 private void dockStateChanged(int state) {
2082 synchronized (mLocks) {
2083 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2084 if (mIsDocked) {
2085 mHighestLightSensorValue = -1;
2086 }
2087 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2088 // force lights recalculation
2089 int value = (int)mLightSensorValue;
2090 mLightSensorValue = -1;
2091 lightSensorChangedLocked(value);
2092 }
2093 }
2094 }
2095
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002096 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002097 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002098 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002099 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002100
Mike Lockwoodb2865412010-02-02 22:40:33 -05002101 // do not allow light sensor value to decrease
2102 if (mHighestLightSensorValue < value) {
2103 mHighestLightSensorValue = value;
2104 }
2105
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002106 if (mLightSensorValue != value) {
2107 mLightSensorValue = value;
2108 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002109 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2110 // we only do this if we are undocked, since lighting should be stable when
2111 // stationary in a dock.
2112 int lcdValue = getAutoBrightnessValue(
2113 (mIsDocked ? value : mHighestLightSensorValue),
2114 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002115 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002116 int keyboardValue;
2117 if (mKeyboardVisible) {
2118 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2119 } else {
2120 keyboardValue = 0;
2121 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002122 mLightSensorScreenBrightness = lcdValue;
2123 mLightSensorButtonBrightness = buttonValue;
2124 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002125
2126 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002127 Slog.d(TAG, "lcdValue " + lcdValue);
2128 Slog.d(TAG, "buttonValue " + buttonValue);
2129 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002130 }
2131
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002132 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002133 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002134 if (ANIMATE_SCREEN_LIGHTS) {
2135 if (mScreenBrightness.setTargetLocked(lcdValue,
2136 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2137 (int)mScreenBrightness.curValue)) {
2138 startAnimation = true;
2139 }
2140 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002141 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002142 ? LightsService.BRIGHTNESS_MODE_SENSOR
2143 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002144 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002145 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002146 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002147 if (mButtonBrightnessOverride < 0) {
2148 if (ANIMATE_BUTTON_LIGHTS) {
2149 if (mButtonBrightness.setTargetLocked(buttonValue,
2150 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2151 (int)mButtonBrightness.curValue)) {
2152 startAnimation = true;
2153 }
2154 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002155 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002156 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002157 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002158 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2159 if (ANIMATE_KEYBOARD_LIGHTS) {
2160 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2161 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2162 (int)mKeyboardBrightness.curValue)) {
2163 startAnimation = true;
2164 }
2165 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002166 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002167 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002168 }
2169 if (startAnimation) {
2170 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002171 Slog.i(TAG, "lightSensorChangedLocked scheduling light animator");
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002172 }
2173 mHandler.removeCallbacks(mLightAnimator);
2174 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002175 }
2176 }
2177 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002178 }
2179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 /**
2181 * The user requested that we go to sleep (probably with the power button).
2182 * This overrides all wake locks that are held.
2183 */
2184 public void goToSleep(long time)
2185 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002186 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2187 }
2188
2189 /**
2190 * The user requested that we go to sleep (probably with the power button).
2191 * This overrides all wake locks that are held.
2192 */
2193 public void goToSleepWithReason(long time, int reason)
2194 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002195 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2196 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002197 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 }
2199 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002202 * Reboot the device immediately, passing 'reason' (may be null)
2203 * to the underlying __reboot system call. Should not return.
2204 */
2205 public void reboot(String reason)
2206 {
2207 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002208
San Mehat1e512792010-01-07 10:40:29 -08002209 /*
2210 * Manually shutdown the MountService to ensure media is
2211 * put into a safe state.
2212 */
2213 IMountService mSvc = IMountService.Stub.asInterface(
2214 ServiceManager.getService("mount"));
2215
2216 if (mSvc != null) {
2217 try {
2218 mSvc.shutdown();
2219 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002220 Slog.e(TAG, "MountService shutdown failed", e);
San Mehat1e512792010-01-07 10:40:29 -08002221 }
2222 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002223 Slog.w(TAG, "MountService unavailable for shutdown");
San Mehat1e512792010-01-07 10:40:29 -08002224 }
San Mehat14e69af2010-01-06 14:58:18 -08002225
Doug Zongker50a21f42009-11-19 12:49:53 -08002226 try {
2227 Power.reboot(reason);
2228 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002229 Slog.e(TAG, "reboot failed", e);
Doug Zongker50a21f42009-11-19 12:49:53 -08002230 }
2231 }
2232
Dan Egnor60d87622009-12-16 16:32:58 -08002233 /**
2234 * Crash the runtime (causing a complete restart of the Android framework).
2235 * Requires REBOOT permission. Mostly for testing. Should not return.
2236 */
2237 public void crash(final String message)
2238 {
2239 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2240 Thread t = new Thread("PowerManagerService.crash()") {
2241 public void run() { throw new RuntimeException(message); }
2242 };
2243 try {
2244 t.start();
2245 t.join();
2246 } catch (InterruptedException e) {
2247 Log.wtf(TAG, e);
2248 }
2249 }
2250
Mike Lockwood435eb642009-12-03 08:40:18 -05002251 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252
2253 if (mLastEventTime <= time) {
2254 mLastEventTime = time;
2255 // cancel all of the wake locks
2256 mWakeLockState = SCREEN_OFF;
2257 int N = mLocks.size();
2258 int numCleared = 0;
2259 for (int i=0; i<N; i++) {
2260 WakeLock wl = mLocks.get(i);
2261 if (isScreenLock(wl.flags)) {
2262 mLocks.get(i).activated = false;
2263 numCleared++;
2264 }
2265 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002266 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002267 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002269 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270 cancelTimerLocked();
2271 }
2272 }
2273
2274 public long timeSinceScreenOn() {
2275 synchronized (mLocks) {
2276 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2277 return 0;
2278 }
2279 return SystemClock.elapsedRealtime() - mScreenOffTime;
2280 }
2281 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002284 synchronized (mLocks) {
2285 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002286 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002287 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002288 if (mKeyboardVisible != visible) {
2289 mKeyboardVisible = visible;
2290 // don't signal user activity if the screen is off; other code
2291 // will take care of turning on due to a true change to the lid
2292 // switch and synchronized with the lock screen.
2293 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002294 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002295 // force recompute of backlight values
2296 if (mLightSensorValue >= 0) {
2297 int value = (int)mLightSensorValue;
2298 mLightSensorValue = -1;
2299 lightSensorChangedLocked(value);
2300 }
2301 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002302 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2303 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002304 }
2305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 }
2307
2308 /**
2309 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002310 * When disabling user activity we also reset user power state so the keyguard can reset its
2311 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 */
2313 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002314 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002315 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 synchronized (mLocks) {
2318 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002319 if (!enabled) {
2320 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2321 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 }
2324 }
2325
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002326 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002327 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002328 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002329 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002330 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002331 // force recompute of backlight values
2332 if (mLightSensorValue >= 0) {
2333 int value = (int)mLightSensorValue;
2334 mLightSensorValue = -1;
2335 lightSensorChangedLocked(value);
2336 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002337 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002338 }
2339 }
2340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 /** Sets the screen off timeouts:
2342 * mKeylightDelay
2343 * mDimDelay
2344 * mScreenOffDelay
2345 * */
2346 private void setScreenOffTimeoutsLocked() {
2347 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002348 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 mDimDelay = -1;
2350 mScreenOffDelay = 0;
2351 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2352 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2353 mDimDelay = -1;
2354 mScreenOffDelay = 0;
2355 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002356 int totalDelay = mScreenOffTimeoutSetting;
2357 if (totalDelay > mMaximumScreenOffTimeout) {
2358 totalDelay = mMaximumScreenOffTimeout;
2359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2361 if (totalDelay < 0) {
2362 mScreenOffDelay = Integer.MAX_VALUE;
2363 } else if (mKeylightDelay < totalDelay) {
2364 // subtract the time that the keylight delay. This will give us the
2365 // remainder of the time that we need to sleep to get the accurate
2366 // screen off timeout.
2367 mScreenOffDelay = totalDelay - mKeylightDelay;
2368 } else {
2369 mScreenOffDelay = 0;
2370 }
2371 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2372 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2373 mScreenOffDelay = LONG_DIM_TIME;
2374 } else {
2375 mDimDelay = -1;
2376 }
2377 }
2378 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002379 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2381 + " mDimScreen=" + mDimScreen);
2382 }
2383 }
2384
2385 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002386 * Refreshes cached secure settings. Called once on startup, and
2387 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 */
Doug Zongker43866e02010-01-07 12:09:54 -08002389 private void updateSettingsValues() {
2390 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002392 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002394 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 }
2396
2397 private class LockList extends ArrayList<WakeLock>
2398 {
2399 void addLock(WakeLock wl)
2400 {
2401 int index = getIndex(wl.binder);
2402 if (index < 0) {
2403 this.add(wl);
2404 }
2405 }
2406
2407 WakeLock removeLock(IBinder binder)
2408 {
2409 int index = getIndex(binder);
2410 if (index >= 0) {
2411 return this.remove(index);
2412 } else {
2413 return null;
2414 }
2415 }
2416
2417 int getIndex(IBinder binder)
2418 {
2419 int N = this.size();
2420 for (int i=0; i<N; i++) {
2421 if (this.get(i).binder == binder) {
2422 return i;
2423 }
2424 }
2425 return -1;
2426 }
2427
2428 int gatherState()
2429 {
2430 int result = 0;
2431 int N = this.size();
2432 for (int i=0; i<N; i++) {
2433 WakeLock wl = this.get(i);
2434 if (wl.activated) {
2435 if (isScreenLock(wl.flags)) {
2436 result |= wl.minState;
2437 }
2438 }
2439 }
2440 return result;
2441 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002442
Michael Chane96440f2009-05-06 10:27:36 -07002443 int reactivateScreenLocksLocked()
2444 {
2445 int result = 0;
2446 int N = this.size();
2447 for (int i=0; i<N; i++) {
2448 WakeLock wl = this.get(i);
2449 if (isScreenLock(wl.flags)) {
2450 wl.activated = true;
2451 result |= wl.minState;
2452 }
2453 }
2454 return result;
2455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 }
2457
2458 void setPolicy(WindowManagerPolicy p) {
2459 synchronized (mLocks) {
2460 mPolicy = p;
2461 mLocks.notifyAll();
2462 }
2463 }
2464
2465 WindowManagerPolicy getPolicyLocked() {
2466 while (mPolicy == null || !mDoneBooting) {
2467 try {
2468 mLocks.wait();
2469 } catch (InterruptedException e) {
2470 // Ignore
2471 }
2472 }
2473 return mPolicy;
2474 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002477 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2478 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2479 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002480 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002481 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002482 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002483 }
2484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002486 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002488 long identity = Binder.clearCallingIdentity();
2489 try {
2490 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2491 mBatteryStats.noteScreenOn();
2492 } catch (RemoteException e) {
2493 // Nothing interesting to do.
2494 } finally {
2495 Binder.restoreCallingIdentity(identity);
2496 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002497 }
2498 }
2499
2500 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002501 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002502 synchronized (mLocks) {
2503 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2505 updateWakeLockLocked();
2506 mLocks.notifyAll();
2507 }
2508 }
2509
2510 public void monitor() {
2511 synchronized (mLocks) { }
2512 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002513
2514 public int getSupportedWakeLockFlags() {
2515 int result = PowerManager.PARTIAL_WAKE_LOCK
2516 | PowerManager.FULL_WAKE_LOCK
2517 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2518
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002519 if (mProximitySensor != null) {
2520 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2521 }
2522
2523 return result;
2524 }
2525
Mike Lockwood237a2992009-09-15 14:42:16 -04002526 public void setBacklightBrightness(int brightness) {
2527 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2528 // Don't let applications turn the screen all the way off
2529 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002530 mLcdLight.setBrightness(brightness);
2531 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2532 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002533 long identity = Binder.clearCallingIdentity();
2534 try {
2535 mBatteryStats.noteScreenBrightness(brightness);
2536 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002537 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
Mike Lockwood237a2992009-09-15 14:42:16 -04002538 } finally {
2539 Binder.restoreCallingIdentity(identity);
2540 }
2541
2542 // update our animation state
2543 if (ANIMATE_SCREEN_LIGHTS) {
2544 mScreenBrightness.curValue = brightness;
2545 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002546 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002547 }
2548 if (ANIMATE_KEYBOARD_LIGHTS) {
2549 mKeyboardBrightness.curValue = brightness;
2550 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002551 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002552 }
2553 if (ANIMATE_BUTTON_LIGHTS) {
2554 mButtonBrightness.curValue = brightness;
2555 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002556 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002557 }
2558 }
2559
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002560 public void setAttentionLight(boolean on, int color) {
2561 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002562 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002563 }
2564
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002565 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002566 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002567 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002568 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002569 if (!mProximitySensorEnabled) {
2570 // clear calling identity so sensor manager battery stats are accurate
2571 long identity = Binder.clearCallingIdentity();
2572 try {
2573 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2574 SensorManager.SENSOR_DELAY_NORMAL);
2575 mProximitySensorEnabled = true;
2576 } finally {
2577 Binder.restoreCallingIdentity(identity);
2578 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002579 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002580 }
2581
2582 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002583 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002584 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002585 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002586 if (mProximitySensorEnabled) {
2587 // clear calling identity so sensor manager battery stats are accurate
2588 long identity = Binder.clearCallingIdentity();
2589 try {
2590 mSensorManager.unregisterListener(mProximityListener);
2591 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002592 if (mProximityPartialLock.isHeld()) {
2593 mProximityPartialLock.release();
2594 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002595 mProximitySensorEnabled = false;
2596 } finally {
2597 Binder.restoreCallingIdentity(identity);
2598 }
2599 if (mProximitySensorActive) {
2600 mProximitySensorActive = false;
2601 forceUserActivityLocked();
2602 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002603 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002604 }
2605
Mike Lockwood20f87d72009-11-05 16:08:51 -05002606 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002607 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002608 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002609 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002610 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002611 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002612 return;
2613 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002614 if (active) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002615 goToSleepLocked(SystemClock.uptimeMillis(),
2616 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002617 mProximitySensorActive = true;
2618 } else {
2619 // proximity sensor negative events trigger as user activity.
2620 // temporarily set mUserActivityAllowed to true so this will work
2621 // even when the keyguard is on.
2622 mProximitySensorActive = false;
2623 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002624
2625 if (mProximityWakeLockCount == 0) {
2626 // disable sensor if we have no listeners left after proximity negative
2627 disableProximityLockLocked();
2628 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002629 }
2630 }
2631
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002632 private void enableLightSensor(boolean enable) {
2633 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002634 Slog.d(TAG, "enableLightSensor " + enable);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002635 }
2636 if (mSensorManager != null && mLightSensorEnabled != enable) {
2637 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002638 // clear calling identity so sensor manager battery stats are accurate
2639 long identity = Binder.clearCallingIdentity();
2640 try {
2641 if (enable) {
2642 mSensorManager.registerListener(mLightListener, mLightSensor,
2643 SensorManager.SENSOR_DELAY_NORMAL);
2644 } else {
2645 mSensorManager.unregisterListener(mLightListener);
2646 mHandler.removeCallbacks(mAutoBrightnessTask);
2647 }
2648 } finally {
2649 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002650 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002651 }
2652 }
2653
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002654 SensorEventListener mProximityListener = new SensorEventListener() {
2655 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002656 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002657 synchronized (mLocks) {
2658 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002659 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2660 mLastProximityEventTime = milliseconds;
2661 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002662 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002663
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002664 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002665 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2666 distance < mProximitySensor.getMaximumRange());
2667
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002668 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002669 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002670 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002671 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2672 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2673 mProximityPendingValue = (active ? 1 : 0);
2674 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002675 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002676 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002677 // process the value immediately
2678 mProximityPendingValue = -1;
2679 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002680 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002681
2682 // update mProximityPartialLock state
2683 boolean held = mProximityPartialLock.isHeld();
2684 if (!held && proximityTaskQueued) {
2685 // hold wakelock until mProximityTask runs
2686 mProximityPartialLock.acquire();
2687 } else if (held && !proximityTaskQueued) {
2688 mProximityPartialLock.release();
2689 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002690 }
2691 }
2692
2693 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2694 // ignore
2695 }
2696 };
2697
2698 SensorEventListener mLightListener = new SensorEventListener() {
2699 public void onSensorChanged(SensorEvent event) {
2700 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002701 // ignore light sensor while screen is turning off
2702 if (isScreenTurningOffLocked()) {
2703 return;
2704 }
2705
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002706 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002707 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002708 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002709 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002710 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002711 mHandler.removeCallbacks(mAutoBrightnessTask);
2712 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002713 if (mLightSensorValue == -1 ||
2714 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2715 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002716 lightSensorChangedLocked(value);
2717 } else {
2718 // delay processing to debounce the sensor
2719 mLightSensorPendingValue = value;
2720 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2721 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002722 } else {
2723 mLightSensorPendingValue = -1;
2724 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002725 }
2726 }
2727
2728 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2729 // ignore
2730 }
2731 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732}