blob: 2fb481cbc1335ed6f4a0ddbb4e075929b3466e2d [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import com.android.internal.app.IBatteryStats;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -080020import com.android.internal.app.ShutdownThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import com.android.server.am.BatteryStatsService;
22
23import android.app.ActivityManagerNative;
24import android.app.IActivityManager;
25import android.content.BroadcastReceiver;
26import android.content.ContentQueryMap;
27import android.content.ContentResolver;
28import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
31import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070032import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080033import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070035import android.hardware.Sensor;
36import android.hardware.SensorEvent;
37import android.hardware.SensorEventListener;
38import android.hardware.SensorManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.os.BatteryStats;
40import android.os.Binder;
Doug Zongker43866e02010-01-07 12:09:54 -080041import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.Handler;
43import android.os.HandlerThread;
44import android.os.IBinder;
45import android.os.IPowerManager;
46import android.os.LocalPowerManager;
47import android.os.Power;
48import android.os.PowerManager;
49import android.os.Process;
50import android.os.RemoteException;
San Mehat14e69af2010-01-06 14:58:18 -080051import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.SystemClock;
53import android.provider.Settings.SettingNotFoundException;
54import android.provider.Settings;
55import android.util.EventLog;
56import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080057import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.view.WindowManagerPolicy;
59import static android.provider.Settings.System.DIM_SCREEN;
60import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050061import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070062import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
64import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
65
66import java.io.FileDescriptor;
Doug Zongker50a21f42009-11-19 12:49:53 -080067import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import java.io.PrintWriter;
69import java.util.ArrayList;
70import java.util.HashMap;
71import java.util.Observable;
72import java.util.Observer;
73
Mike Lockwoodbc706a02009-07-27 13:50:57 -070074class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040075 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
77 private static final String TAG = "PowerManagerService";
78 static final String PARTIAL_NAME = "PowerManagerService";
79
80 private static final boolean LOG_PARTIAL_WL = false;
81
82 // Indicates whether touch-down cycles should be logged as part of the
83 // LOG_POWER_SCREEN_STATE log events
84 private static final boolean LOG_TOUCH_DOWNS = true;
85
86 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
87 | PowerManager.SCREEN_DIM_WAKE_LOCK
88 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070089 | PowerManager.FULL_WAKE_LOCK
90 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091
92 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -080093 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
95 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
96 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
97 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
98
Mike Lockwoodd7786b42009-10-15 17:09:16 -070099 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -0500100 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700101
Mike Lockwood20f87d72009-11-05 16:08:51 -0500102 // For debouncing the proximity sensor.
103 private static final int PROXIMITY_SENSOR_DELAY = 1000;
104
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400105 // trigger proximity if distance is less than 5 cm
106 private static final float PROXIMITY_THRESHOLD = 5.0f;
107
Doug Zongker43866e02010-01-07 12:09:54 -0800108 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
110
111 // flags for setPowerState
112 private static final int SCREEN_ON_BIT = 0x00000001;
113 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
114 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
115 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
116 private static final int BATTERY_LOW_BIT = 0x00000010;
117
118 // values for setPowerState
119
120 // SCREEN_OFF == everything off
121 private static final int SCREEN_OFF = 0x00000000;
122
123 // SCREEN_DIM == screen on, screen backlight dim
124 private static final int SCREEN_DIM = SCREEN_ON_BIT;
125
126 // SCREEN_BRIGHT == screen on, screen backlight bright
127 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
128
129 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
130 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
131
132 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
133 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
134
135 // used for noChangeLights in setPowerState()
136 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
137
138 static final boolean ANIMATE_SCREEN_LIGHTS = true;
139 static final boolean ANIMATE_BUTTON_LIGHTS = false;
140 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400143 // Slower animation for autobrightness changes
144 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
146 // These magic numbers are the initial state of the LEDs at boot. Ideally
147 // we should read them from the driver, but our current hardware returns 0
148 // for the initial value. Oops!
149 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
150 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
151 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 private final int MY_UID;
154
155 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500156 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500158 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
159 private final int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private int mPartialCount = 0;
161 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500162 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
163 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
164 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 private int mUserState;
166 private boolean mKeyboardVisible = false;
167 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500168 private int mProximityWakeLockCount = 0;
169 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700170 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500171 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
172 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800173 private int mScreenOffTimeoutSetting;
174 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 private int mKeylightDelay;
176 private int mDimDelay;
177 private int mScreenOffDelay;
178 private int mWakeLockState;
179 private long mLastEventTime = 0;
180 private long mScreenOffTime;
181 private volatile WindowManagerPolicy mPolicy;
182 private final LockList mLocks = new LockList();
183 private Intent mScreenOffIntent;
184 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500185 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500187 private LightsService.Light mLcdLight;
188 private LightsService.Light mButtonLight;
189 private LightsService.Light mKeyboardLight;
190 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 private UnsynchronizedWakeLock mBroadcastWakeLock;
192 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
193 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
194 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500195 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 private HandlerThread mHandlerThread;
197 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500198 private final TimeoutTask mTimeoutTask = new TimeoutTask();
199 private final LightAnimator mLightAnimator = new LightAnimator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700201 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700203 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700205 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700206 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 private boolean mIsPowered = false;
208 private IActivityManager mActivityService;
209 private IBatteryStats mBatteryStats;
210 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700211 private SensorManager mSensorManager;
212 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400213 private Sensor mLightSensor;
214 private boolean mLightSensorEnabled;
215 private float mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500216 private int mHighestLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700217 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500218 private int mLightSensorScreenBrightness = -1;
219 private int mLightSensorButtonBrightness = -1;
220 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500222 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 private long mNextTimeout;
224 private volatile int mPokey = 0;
225 private volatile boolean mPokeAwakeOnSet = false;
226 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500227 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500228 // mLastScreenOnTime is the time the screen was last turned on
229 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 private boolean mPreventScreenOn;
231 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500232 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400233 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700234 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700235 private int[] mAutoBrightnessLevels;
236 private int[] mLcdBacklightValues;
237 private int[] mButtonBacklightValues;
238 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500239 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240
241 // Used when logging number and duration of touch-down cycles
242 private long mTotalTouchDownTime;
243 private long mLastTouchDown;
244 private int mTouchCycles;
245
246 // could be either static or controllable at runtime
247 private static final boolean mSpew = false;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500248 private static final boolean mDebugProximitySensor = (true || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400249 private static final boolean mDebugLightSensor = (false || mSpew);
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700250
251 private native void nativeInit();
252 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253
254 /*
255 static PrintStream mLog;
256 static {
257 try {
258 mLog = new PrintStream("/data/power.log");
259 }
260 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800261 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 }
263 }
264 static class Log {
265 static void d(String tag, String s) {
266 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800267 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 }
269 static void i(String tag, String s) {
270 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800271 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 }
273 static void w(String tag, String s) {
274 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800275 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 }
277 static void e(String tag, String s) {
278 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800279 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 }
281 }
282 */
283
284 /**
285 * This class works around a deadlock between the lock in PowerManager.WakeLock
286 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
287 * mToken object so it can be accessed from any thread, but it calls into here
288 * with its lock held. This class is essentially a reimplementation of
289 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
290 * only call it with our own locks held.
291 */
292 private class UnsynchronizedWakeLock {
293 int mFlags;
294 String mTag;
295 IBinder mToken;
296 int mCount = 0;
297 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500298 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299
300 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
301 mFlags = flags;
302 mTag = tag;
303 mToken = new Binder();
304 mRefCounted = refCounted;
305 }
306
307 public void acquire() {
308 if (!mRefCounted || mCount++ == 0) {
309 long ident = Binder.clearCallingIdentity();
310 try {
311 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
312 MY_UID, mTag);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500313 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 } finally {
315 Binder.restoreCallingIdentity(ident);
316 }
317 }
318 }
319
320 public void release() {
321 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500322 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500323 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 }
325 if (mCount < 0) {
326 throw new RuntimeException("WakeLock under-locked " + mTag);
327 }
328 }
329
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500330 public boolean isHeld()
331 {
332 return mHeld;
333 }
334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 public String toString() {
336 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500337 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 }
339 }
340
341 private final class BatteryReceiver extends BroadcastReceiver {
342 @Override
343 public void onReceive(Context context, Intent intent) {
344 synchronized (mLocks) {
345 boolean wasPowered = mIsPowered;
346 mIsPowered = mBatteryService.isPowered();
347
348 if (mIsPowered != wasPowered) {
349 // update mStayOnWhilePluggedIn wake lock
350 updateWakeLockLocked();
351
352 // treat plugging and unplugging the devices as a user activity.
353 // users find it disconcerting when they unplug the device
354 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500355 // to avoid turning on the screen when unplugging, we only trigger
356 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 // temporarily set mUserActivityAllowed to true so this will work
358 // even when the keyguard is on.
359 synchronized (mLocks) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500360 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0) {
361 forceUserActivityLocked();
362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 }
364 }
365 }
366 }
367 }
368
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500369 private final class BootCompletedReceiver extends BroadcastReceiver {
370 @Override
371 public void onReceive(Context context, Intent intent) {
372 bootCompleted();
373 }
374 }
375
Mike Lockwoodb2865412010-02-02 22:40:33 -0500376 private final class DockReceiver extends BroadcastReceiver {
377 @Override
378 public void onReceive(Context context, Intent intent) {
379 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
380 Intent.EXTRA_DOCK_STATE_UNDOCKED);
381 dockStateChanged(state);
382 }
383 }
384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 /**
386 * Set the setting that determines whether the device stays on when plugged in.
387 * The argument is a bit string, with each bit specifying a power source that,
388 * when the device is connected to that source, causes the device to stay on.
389 * See {@link android.os.BatteryManager} for the list of power sources that
390 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
391 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
392 * @param val an {@code int} containing the bits that specify which power sources
393 * should cause the device to stay on.
394 */
395 public void setStayOnSetting(int val) {
396 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
397 Settings.System.putInt(mContext.getContentResolver(),
398 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
399 }
400
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800401 public void setMaximumScreenOffTimeount(int timeMs) {
402 mContext.enforceCallingOrSelfPermission(
403 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
404 synchronized (mLocks) {
405 mMaximumScreenOffTimeout = timeMs;
406 // recalculate everything
407 setScreenOffTimeoutsLocked();
408 }
409 }
410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 private class SettingsObserver implements Observer {
412 private int getInt(String name) {
413 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
414 }
415
416 public void update(Observable o, Object arg) {
417 synchronized (mLocks) {
418 // STAY_ON_WHILE_PLUGGED_IN
419 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
420 updateWakeLockLocked();
421
422 // SCREEN_OFF_TIMEOUT
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800423 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424
425 // DIM_SCREEN
426 //mDimScreen = getInt(DIM_SCREEN) != 0;
427
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700428 // SCREEN_BRIGHTNESS_MODE
429 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 // recalculate everything
432 setScreenOffTimeoutsLocked();
433 }
434 }
435 }
436
437 PowerManagerService()
438 {
439 // Hack to get our uid... should have a func for this.
440 long token = Binder.clearCallingIdentity();
441 MY_UID = Binder.getCallingUid();
442 Binder.restoreCallingIdentity(token);
443
444 // XXX remove this when the kernel doesn't timeout wake locks
445 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
446
447 // assume nothing is on yet
448 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 // Add ourself to the Watchdog monitors.
451 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 }
453
454 private ContentQueryMap mSettings;
455
Mike Lockwood3a322132009-11-24 00:30:52 -0500456 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700457 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500458 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 mContext = context;
460 mActivityService = activity;
461 mBatteryStats = BatteryStatsService.getService();
462 mBatteryService = battery;
463
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500464 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
465 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
466 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
467 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 mHandlerThread = new HandlerThread("PowerManagerService") {
470 @Override
471 protected void onLooperPrepared() {
472 super.onLooperPrepared();
473 initInThread();
474 }
475 };
476 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 synchronized (mHandlerThread) {
479 while (!mInitComplete) {
480 try {
481 mHandlerThread.wait();
482 } catch (InterruptedException e) {
483 // Ignore
484 }
485 }
486 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700487
488 nativeInit();
489 synchronized (mLocks) {
490 updateNativePowerStateLocked();
491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 void initInThread() {
495 mHandler = new Handler();
496
497 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700498 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
500 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
501 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
502 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
503 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
504 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500505 mProximityPartialLock = new UnsynchronizedWakeLock(
506 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507
508 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
509 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
510 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
511 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
512
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700513 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400514
515 // read settings for auto-brightness
516 mUseSoftwareAutoBrightness = resources.getBoolean(
517 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400518 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700519 mAutoBrightnessLevels = resources.getIntArray(
520 com.android.internal.R.array.config_autoBrightnessLevels);
521 mLcdBacklightValues = resources.getIntArray(
522 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
523 mButtonBacklightValues = resources.getIntArray(
524 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
525 mKeyboardBacklightValues = resources.getIntArray(
526 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500527 mLightSensorWarmupTime = resources.getInteger(
528 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700529 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700530
531 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
533 "(" + Settings.System.NAME + "=?) or ("
534 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700535 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700537 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
538 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 null);
540 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
541 SettingsObserver settingsObserver = new SettingsObserver();
542 mSettings.addObserver(settingsObserver);
543
544 // pretend that the settings changed so we will get their initial state
545 settingsObserver.update(mSettings, null);
546
547 // register for the battery changed notifications
548 IntentFilter filter = new IntentFilter();
549 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
550 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500551 filter = new IntentFilter();
552 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
553 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500554 filter = new IntentFilter();
555 filter.addAction(Intent.ACTION_DOCK_EVENT);
556 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557
Doug Zongker43866e02010-01-07 12:09:54 -0800558 // Listen for secure settings changes
559 mContext.getContentResolver().registerContentObserver(
560 Settings.Secure.CONTENT_URI, true,
561 new ContentObserver(new Handler()) {
562 public void onChange(boolean selfChange) {
563 updateSettingsValues();
564 }
565 });
566 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 synchronized (mHandlerThread) {
569 mInitComplete = true;
570 mHandlerThread.notifyAll();
571 }
572 }
573
574 private class WakeLock implements IBinder.DeathRecipient
575 {
576 WakeLock(int f, IBinder b, String t, int u) {
577 super();
578 flags = f;
579 binder = b;
580 tag = t;
581 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400582 pid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 if (u != MY_UID || (
584 !"KEEP_SCREEN_ON_FLAG".equals(tag)
585 && !"KeyInputQueue".equals(tag))) {
586 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
587 ? BatteryStats.WAKE_TYPE_PARTIAL
588 : BatteryStats.WAKE_TYPE_FULL;
589 } else {
590 monitorType = -1;
591 }
592 try {
593 b.linkToDeath(this, 0);
594 } catch (RemoteException e) {
595 binderDied();
596 }
597 }
598 public void binderDied() {
599 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500600 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 }
602 }
603 final int flags;
604 final IBinder binder;
605 final String tag;
606 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400607 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 final int monitorType;
609 boolean activated = true;
610 int minState;
611 }
612
613 private void updateWakeLockLocked() {
614 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
615 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
616 mStayOnWhilePluggedInScreenDimLock.acquire();
617 mStayOnWhilePluggedInPartialLock.acquire();
618 } else {
619 mStayOnWhilePluggedInScreenDimLock.release();
620 mStayOnWhilePluggedInPartialLock.release();
621 }
622 }
623
624 private boolean isScreenLock(int flags)
625 {
626 int n = flags & LOCK_MASK;
627 return n == PowerManager.FULL_WAKE_LOCK
628 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
629 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
630 }
631
632 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700634 if (uid != Process.myUid()) {
635 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 long ident = Binder.clearCallingIdentity();
638 try {
639 synchronized (mLocks) {
640 acquireWakeLockLocked(flags, lock, uid, tag);
641 }
642 } finally {
643 Binder.restoreCallingIdentity(ident);
644 }
645 }
646
647 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
648 int acquireUid = -1;
649 String acquireName = null;
650 int acquireType = -1;
651
652 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800653 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 }
655
656 int index = mLocks.getIndex(lock);
657 WakeLock wl;
658 boolean newlock;
659 if (index < 0) {
660 wl = new WakeLock(flags, lock, tag, uid);
661 switch (wl.flags & LOCK_MASK)
662 {
663 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500664 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400665 wl.minState = SCREEN_BRIGHT;
666 } else {
667 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 break;
670 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
671 wl.minState = SCREEN_BRIGHT;
672 break;
673 case PowerManager.SCREEN_DIM_WAKE_LOCK:
674 wl.minState = SCREEN_DIM;
675 break;
676 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700677 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 break;
679 default:
680 // just log and bail. we're in the server, so don't
681 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800682 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 + " flags=" + flags);
684 return;
685 }
686 mLocks.addLock(wl);
687 newlock = true;
688 } else {
689 wl = mLocks.get(index);
690 newlock = false;
691 }
692 if (isScreenLock(flags)) {
693 // if this causes a wakeup, we reactivate all of the locks and
694 // set it to whatever they want. otherwise, we modulate that
695 // by the current state so we never turn it more on than
696 // it already is.
697 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700698 int oldWakeLockState = mWakeLockState;
699 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800701 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700702 + " mWakeLockState=0x"
703 + Integer.toHexString(mWakeLockState)
704 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 } else {
707 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800708 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 + " mLocks.gatherState()=0x"
710 + Integer.toHexString(mLocks.gatherState())
711 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
712 }
713 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
714 }
715 setPowerState(mWakeLockState | mUserState);
716 }
717 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
718 if (newlock) {
719 mPartialCount++;
720 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800721 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 }
723 }
724 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700725 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500726 mProximityWakeLockCount++;
727 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700728 enableProximityLockLocked();
729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 }
731 if (newlock) {
732 acquireUid = wl.uid;
733 acquireName = wl.tag;
734 acquireType = wl.monitorType;
735 }
736
737 if (acquireType >= 0) {
738 try {
739 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
740 } catch (RemoteException e) {
741 // Ignore
742 }
743 }
744 }
745
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500746 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700747 int uid = Binder.getCallingUid();
748 if (uid != Process.myUid()) {
749 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751
752 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500753 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 }
755 }
756
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500757 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 int releaseUid;
759 String releaseName;
760 int releaseType;
761
762 WakeLock wl = mLocks.removeLock(lock);
763 if (wl == null) {
764 return;
765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800768 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
770 }
771
772 if (isScreenLock(wl.flags)) {
773 mWakeLockState = mLocks.gatherState();
774 // goes in the middle to reduce flicker
775 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
776 userActivity(SystemClock.uptimeMillis(), false);
777 }
778 setPowerState(mWakeLockState | mUserState);
779 }
780 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
781 mPartialCount--;
782 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800783 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 Power.releaseWakeLock(PARTIAL_NAME);
785 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700786 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500787 mProximityWakeLockCount--;
788 if (mProximityWakeLockCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500789 if (mProximitySensorActive &&
790 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500791 // wait for proximity sensor to go negative before disabling sensor
792 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800793 Slog.d(TAG, "waiting for proximity sensor to go negative");
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500794 }
795 } else {
796 disableProximityLockLocked();
797 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 }
800 // Unlink the lock from the binder.
801 wl.binder.unlinkToDeath(wl, 0);
802 releaseUid = wl.uid;
803 releaseName = wl.tag;
804 releaseType = wl.monitorType;
805
806 if (releaseType >= 0) {
807 long origId = Binder.clearCallingIdentity();
808 try {
809 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
810 } catch (RemoteException e) {
811 // Ignore
812 } finally {
813 Binder.restoreCallingIdentity(origId);
814 }
815 }
816 }
817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 private class PokeLock implements IBinder.DeathRecipient
819 {
820 PokeLock(int p, IBinder b, String t) {
821 super();
822 this.pokey = p;
823 this.binder = b;
824 this.tag = t;
825 try {
826 b.linkToDeath(this, 0);
827 } catch (RemoteException e) {
828 binderDied();
829 }
830 }
831 public void binderDied() {
832 setPokeLock(0, this.binder, this.tag);
833 }
834 int pokey;
835 IBinder binder;
836 String tag;
837 boolean awakeOnSet;
838 }
839
840 public void setPokeLock(int pokey, IBinder token, String tag) {
841 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
842 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800843 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 return;
845 }
846
847 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
848 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
849 + " and POKE_LOCK_MEDIUM_TIMEOUT");
850 }
851
852 synchronized (mLocks) {
853 if (pokey != 0) {
854 PokeLock p = mPokeLocks.get(token);
855 int oldPokey = 0;
856 if (p != null) {
857 oldPokey = p.pokey;
858 p.pokey = pokey;
859 } else {
860 p = new PokeLock(pokey, token, tag);
861 mPokeLocks.put(token, p);
862 }
863 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
864 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
865 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
866 p.awakeOnSet = true;
867 }
868 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700869 PokeLock rLock = mPokeLocks.remove(token);
870 if (rLock != null) {
871 token.unlinkToDeath(rLock, 0);
872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 }
874
875 int oldPokey = mPokey;
876 int cumulative = 0;
877 boolean oldAwakeOnSet = mPokeAwakeOnSet;
878 boolean awakeOnSet = false;
879 for (PokeLock p: mPokeLocks.values()) {
880 cumulative |= p.pokey;
881 if (p.awakeOnSet) {
882 awakeOnSet = true;
883 }
884 }
885 mPokey = cumulative;
886 mPokeAwakeOnSet = awakeOnSet;
887
888 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
889 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 if (oldCumulativeTimeout != newCumulativeTimeout) {
892 setScreenOffTimeoutsLocked();
893 // reset the countdown timer, but use the existing nextState so it doesn't
894 // change anything
895 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
896 }
897 }
898 }
899
900 private static String lockType(int type)
901 {
902 switch (type)
903 {
904 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700905 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700907 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700909 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700911 return "PARTIAL_WAKE_LOCK ";
912 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
913 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 default:
David Brown251faa62009-08-02 22:04:36 -0700915 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
917 }
918
919 private static String dumpPowerState(int state) {
920 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
921 ? "KEYBOARD_BRIGHT_BIT " : "")
922 + (((state & SCREEN_BRIGHT_BIT) != 0)
923 ? "SCREEN_BRIGHT_BIT " : "")
924 + (((state & SCREEN_ON_BIT) != 0)
925 ? "SCREEN_ON_BIT " : "")
926 + (((state & BATTERY_LOW_BIT) != 0)
927 ? "BATTERY_LOW_BIT " : "");
928 }
929
930 @Override
931 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
932 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
933 != PackageManager.PERMISSION_GRANTED) {
934 pw.println("Permission Denial: can't dump PowerManager from from pid="
935 + Binder.getCallingPid()
936 + ", uid=" + Binder.getCallingUid());
937 return;
938 }
939
940 long now = SystemClock.uptimeMillis();
941
Mike Lockwoodca44df82010-02-25 13:48:49 -0500942 synchronized (mLocks) {
943 pw.println("Power Manager State:");
944 pw.println(" mIsPowered=" + mIsPowered
945 + " mPowerState=" + mPowerState
946 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
947 + " ms");
948 pw.println(" mPartialCount=" + mPartialCount);
949 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
950 pw.println(" mUserState=" + dumpPowerState(mUserState));
951 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
952 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
953 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
954 + " " + ((mNextTimeout-now)/1000) + "s from now");
955 pw.println(" mDimScreen=" + mDimScreen
956 + " mStayOnConditions=" + mStayOnConditions);
957 pw.println(" mScreenOffReason=" + mScreenOffReason
958 + " mUserState=" + mUserState);
959 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
960 + ',' + mBroadcastQueue[2] + "}");
961 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
962 + ',' + mBroadcastWhy[2] + "}");
963 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
964 pw.println(" mKeyboardVisible=" + mKeyboardVisible
965 + " mUserActivityAllowed=" + mUserActivityAllowed);
966 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
967 + " mScreenOffDelay=" + mScreenOffDelay);
968 pw.println(" mPreventScreenOn=" + mPreventScreenOn
969 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
970 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
971 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
972 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
973 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
974 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
975 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
976 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
977 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
978 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
979 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
980 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
981 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
982 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
983 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
984 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
985 pw.println(" mLightSensorValue=" + mLightSensorValue
986 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
987 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
988 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
989 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
990 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
991 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
992 mScreenBrightness.dump(pw, " mScreenBrightness: ");
993 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
994 mButtonBrightness.dump(pw, " mButtonBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800995
Mike Lockwoodca44df82010-02-25 13:48:49 -0500996 int N = mLocks.size();
997 pw.println();
998 pw.println("mLocks.size=" + N + ":");
999 for (int i=0; i<N; i++) {
1000 WakeLock wl = mLocks.get(i);
1001 String type = lockType(wl.flags & LOCK_MASK);
1002 String acquireCausesWakeup = "";
1003 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1004 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1005 }
1006 String activated = "";
1007 if (wl.activated) {
1008 activated = " activated";
1009 }
1010 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001011 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1012 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001014
1015 pw.println();
1016 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1017 for (PokeLock p: mPokeLocks.values()) {
1018 pw.println(" poke lock '" + p.tag + "':"
1019 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
1020 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
1021 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
1022 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
1023 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1024 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1025 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1026 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001028
Mike Lockwoodca44df82010-02-25 13:48:49 -05001029 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 }
1032
Joe Onorato7999bff2010-07-24 11:50:05 -04001033 private void setTimeoutLocked(long now, int nextState) {
1034 setTimeoutLocked(now, -1, nextState);
1035 }
1036
1037 // If they gave a timeoutOverride it is the number of seconds
1038 // to screen-off. Figure out where in the countdown cycle we
1039 // should jump to.
1040 private void setTimeoutLocked(long now, long timeoutOverride, int nextState) {
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001041 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001042 synchronized (mLocks) {
1043 mHandler.removeCallbacks(mTimeoutTask);
1044 mTimeoutTask.nextState = nextState;
1045 long when = 0;
1046 if (timeoutOverride <= 0) {
1047 switch (nextState)
1048 {
1049 case SCREEN_BRIGHT:
1050 when = now + mKeylightDelay;
1051 break;
1052 case SCREEN_DIM:
1053 if (mDimDelay >= 0) {
1054 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001055 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001056 } else {
1057 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1058 }
1059 case SCREEN_OFF:
1060 synchronized (mLocks) {
1061 when = now + mScreenOffDelay;
1062 }
1063 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001064 default:
1065 when = now;
1066 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001068 } else {
1069 override: {
1070 if (timeoutOverride <= mScreenOffDelay) {
1071 when = now + timeoutOverride;
1072 nextState = SCREEN_OFF;
1073 break override;
1074 }
1075 timeoutOverride -= mScreenOffDelay;
1076
1077 if (mDimDelay >= 0) {
1078 if (timeoutOverride <= mDimDelay) {
1079 when = now + timeoutOverride;
1080 nextState = SCREEN_DIM;
1081 break override;
1082 }
1083 timeoutOverride -= mDimDelay;
1084 }
1085
1086 when = now + timeoutOverride;
1087 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001089 }
1090 if (mSpew) {
1091 Slog.d(TAG, "setTimeoutLocked now=" + now
1092 + " timeoutOverride=" + timeoutOverride
1093 + " nextState=" + nextState + " when=" + when);
1094 }
1095 mHandler.postAtTime(mTimeoutTask, when);
1096 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 }
1099 }
1100
1101 private void cancelTimerLocked()
1102 {
1103 mHandler.removeCallbacks(mTimeoutTask);
1104 mTimeoutTask.nextState = -1;
1105 }
1106
1107 private class TimeoutTask implements Runnable
1108 {
1109 int nextState; // access should be synchronized on mLocks
1110 public void run()
1111 {
1112 synchronized (mLocks) {
1113 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001114 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 }
1116
1117 if (nextState == -1) {
1118 return;
1119 }
1120
1121 mUserState = this.nextState;
1122 setPowerState(this.nextState | mWakeLockState);
1123
1124 long now = SystemClock.uptimeMillis();
1125
1126 switch (this.nextState)
1127 {
1128 case SCREEN_BRIGHT:
1129 if (mDimDelay >= 0) {
1130 setTimeoutLocked(now, SCREEN_DIM);
1131 break;
1132 }
1133 case SCREEN_DIM:
1134 setTimeoutLocked(now, SCREEN_OFF);
1135 break;
1136 }
1137 }
1138 }
1139 }
1140
1141 private void sendNotificationLocked(boolean on, int why)
1142 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001143 if (!on) {
1144 mStillNeedSleepNotification = false;
1145 }
1146
Joe Onorato128e7292009-03-24 18:41:31 -07001147 // Add to the queue.
1148 int index = 0;
1149 while (mBroadcastQueue[index] != -1) {
1150 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 }
Joe Onorato128e7292009-03-24 18:41:31 -07001152 mBroadcastQueue[index] = on ? 1 : 0;
1153 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154
Joe Onorato128e7292009-03-24 18:41:31 -07001155 // If we added it position 2, then there is a pair that can be stripped.
1156 // If we added it position 1 and we're turning the screen off, we can strip
1157 // the pair and do nothing, because the screen is already off, and therefore
1158 // keyguard has already been enabled.
1159 // However, if we added it at position 1 and we're turning it on, then position
1160 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1161 // on, so have to run the queue then.
1162 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001163 // While we're collapsing them, if it's going off, and the new reason
1164 // is more significant than the first, then use the new one.
1165 if (!on && mBroadcastWhy[0] > why) {
1166 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001167 }
1168 mBroadcastQueue[0] = on ? 1 : 0;
1169 mBroadcastQueue[1] = -1;
1170 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001171 mBroadcastWakeLock.release();
1172 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001173 index = 0;
1174 }
1175 if (index == 1 && !on) {
1176 mBroadcastQueue[0] = -1;
1177 mBroadcastQueue[1] = -1;
1178 index = -1;
1179 // The wake lock was being held, but we're not actually going to do any
1180 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001181 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001183 }
1184
1185 // Now send the message.
1186 if (index >= 0) {
1187 // Acquire the broadcast wake lock before changing the power
1188 // state. It will be release after the broadcast is sent.
1189 // We always increment the ref count for each notification in the queue
1190 // and always decrement when that notification is handled.
1191 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001192 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001193 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 }
1195 }
1196
1197 private Runnable mNotificationTask = new Runnable()
1198 {
1199 public void run()
1200 {
Joe Onorato128e7292009-03-24 18:41:31 -07001201 while (true) {
1202 int value;
1203 int why;
1204 WindowManagerPolicy policy;
1205 synchronized (mLocks) {
1206 value = mBroadcastQueue[0];
1207 why = mBroadcastWhy[0];
1208 for (int i=0; i<2; i++) {
1209 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1210 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1211 }
1212 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 }
Joe Onorato128e7292009-03-24 18:41:31 -07001214 if (value == 1) {
1215 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001216
Joe Onorato128e7292009-03-24 18:41:31 -07001217 policy.screenTurnedOn();
1218 try {
1219 ActivityManagerNative.getDefault().wakingUp();
1220 } catch (RemoteException e) {
1221 // ignore it
1222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223
Joe Onorato128e7292009-03-24 18:41:31 -07001224 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001225 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001226 }
1227 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1228 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1229 mScreenOnBroadcastDone, mHandler, 0, null, null);
1230 } else {
1231 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001232 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001233 mBroadcastWakeLock.mCount);
1234 mBroadcastWakeLock.release();
1235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 }
1237 }
Joe Onorato128e7292009-03-24 18:41:31 -07001238 else if (value == 0) {
1239 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001240
Joe Onorato128e7292009-03-24 18:41:31 -07001241 policy.screenTurnedOff(why);
1242 try {
1243 ActivityManagerNative.getDefault().goingToSleep();
1244 } catch (RemoteException e) {
1245 // ignore it.
1246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247
Joe Onorato128e7292009-03-24 18:41:31 -07001248 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1249 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1250 mScreenOffBroadcastDone, mHandler, 0, null, null);
1251 } else {
1252 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001253 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001254 mBroadcastWakeLock.mCount);
1255 mBroadcastWakeLock.release();
1256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 }
1258 }
Joe Onorato128e7292009-03-24 18:41:31 -07001259 else {
1260 // If we're in this case, then this handler is running for a previous
1261 // paired transaction. mBroadcastWakeLock will already have been released.
1262 break;
1263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 }
1265 }
1266 };
1267
1268 long mScreenOnStart;
1269 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1270 public void onReceive(Context context, Intent intent) {
1271 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001272 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1274 mBroadcastWakeLock.release();
1275 }
1276 }
1277 };
1278
1279 long mScreenOffStart;
1280 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1281 public void onReceive(Context context, Intent intent) {
1282 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001283 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1285 mBroadcastWakeLock.release();
1286 }
1287 }
1288 };
1289
1290 void logPointerUpEvent() {
1291 if (LOG_TOUCH_DOWNS) {
1292 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1293 mLastTouchDown = 0;
1294 }
1295 }
1296
1297 void logPointerDownEvent() {
1298 if (LOG_TOUCH_DOWNS) {
1299 // If we are not already timing a down/up sequence
1300 if (mLastTouchDown == 0) {
1301 mLastTouchDown = SystemClock.elapsedRealtime();
1302 mTouchCycles++;
1303 }
1304 }
1305 }
1306
1307 /**
1308 * Prevents the screen from turning on even if it *should* turn on due
1309 * to a subsequent full wake lock being acquired.
1310 * <p>
1311 * This is a temporary hack that allows an activity to "cover up" any
1312 * display glitches that happen during the activity's startup
1313 * sequence. (Specifically, this API was added to work around a
1314 * cosmetic bug in the "incoming call" sequence, where the lock screen
1315 * would flicker briefly before the incoming call UI became visible.)
1316 * TODO: There ought to be a more elegant way of doing this,
1317 * probably by having the PowerManager and ActivityManager
1318 * work together to let apps specify that the screen on/off
1319 * state should be synchronized with the Activity lifecycle.
1320 * <p>
1321 * Note that calling preventScreenOn(true) will NOT turn the screen
1322 * off if it's currently on. (This API only affects *future*
1323 * acquisitions of full wake locks.)
1324 * But calling preventScreenOn(false) WILL turn the screen on if
1325 * it's currently off because of a prior preventScreenOn(true) call.
1326 * <p>
1327 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1328 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1329 * call doesn't occur within 5 seconds, we'll turn the screen back on
1330 * ourselves (and log a warning about it); this prevents a buggy app
1331 * from disabling the screen forever.)
1332 * <p>
1333 * TODO: this feature should really be controlled by a new type of poke
1334 * lock (rather than an IPowerManager call).
1335 */
1336 public void preventScreenOn(boolean prevent) {
1337 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1338
1339 synchronized (mLocks) {
1340 if (prevent) {
1341 // First of all, grab a partial wake lock to
1342 // make sure the CPU stays on during the entire
1343 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1344 mPreventScreenOnPartialLock.acquire();
1345
1346 // Post a forceReenableScreen() call (for 5 seconds in the
1347 // future) to make sure the matching preventScreenOn(false) call
1348 // has happened by then.
1349 mHandler.removeCallbacks(mForceReenableScreenTask);
1350 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1351
1352 // Finally, set the flag that prevents the screen from turning on.
1353 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001354 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 mPreventScreenOn = true;
1356 } else {
1357 // (Re)enable the screen.
1358 mPreventScreenOn = false;
1359
1360 // We're "undoing" a the prior preventScreenOn(true) call, so we
1361 // no longer need the 5-second safeguard.
1362 mHandler.removeCallbacks(mForceReenableScreenTask);
1363
1364 // Forcibly turn on the screen if it's supposed to be on. (This
1365 // handles the case where the screen is currently off because of
1366 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001367 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001369 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1371 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001372 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001374 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 }
1376 }
1377
1378 // Release the partial wake lock that we held during the
1379 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1380 mPreventScreenOnPartialLock.release();
1381 }
1382 }
1383 }
1384
1385 public void setScreenBrightnessOverride(int brightness) {
1386 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1387
Mike Lockwoodf527c712010-06-10 14:12:33 -04001388 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 synchronized (mLocks) {
1390 if (mScreenBrightnessOverride != brightness) {
1391 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001392 if (isScreenOn()) {
1393 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 }
1396 }
1397 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001398
1399 public void setButtonBrightnessOverride(int brightness) {
1400 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1401
Mike Lockwoodf527c712010-06-10 14:12:33 -04001402 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001403 synchronized (mLocks) {
1404 if (mButtonBrightnessOverride != brightness) {
1405 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001406 if (isScreenOn()) {
1407 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1408 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001409 }
1410 }
1411 }
1412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 /**
1414 * Sanity-check that gets called 5 seconds after any call to
1415 * preventScreenOn(true). This ensures that the original call
1416 * is followed promptly by a call to preventScreenOn(false).
1417 */
1418 private void forceReenableScreen() {
1419 // We shouldn't get here at all if mPreventScreenOn is false, since
1420 // we should have already removed any existing
1421 // mForceReenableScreenTask messages...
1422 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001423 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 return;
1425 }
1426
1427 // Uh oh. It's been 5 seconds since a call to
1428 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1429 // This means the app that called preventScreenOn(true) is either
1430 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1431 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1432 // crashed before doing so.)
1433
1434 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001435 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 + "Forcing the screen back on...");
1437 preventScreenOn(false);
1438 }
1439
1440 private Runnable mForceReenableScreenTask = new Runnable() {
1441 public void run() {
1442 forceReenableScreen();
1443 }
1444 };
1445
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001446 private int setScreenStateLocked(boolean on) {
1447 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001448 if (err == 0) {
1449 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1450 if (mUseSoftwareAutoBrightness) {
1451 enableLightSensor(on);
1452 if (!on) {
1453 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001454 mButtonLight.turnOff();
1455 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001456 // clear current value so we will update based on the new conditions
1457 // when the sensor is reenabled.
1458 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001459 // reset our highest light sensor value when the screen turns off
1460 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001461 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001462 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001463 }
1464 return err;
1465 }
1466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 private void setPowerState(int state)
1468 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001469 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 }
1471
Mike Lockwood435eb642009-12-03 08:40:18 -05001472 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 {
1474 synchronized (mLocks) {
1475 int err;
1476
1477 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001478 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001480 + " noChangeLights=" + noChangeLights
1481 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
1483
1484 if (noChangeLights) {
1485 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1486 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001487 if (mProximitySensorActive) {
1488 // don't turn on the screen when the proximity sensor lock is held
1489 newState = (newState & ~SCREEN_BRIGHT);
1490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491
1492 if (batteryIsLow()) {
1493 newState |= BATTERY_LOW_BIT;
1494 } else {
1495 newState &= ~BATTERY_LOW_BIT;
1496 }
1497 if (newState == mPowerState) {
1498 return;
1499 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001500
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001501 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 newState |= ALL_BRIGHT;
1503 }
1504
1505 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1506 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1507
Mike Lockwood51b84492009-11-16 21:51:18 -05001508 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001509 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001511 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001513 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001515 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001517 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001519 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1521 }
1522
1523 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001524 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1526 }
1527
1528 if (oldScreenOn != newScreenOn) {
1529 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001530 // When the user presses the power button, we need to always send out the
1531 // notification that it's going to sleep so the keyguard goes on. But
1532 // we can't do that until the screen fades out, so we don't show the keyguard
1533 // too early.
1534 if (mStillNeedSleepNotification) {
1535 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1536 }
1537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 // Turn on the screen UNLESS there was a prior
1539 // preventScreenOn(true) request. (Note that the lifetime
1540 // of a single preventScreenOn() request is limited to 5
1541 // seconds to prevent a buggy app from disabling the
1542 // screen forever; see forceReenableScreen().)
1543 boolean reallyTurnScreenOn = true;
1544 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001545 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 + mPreventScreenOn);
1547 }
1548
1549 if (mPreventScreenOn) {
1550 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001551 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 }
1553 reallyTurnScreenOn = false;
1554 }
1555 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001556 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 long identity = Binder.clearCallingIdentity();
1558 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001559 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 mBatteryStats.noteScreenOn();
1561 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001562 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 } finally {
1564 Binder.restoreCallingIdentity(identity);
1565 }
1566 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001567 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 // But continue as if we really did turn the screen on...
1569 err = 0;
1570 }
1571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 mLastTouchDown = 0;
1573 mTotalTouchDownTime = 0;
1574 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001575 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 mTotalTouchDownTime, mTouchCycles);
1577 if (err == 0) {
1578 mPowerState |= SCREEN_ON_BIT;
1579 sendNotificationLocked(true, -1);
1580 }
1581 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001582 // cancel light sensor task
1583 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 mScreenOffTime = SystemClock.elapsedRealtime();
1585 long identity = Binder.clearCallingIdentity();
1586 try {
1587 mBatteryStats.noteScreenOff();
1588 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001589 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 } finally {
1591 Binder.restoreCallingIdentity(identity);
1592 }
1593 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001594 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001596 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 err = 0;
1599 mLastTouchDown = 0;
1600 }
1601 }
1602 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001603
1604 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 }
1606 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001607
1608 private void updateNativePowerStateLocked() {
1609 nativeSetPowerState(
1610 (mPowerState & SCREEN_ON_BIT) != 0,
1611 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1612 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001613
Mike Lockwood435eb642009-12-03 08:40:18 -05001614 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001616 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001618 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001620 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001622 mScreenOffReason = reason;
1623 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 }
1625 return err;
1626 }
1627
1628 private boolean batteryIsLow() {
1629 return (!mIsPowered &&
1630 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1631 }
1632
The Android Open Source Project10592532009-03-18 17:39:46 -07001633 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001634 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001635 newState = applyButtonState(newState);
1636 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001637 final int realDifference = (newState ^ oldState);
1638 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001640 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 int offMask = 0;
1644 int dimMask = 0;
1645 int onMask = 0;
1646
1647 int preferredBrightness = getPreferredBrightness();
1648 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1651 if (ANIMATE_KEYBOARD_LIGHTS) {
1652 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1653 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001654 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001655 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001657 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001658 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1659 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
1661 startAnimation = true;
1662 } else {
1663 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001664 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001666 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 }
1668 }
1669 }
1670
1671 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1672 if (ANIMATE_BUTTON_LIGHTS) {
1673 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1674 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001675 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001676 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001678 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001679 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1680 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 }
1682 startAnimation = true;
1683 } else {
1684 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001685 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001687 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
1689 }
1690 }
1691
1692 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1693 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001694 int nominalCurrentValue = -1;
1695 // If there was an actual difference in the light state, then
1696 // figure out the "ideal" current value based on the previous
1697 // state. Otherwise, this is a change due to the brightness
1698 // override, so we want to animate from whatever the current
1699 // value is.
1700 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1701 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1702 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1703 nominalCurrentValue = preferredBrightness;
1704 break;
1705 case SCREEN_ON_BIT:
1706 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1707 break;
1708 case 0:
1709 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1710 break;
1711 case SCREEN_BRIGHT_BIT:
1712 default:
1713 // not possible
1714 nominalCurrentValue = (int)mScreenBrightness.curValue;
1715 break;
1716 }
Joe Onorato128e7292009-03-24 18:41:31 -07001717 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001718 int brightness = preferredBrightness;
1719 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1721 // dim or turn off backlight, depending on if the screen is on
1722 // the scale is because the brightness ramp isn't linear and this biases
1723 // it so the later parts take longer.
1724 final float scale = 1.5f;
1725 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1726 if (ratio > 1.0f) ratio = 1.0f;
1727 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1729 // was bright
1730 steps = ANIM_STEPS;
1731 } else {
1732 // was dim
1733 steps = (int)(ANIM_STEPS*ratio*scale);
1734 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001735 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 if ((oldState & SCREEN_ON_BIT) != 0) {
1738 // was bright
1739 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1740 } else {
1741 // was dim
1742 steps = (int)(ANIM_STEPS*ratio);
1743 }
1744 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1745 // If the "stay on while plugged in" option is
1746 // turned on, then the screen will often not
1747 // automatically turn off while plugged in. To
1748 // still have a sense of when it is inactive, we
1749 // will then count going dim as turning off.
1750 mScreenOffTime = SystemClock.elapsedRealtime();
1751 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001752 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001755 long identity = Binder.clearCallingIdentity();
1756 try {
1757 mBatteryStats.noteScreenBrightness(brightness);
1758 } catch (RemoteException e) {
1759 // Nothing interesting to do.
1760 } finally {
1761 Binder.restoreCallingIdentity(identity);
1762 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001763 if (mScreenBrightness.setTargetLocked(brightness,
1764 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1765 startAnimation = true;
1766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 } else {
1768 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1769 // dim or turn off backlight, depending on if the screen is on
1770 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001771 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001773 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 }
1775 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001776 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 }
1778 }
1779 }
1780
1781 if (startAnimation) {
1782 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001783 Slog.i(TAG, "Scheduling light animator!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 }
1785 mHandler.removeCallbacks(mLightAnimator);
1786 mHandler.post(mLightAnimator);
1787 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001790 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001791 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 }
1793 if (dimMask != 0) {
1794 int brightness = Power.BRIGHTNESS_DIM;
1795 if ((newState & BATTERY_LOW_BIT) != 0 &&
1796 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1797 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1798 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001799 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001800 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 }
1802 if (onMask != 0) {
1803 int brightness = getPreferredBrightness();
1804 if ((newState & BATTERY_LOW_BIT) != 0 &&
1805 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1806 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1807 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001808 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001809 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812
The Android Open Source Project10592532009-03-18 17:39:46 -07001813 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001814 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001815 ? LightsService.BRIGHTNESS_MODE_SENSOR
1816 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001817 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001818 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001819 }
1820 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001821 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001822 }
1823 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001824 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827
1828 class BrightnessState {
1829 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 boolean initialized;
1832 int targetValue;
1833 float curValue;
1834 float delta;
1835 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 BrightnessState(int m) {
1838 mask = m;
1839 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 public void dump(PrintWriter pw, String prefix) {
1842 pw.println(prefix + "animating=" + animating
1843 + " targetValue=" + targetValue
1844 + " curValue=" + curValue
1845 + " delta=" + delta);
1846 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001847
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001848 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001849 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 if (!initialized) {
1851 initialized = true;
1852 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001853 } else if (targetValue == target) {
1854 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
1856 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001857 delta = (targetValue -
1858 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1859 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001861 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato8a9b2202010-02-26 18:56:32 -08001862 Slog.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001863 + " target=" + targetValue + " delta=" + delta
1864 + " nominalCurrentValue=" + nominalCurrentValue
1865 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 }
1867 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001868 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 boolean stepLocked() {
1872 if (!animating) return false;
1873 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001874 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 + " target=" + targetValue + " delta=" + delta);
1876 }
1877 curValue += delta;
1878 int curIntValue = (int)curValue;
1879 boolean more = true;
1880 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001881 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 more = false;
1883 } else if (delta > 0) {
1884 if (curIntValue >= targetValue) {
1885 curValue = curIntValue = targetValue;
1886 more = false;
1887 }
1888 } else {
1889 if (curIntValue <= targetValue) {
1890 curValue = curIntValue = targetValue;
1891 more = false;
1892 }
1893 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001894 //Slog.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001895 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 animating = more;
1897 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001898 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001899 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 }
1901 }
1902 return more;
1903 }
1904 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 private class LightAnimator implements Runnable {
1907 public void run() {
1908 synchronized (mLocks) {
1909 long now = SystemClock.uptimeMillis();
1910 boolean more = mScreenBrightness.stepLocked();
1911 if (mKeyboardBrightness.stepLocked()) {
1912 more = true;
1913 }
1914 if (mButtonBrightness.stepLocked()) {
1915 more = true;
1916 }
1917 if (more) {
1918 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1919 }
1920 }
1921 }
1922 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 private int getPreferredBrightness() {
1925 try {
1926 if (mScreenBrightnessOverride >= 0) {
1927 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001928 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001929 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001930 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 }
1932 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1933 SCREEN_BRIGHTNESS);
1934 // Don't let applications turn the screen all the way off
1935 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1936 } catch (SettingNotFoundException snfe) {
1937 return Power.BRIGHTNESS_ON;
1938 }
1939 }
1940
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001941 private int applyButtonState(int state) {
1942 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04001943 if ((state & BATTERY_LOW_BIT) != 0) {
1944 // do not override brightness if the battery is low
1945 return state;
1946 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001947 if (mButtonBrightnessOverride >= 0) {
1948 brightness = mButtonBrightnessOverride;
1949 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
1950 brightness = mLightSensorButtonBrightness;
1951 }
1952 if (brightness > 0) {
1953 return state | BUTTON_BRIGHT_BIT;
1954 } else if (brightness == 0) {
1955 return state & ~BUTTON_BRIGHT_BIT;
1956 } else {
1957 return state;
1958 }
1959 }
1960
1961 private int applyKeyboardState(int state) {
1962 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04001963 if ((state & BATTERY_LOW_BIT) != 0) {
1964 // do not override brightness if the battery is low
1965 return state;
1966 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001967 if (!mKeyboardVisible) {
1968 brightness = 0;
1969 } else if (mButtonBrightnessOverride >= 0) {
1970 brightness = mButtonBrightnessOverride;
1971 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
1972 brightness = mLightSensorKeyboardBrightness;
1973 }
1974 if (brightness > 0) {
1975 return state | KEYBOARD_BRIGHT_BIT;
1976 } else if (brightness == 0) {
1977 return state & ~KEYBOARD_BRIGHT_BIT;
1978 } else {
1979 return state;
1980 }
1981 }
1982
Charles Mendis322591c2009-10-29 11:06:59 -07001983 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 synchronized (mLocks) {
1985 return (mPowerState & SCREEN_ON_BIT) != 0;
1986 }
1987 }
1988
Charles Mendis322591c2009-10-29 11:06:59 -07001989 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 synchronized (mLocks) {
1991 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1992 }
1993 }
1994
Mike Lockwood497087e32009-11-08 18:33:03 -05001995 private boolean isScreenTurningOffLocked() {
1996 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1997 }
1998
Mike Lockwood200b30b2009-09-20 00:23:59 -04001999 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002000 if (isScreenTurningOffLocked()) {
2001 // cancel animation so userActivity will succeed
2002 mScreenBrightness.animating = false;
2003 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002004 boolean savedActivityAllowed = mUserActivityAllowed;
2005 mUserActivityAllowed = true;
2006 userActivity(SystemClock.uptimeMillis(), false);
2007 mUserActivityAllowed = savedActivityAllowed;
2008 }
2009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2011 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002012 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 }
2014
2015 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002016 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 }
2018
2019 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002020 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 }
2022
2023 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002024 userActivity(time, -1, noChangeLights, eventType, force);
2025 }
2026
2027 /*
2028 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2029 * on with user activity. Don't use this function.
2030 */
2031 public void clearUserActivityTimeout(long now, long timeout) {
2032 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2033 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2034 userActivity(now, timeout, false, OTHER_EVENT, false);
2035 }
2036
2037 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2038 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2040
2041 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002042 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002044 Slog.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 }
2046 return;
2047 }
2048
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002049 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
2050 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
2051 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
2052 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002053 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002054 }
2055 return;
2056 }
2057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 if (false) {
2059 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002060 Slog.d(TAG, "userActivity !!!");//, new RuntimeException());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002062 Slog.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 }
2064 }
2065
2066 synchronized (mLocks) {
2067 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002068 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 + " mUserActivityAllowed=" + mUserActivityAllowed
2070 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002071 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2072 + " mProximitySensorActive=" + mProximitySensorActive
2073 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 }
Mike Lockwood05067122009-10-27 23:07:25 -04002075 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002076 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002077 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002078 return;
2079 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002080 // Disable proximity sensor if if user presses power key while we are in the
2081 // "waiting for proximity sensor to go negative" state.
2082 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2083 mProximitySensorActive = false;
2084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 if (mLastEventTime <= time || force) {
2086 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002087 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002088 // Only turn on button backlights if a button was pressed
2089 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002090 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2092 } else {
2093 // don't clear button/keyboard backlights when the screen is touched.
2094 mUserState |= SCREEN_BRIGHT;
2095 }
2096
Dianne Hackborn617f8772009-03-31 15:04:46 -07002097 int uid = Binder.getCallingUid();
2098 long ident = Binder.clearCallingIdentity();
2099 try {
2100 mBatteryStats.noteUserActivity(uid, eventType);
2101 } catch (RemoteException e) {
2102 // Ignore
2103 } finally {
2104 Binder.restoreCallingIdentity(ident);
2105 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002106
Michael Chane96440f2009-05-06 10:27:36 -07002107 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002108 setPowerState(mUserState | mWakeLockState, noChangeLights,
2109 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002110 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 }
2112 }
2113 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002114
2115 if (mPolicy != null) {
2116 mPolicy.userActivity();
2117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 }
2119
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002120 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2121 try {
2122 int i;
2123 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2124 if (sensorValue < mAutoBrightnessLevels[i]) {
2125 break;
2126 }
2127 }
2128 return values[i];
2129 } catch (Exception e) {
2130 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002131 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002132 return 255;
2133 }
2134 }
2135
Mike Lockwood20f87d72009-11-05 16:08:51 -05002136 private Runnable mProximityTask = new Runnable() {
2137 public void run() {
2138 synchronized (mLocks) {
2139 if (mProximityPendingValue != -1) {
2140 proximityChangedLocked(mProximityPendingValue == 1);
2141 mProximityPendingValue = -1;
2142 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002143 if (mProximityPartialLock.isHeld()) {
2144 mProximityPartialLock.release();
2145 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002146 }
2147 }
2148 };
2149
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002150 private Runnable mAutoBrightnessTask = new Runnable() {
2151 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002152 synchronized (mLocks) {
2153 int value = (int)mLightSensorPendingValue;
2154 if (value >= 0) {
2155 mLightSensorPendingValue = -1;
2156 lightSensorChangedLocked(value);
2157 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002158 }
2159 }
2160 };
2161
Mike Lockwoodb2865412010-02-02 22:40:33 -05002162 private void dockStateChanged(int state) {
2163 synchronized (mLocks) {
2164 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2165 if (mIsDocked) {
2166 mHighestLightSensorValue = -1;
2167 }
2168 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2169 // force lights recalculation
2170 int value = (int)mLightSensorValue;
2171 mLightSensorValue = -1;
2172 lightSensorChangedLocked(value);
2173 }
2174 }
2175 }
2176
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002177 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002178 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002179 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002180 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002181
Mike Lockwoodb2865412010-02-02 22:40:33 -05002182 // do not allow light sensor value to decrease
2183 if (mHighestLightSensorValue < value) {
2184 mHighestLightSensorValue = value;
2185 }
2186
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002187 if (mLightSensorValue != value) {
2188 mLightSensorValue = value;
2189 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002190 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2191 // we only do this if we are undocked, since lighting should be stable when
2192 // stationary in a dock.
2193 int lcdValue = getAutoBrightnessValue(
2194 (mIsDocked ? value : mHighestLightSensorValue),
2195 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002196 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002197 int keyboardValue;
2198 if (mKeyboardVisible) {
2199 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2200 } else {
2201 keyboardValue = 0;
2202 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002203 mLightSensorScreenBrightness = lcdValue;
2204 mLightSensorButtonBrightness = buttonValue;
2205 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002206
2207 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002208 Slog.d(TAG, "lcdValue " + lcdValue);
2209 Slog.d(TAG, "buttonValue " + buttonValue);
2210 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002211 }
2212
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002213 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002214 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002215 if (ANIMATE_SCREEN_LIGHTS) {
2216 if (mScreenBrightness.setTargetLocked(lcdValue,
2217 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2218 (int)mScreenBrightness.curValue)) {
2219 startAnimation = true;
2220 }
2221 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002222 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002223 ? LightsService.BRIGHTNESS_MODE_SENSOR
2224 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002225 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002226 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002227 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002228 if (mButtonBrightnessOverride < 0) {
2229 if (ANIMATE_BUTTON_LIGHTS) {
2230 if (mButtonBrightness.setTargetLocked(buttonValue,
2231 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2232 (int)mButtonBrightness.curValue)) {
2233 startAnimation = true;
2234 }
2235 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002236 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002237 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002238 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002239 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2240 if (ANIMATE_KEYBOARD_LIGHTS) {
2241 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2242 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2243 (int)mKeyboardBrightness.curValue)) {
2244 startAnimation = true;
2245 }
2246 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002247 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002248 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002249 }
2250 if (startAnimation) {
2251 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002252 Slog.i(TAG, "lightSensorChangedLocked scheduling light animator");
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002253 }
2254 mHandler.removeCallbacks(mLightAnimator);
2255 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002256 }
2257 }
2258 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002259 }
2260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 /**
2262 * The user requested that we go to sleep (probably with the power button).
2263 * This overrides all wake locks that are held.
2264 */
2265 public void goToSleep(long time)
2266 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002267 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2268 }
2269
2270 /**
2271 * The user requested that we go to sleep (probably with the power button).
2272 * This overrides all wake locks that are held.
2273 */
2274 public void goToSleepWithReason(long time, int reason)
2275 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2277 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002278 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 }
2280 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002283 * Reboot the device immediately, passing 'reason' (may be null)
2284 * to the underlying __reboot system call. Should not return.
2285 */
2286 public void reboot(String reason)
2287 {
2288 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002289
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002290 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2291 throw new IllegalStateException("Too early to call reboot()");
2292 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002293
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002294 final String finalReason = reason;
2295 Runnable runnable = new Runnable() {
2296 public void run() {
2297 synchronized (this) {
2298 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002299 }
2300
San Mehat1e512792010-01-07 10:40:29 -08002301 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002302 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002303 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002304 mHandler.post(runnable);
2305
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002306 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002307 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002308 while (true) {
2309 try {
2310 runnable.wait();
2311 } catch (InterruptedException e) {
2312 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002313 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002314 }
2315 }
2316
Dan Egnor60d87622009-12-16 16:32:58 -08002317 /**
2318 * Crash the runtime (causing a complete restart of the Android framework).
2319 * Requires REBOOT permission. Mostly for testing. Should not return.
2320 */
2321 public void crash(final String message)
2322 {
2323 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2324 Thread t = new Thread("PowerManagerService.crash()") {
2325 public void run() { throw new RuntimeException(message); }
2326 };
2327 try {
2328 t.start();
2329 t.join();
2330 } catch (InterruptedException e) {
2331 Log.wtf(TAG, e);
2332 }
2333 }
2334
Mike Lockwood435eb642009-12-03 08:40:18 -05002335 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336
2337 if (mLastEventTime <= time) {
2338 mLastEventTime = time;
2339 // cancel all of the wake locks
2340 mWakeLockState = SCREEN_OFF;
2341 int N = mLocks.size();
2342 int numCleared = 0;
2343 for (int i=0; i<N; i++) {
2344 WakeLock wl = mLocks.get(i);
2345 if (isScreenLock(wl.flags)) {
2346 mLocks.get(i).activated = false;
2347 numCleared++;
2348 }
2349 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002350 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002351 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002353 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 cancelTimerLocked();
2355 }
2356 }
2357
2358 public long timeSinceScreenOn() {
2359 synchronized (mLocks) {
2360 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2361 return 0;
2362 }
2363 return SystemClock.elapsedRealtime() - mScreenOffTime;
2364 }
2365 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002368 synchronized (mLocks) {
2369 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002370 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002371 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002372 if (mKeyboardVisible != visible) {
2373 mKeyboardVisible = visible;
2374 // don't signal user activity if the screen is off; other code
2375 // will take care of turning on due to a true change to the lid
2376 // switch and synchronized with the lock screen.
2377 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002378 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002379 // force recompute of backlight values
2380 if (mLightSensorValue >= 0) {
2381 int value = (int)mLightSensorValue;
2382 mLightSensorValue = -1;
2383 lightSensorChangedLocked(value);
2384 }
2385 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002386 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2387 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002388 }
2389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 }
2391
2392 /**
2393 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002394 * When disabling user activity we also reset user power state so the keyguard can reset its
2395 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 */
2397 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002398 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002399 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 synchronized (mLocks) {
2402 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002403 if (!enabled) {
2404 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2405 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 }
2408 }
2409
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002410 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002411 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002412 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002413 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002414 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002415 // force recompute of backlight values
2416 if (mLightSensorValue >= 0) {
2417 int value = (int)mLightSensorValue;
2418 mLightSensorValue = -1;
2419 lightSensorChangedLocked(value);
2420 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002421 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002422 }
2423 }
2424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 /** Sets the screen off timeouts:
2426 * mKeylightDelay
2427 * mDimDelay
2428 * mScreenOffDelay
2429 * */
2430 private void setScreenOffTimeoutsLocked() {
2431 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002432 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 mDimDelay = -1;
2434 mScreenOffDelay = 0;
2435 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2436 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2437 mDimDelay = -1;
2438 mScreenOffDelay = 0;
2439 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002440 int totalDelay = mScreenOffTimeoutSetting;
2441 if (totalDelay > mMaximumScreenOffTimeout) {
2442 totalDelay = mMaximumScreenOffTimeout;
2443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2445 if (totalDelay < 0) {
2446 mScreenOffDelay = Integer.MAX_VALUE;
2447 } else if (mKeylightDelay < totalDelay) {
2448 // subtract the time that the keylight delay. This will give us the
2449 // remainder of the time that we need to sleep to get the accurate
2450 // screen off timeout.
2451 mScreenOffDelay = totalDelay - mKeylightDelay;
2452 } else {
2453 mScreenOffDelay = 0;
2454 }
2455 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2456 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2457 mScreenOffDelay = LONG_DIM_TIME;
2458 } else {
2459 mDimDelay = -1;
2460 }
2461 }
2462 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002463 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2465 + " mDimScreen=" + mDimScreen);
2466 }
2467 }
2468
2469 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002470 * Refreshes cached secure settings. Called once on startup, and
2471 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 */
Doug Zongker43866e02010-01-07 12:09:54 -08002473 private void updateSettingsValues() {
2474 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002476 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002478 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 }
2480
2481 private class LockList extends ArrayList<WakeLock>
2482 {
2483 void addLock(WakeLock wl)
2484 {
2485 int index = getIndex(wl.binder);
2486 if (index < 0) {
2487 this.add(wl);
2488 }
2489 }
2490
2491 WakeLock removeLock(IBinder binder)
2492 {
2493 int index = getIndex(binder);
2494 if (index >= 0) {
2495 return this.remove(index);
2496 } else {
2497 return null;
2498 }
2499 }
2500
2501 int getIndex(IBinder binder)
2502 {
2503 int N = this.size();
2504 for (int i=0; i<N; i++) {
2505 if (this.get(i).binder == binder) {
2506 return i;
2507 }
2508 }
2509 return -1;
2510 }
2511
2512 int gatherState()
2513 {
2514 int result = 0;
2515 int N = this.size();
2516 for (int i=0; i<N; i++) {
2517 WakeLock wl = this.get(i);
2518 if (wl.activated) {
2519 if (isScreenLock(wl.flags)) {
2520 result |= wl.minState;
2521 }
2522 }
2523 }
2524 return result;
2525 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002526
Michael Chane96440f2009-05-06 10:27:36 -07002527 int reactivateScreenLocksLocked()
2528 {
2529 int result = 0;
2530 int N = this.size();
2531 for (int i=0; i<N; i++) {
2532 WakeLock wl = this.get(i);
2533 if (isScreenLock(wl.flags)) {
2534 wl.activated = true;
2535 result |= wl.minState;
2536 }
2537 }
2538 return result;
2539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 }
2541
2542 void setPolicy(WindowManagerPolicy p) {
2543 synchronized (mLocks) {
2544 mPolicy = p;
2545 mLocks.notifyAll();
2546 }
2547 }
2548
2549 WindowManagerPolicy getPolicyLocked() {
2550 while (mPolicy == null || !mDoneBooting) {
2551 try {
2552 mLocks.wait();
2553 } catch (InterruptedException e) {
2554 // Ignore
2555 }
2556 }
2557 return mPolicy;
2558 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002561 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2562 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2563 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002564 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002565 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002566 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002567 }
2568
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002569 // wait until sensors are enabled before turning on screen.
2570 // some devices will not activate the light sensor properly on boot
2571 // unless we do this.
2572 if (mUseSoftwareAutoBrightness) {
2573 // turn the screen on
2574 setPowerState(SCREEN_BRIGHT);
2575 } else {
2576 // turn everything on
2577 setPowerState(ALL_BRIGHT);
2578 }
2579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002581 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002583
Dianne Hackborn617f8772009-03-31 15:04:46 -07002584 long identity = Binder.clearCallingIdentity();
2585 try {
2586 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2587 mBatteryStats.noteScreenOn();
2588 } catch (RemoteException e) {
2589 // Nothing interesting to do.
2590 } finally {
2591 Binder.restoreCallingIdentity(identity);
2592 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002593 }
2594 }
2595
2596 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002597 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002598 synchronized (mLocks) {
2599 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2601 updateWakeLockLocked();
2602 mLocks.notifyAll();
2603 }
2604 }
2605
2606 public void monitor() {
2607 synchronized (mLocks) { }
2608 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002609
2610 public int getSupportedWakeLockFlags() {
2611 int result = PowerManager.PARTIAL_WAKE_LOCK
2612 | PowerManager.FULL_WAKE_LOCK
2613 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2614
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002615 if (mProximitySensor != null) {
2616 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2617 }
2618
2619 return result;
2620 }
2621
Mike Lockwood237a2992009-09-15 14:42:16 -04002622 public void setBacklightBrightness(int brightness) {
2623 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2624 // Don't let applications turn the screen all the way off
2625 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002626 mLcdLight.setBrightness(brightness);
2627 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2628 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002629 long identity = Binder.clearCallingIdentity();
2630 try {
2631 mBatteryStats.noteScreenBrightness(brightness);
2632 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002633 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
Mike Lockwood237a2992009-09-15 14:42:16 -04002634 } finally {
2635 Binder.restoreCallingIdentity(identity);
2636 }
2637
2638 // update our animation state
2639 if (ANIMATE_SCREEN_LIGHTS) {
2640 mScreenBrightness.curValue = brightness;
2641 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002642 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002643 }
2644 if (ANIMATE_KEYBOARD_LIGHTS) {
2645 mKeyboardBrightness.curValue = brightness;
2646 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002647 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002648 }
2649 if (ANIMATE_BUTTON_LIGHTS) {
2650 mButtonBrightness.curValue = brightness;
2651 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002652 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002653 }
2654 }
2655
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002656 public void setAttentionLight(boolean on, int color) {
2657 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002658 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002659 }
2660
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002661 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002662 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002663 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002664 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002665 if (!mProximitySensorEnabled) {
2666 // clear calling identity so sensor manager battery stats are accurate
2667 long identity = Binder.clearCallingIdentity();
2668 try {
2669 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2670 SensorManager.SENSOR_DELAY_NORMAL);
2671 mProximitySensorEnabled = true;
2672 } finally {
2673 Binder.restoreCallingIdentity(identity);
2674 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002675 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002676 }
2677
2678 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002679 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002680 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002681 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002682 if (mProximitySensorEnabled) {
2683 // clear calling identity so sensor manager battery stats are accurate
2684 long identity = Binder.clearCallingIdentity();
2685 try {
2686 mSensorManager.unregisterListener(mProximityListener);
2687 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002688 if (mProximityPartialLock.isHeld()) {
2689 mProximityPartialLock.release();
2690 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002691 mProximitySensorEnabled = false;
2692 } finally {
2693 Binder.restoreCallingIdentity(identity);
2694 }
2695 if (mProximitySensorActive) {
2696 mProximitySensorActive = false;
2697 forceUserActivityLocked();
2698 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002699 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002700 }
2701
Mike Lockwood20f87d72009-11-05 16:08:51 -05002702 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002703 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002704 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002705 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002706 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002707 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002708 return;
2709 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002710 if (active) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002711 goToSleepLocked(SystemClock.uptimeMillis(),
2712 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002713 mProximitySensorActive = true;
2714 } else {
2715 // proximity sensor negative events trigger as user activity.
2716 // temporarily set mUserActivityAllowed to true so this will work
2717 // even when the keyguard is on.
2718 mProximitySensorActive = false;
2719 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002720
2721 if (mProximityWakeLockCount == 0) {
2722 // disable sensor if we have no listeners left after proximity negative
2723 disableProximityLockLocked();
2724 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002725 }
2726 }
2727
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002728 private void enableLightSensor(boolean enable) {
2729 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002730 Slog.d(TAG, "enableLightSensor " + enable);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002731 }
2732 if (mSensorManager != null && mLightSensorEnabled != enable) {
2733 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002734 // clear calling identity so sensor manager battery stats are accurate
2735 long identity = Binder.clearCallingIdentity();
2736 try {
2737 if (enable) {
2738 mSensorManager.registerListener(mLightListener, mLightSensor,
2739 SensorManager.SENSOR_DELAY_NORMAL);
2740 } else {
2741 mSensorManager.unregisterListener(mLightListener);
2742 mHandler.removeCallbacks(mAutoBrightnessTask);
2743 }
2744 } finally {
2745 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002746 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002747 }
2748 }
2749
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002750 SensorEventListener mProximityListener = new SensorEventListener() {
2751 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002752 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002753 synchronized (mLocks) {
2754 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002755 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2756 mLastProximityEventTime = milliseconds;
2757 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002758 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002759
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002760 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002761 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2762 distance < mProximitySensor.getMaximumRange());
2763
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002764 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002765 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002766 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002767 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2768 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2769 mProximityPendingValue = (active ? 1 : 0);
2770 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002771 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002772 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002773 // process the value immediately
2774 mProximityPendingValue = -1;
2775 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002776 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002777
2778 // update mProximityPartialLock state
2779 boolean held = mProximityPartialLock.isHeld();
2780 if (!held && proximityTaskQueued) {
2781 // hold wakelock until mProximityTask runs
2782 mProximityPartialLock.acquire();
2783 } else if (held && !proximityTaskQueued) {
2784 mProximityPartialLock.release();
2785 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002786 }
2787 }
2788
2789 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2790 // ignore
2791 }
2792 };
2793
2794 SensorEventListener mLightListener = new SensorEventListener() {
2795 public void onSensorChanged(SensorEvent event) {
2796 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002797 // ignore light sensor while screen is turning off
2798 if (isScreenTurningOffLocked()) {
2799 return;
2800 }
2801
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002802 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002803 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002804 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002805 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002806 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002807 mHandler.removeCallbacks(mAutoBrightnessTask);
2808 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002809 if (mLightSensorValue == -1 ||
2810 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2811 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002812 lightSensorChangedLocked(value);
2813 } else {
2814 // delay processing to debounce the sensor
2815 mLightSensorPendingValue = value;
2816 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2817 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002818 } else {
2819 mLightSensorPendingValue = -1;
2820 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002821 }
2822 }
2823
2824 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2825 // ignore
2826 }
2827 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828}