blob: e9d5efce6bac556b6e3db228cae43e690d69e737 [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
1033 private void setTimeoutLocked(long now, int nextState)
1034 {
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001035 if (mBootCompleted) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 mHandler.removeCallbacks(mTimeoutTask);
1037 mTimeoutTask.nextState = nextState;
1038 long when = now;
1039 switch (nextState)
1040 {
1041 case SCREEN_BRIGHT:
1042 when += mKeylightDelay;
1043 break;
1044 case SCREEN_DIM:
1045 if (mDimDelay >= 0) {
1046 when += mDimDelay;
1047 break;
1048 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001049 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
1051 case SCREEN_OFF:
1052 synchronized (mLocks) {
1053 when += mScreenOffDelay;
1054 }
1055 break;
1056 }
1057 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001058 Slog.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 + " when=" + when);
1060 }
1061 mHandler.postAtTime(mTimeoutTask, when);
1062 mNextTimeout = when; // for debugging
1063 }
1064 }
1065
1066 private void cancelTimerLocked()
1067 {
1068 mHandler.removeCallbacks(mTimeoutTask);
1069 mTimeoutTask.nextState = -1;
1070 }
1071
1072 private class TimeoutTask implements Runnable
1073 {
1074 int nextState; // access should be synchronized on mLocks
1075 public void run()
1076 {
1077 synchronized (mLocks) {
1078 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001079 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 }
1081
1082 if (nextState == -1) {
1083 return;
1084 }
1085
1086 mUserState = this.nextState;
1087 setPowerState(this.nextState | mWakeLockState);
1088
1089 long now = SystemClock.uptimeMillis();
1090
1091 switch (this.nextState)
1092 {
1093 case SCREEN_BRIGHT:
1094 if (mDimDelay >= 0) {
1095 setTimeoutLocked(now, SCREEN_DIM);
1096 break;
1097 }
1098 case SCREEN_DIM:
1099 setTimeoutLocked(now, SCREEN_OFF);
1100 break;
1101 }
1102 }
1103 }
1104 }
1105
1106 private void sendNotificationLocked(boolean on, int why)
1107 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001108 if (!on) {
1109 mStillNeedSleepNotification = false;
1110 }
1111
Joe Onorato128e7292009-03-24 18:41:31 -07001112 // Add to the queue.
1113 int index = 0;
1114 while (mBroadcastQueue[index] != -1) {
1115 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
Joe Onorato128e7292009-03-24 18:41:31 -07001117 mBroadcastQueue[index] = on ? 1 : 0;
1118 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119
Joe Onorato128e7292009-03-24 18:41:31 -07001120 // If we added it position 2, then there is a pair that can be stripped.
1121 // If we added it position 1 and we're turning the screen off, we can strip
1122 // the pair and do nothing, because the screen is already off, and therefore
1123 // keyguard has already been enabled.
1124 // However, if we added it at position 1 and we're turning it on, then position
1125 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1126 // on, so have to run the queue then.
1127 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001128 // While we're collapsing them, if it's going off, and the new reason
1129 // is more significant than the first, then use the new one.
1130 if (!on && mBroadcastWhy[0] > why) {
1131 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001132 }
1133 mBroadcastQueue[0] = on ? 1 : 0;
1134 mBroadcastQueue[1] = -1;
1135 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001136 mBroadcastWakeLock.release();
1137 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001138 index = 0;
1139 }
1140 if (index == 1 && !on) {
1141 mBroadcastQueue[0] = -1;
1142 mBroadcastQueue[1] = -1;
1143 index = -1;
1144 // The wake lock was being held, but we're not actually going to do any
1145 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001146 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001148 }
1149
1150 // Now send the message.
1151 if (index >= 0) {
1152 // Acquire the broadcast wake lock before changing the power
1153 // state. It will be release after the broadcast is sent.
1154 // We always increment the ref count for each notification in the queue
1155 // and always decrement when that notification is handled.
1156 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001157 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001158 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 }
1160 }
1161
1162 private Runnable mNotificationTask = new Runnable()
1163 {
1164 public void run()
1165 {
Joe Onorato128e7292009-03-24 18:41:31 -07001166 while (true) {
1167 int value;
1168 int why;
1169 WindowManagerPolicy policy;
1170 synchronized (mLocks) {
1171 value = mBroadcastQueue[0];
1172 why = mBroadcastWhy[0];
1173 for (int i=0; i<2; i++) {
1174 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1175 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1176 }
1177 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 }
Joe Onorato128e7292009-03-24 18:41:31 -07001179 if (value == 1) {
1180 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001181
Joe Onorato128e7292009-03-24 18:41:31 -07001182 policy.screenTurnedOn();
1183 try {
1184 ActivityManagerNative.getDefault().wakingUp();
1185 } catch (RemoteException e) {
1186 // ignore it
1187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188
Joe Onorato128e7292009-03-24 18:41:31 -07001189 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001190 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001191 }
1192 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1193 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1194 mScreenOnBroadcastDone, mHandler, 0, null, null);
1195 } else {
1196 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001197 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001198 mBroadcastWakeLock.mCount);
1199 mBroadcastWakeLock.release();
1200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 }
1202 }
Joe Onorato128e7292009-03-24 18:41:31 -07001203 else if (value == 0) {
1204 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001205
Joe Onorato128e7292009-03-24 18:41:31 -07001206 policy.screenTurnedOff(why);
1207 try {
1208 ActivityManagerNative.getDefault().goingToSleep();
1209 } catch (RemoteException e) {
1210 // ignore it.
1211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212
Joe Onorato128e7292009-03-24 18:41:31 -07001213 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1214 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1215 mScreenOffBroadcastDone, mHandler, 0, null, null);
1216 } else {
1217 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001218 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001219 mBroadcastWakeLock.mCount);
1220 mBroadcastWakeLock.release();
1221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 }
1223 }
Joe Onorato128e7292009-03-24 18:41:31 -07001224 else {
1225 // If we're in this case, then this handler is running for a previous
1226 // paired transaction. mBroadcastWakeLock will already have been released.
1227 break;
1228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 }
1230 }
1231 };
1232
1233 long mScreenOnStart;
1234 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1235 public void onReceive(Context context, Intent intent) {
1236 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001237 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1239 mBroadcastWakeLock.release();
1240 }
1241 }
1242 };
1243
1244 long mScreenOffStart;
1245 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1246 public void onReceive(Context context, Intent intent) {
1247 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001248 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1250 mBroadcastWakeLock.release();
1251 }
1252 }
1253 };
1254
1255 void logPointerUpEvent() {
1256 if (LOG_TOUCH_DOWNS) {
1257 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1258 mLastTouchDown = 0;
1259 }
1260 }
1261
1262 void logPointerDownEvent() {
1263 if (LOG_TOUCH_DOWNS) {
1264 // If we are not already timing a down/up sequence
1265 if (mLastTouchDown == 0) {
1266 mLastTouchDown = SystemClock.elapsedRealtime();
1267 mTouchCycles++;
1268 }
1269 }
1270 }
1271
1272 /**
1273 * Prevents the screen from turning on even if it *should* turn on due
1274 * to a subsequent full wake lock being acquired.
1275 * <p>
1276 * This is a temporary hack that allows an activity to "cover up" any
1277 * display glitches that happen during the activity's startup
1278 * sequence. (Specifically, this API was added to work around a
1279 * cosmetic bug in the "incoming call" sequence, where the lock screen
1280 * would flicker briefly before the incoming call UI became visible.)
1281 * TODO: There ought to be a more elegant way of doing this,
1282 * probably by having the PowerManager and ActivityManager
1283 * work together to let apps specify that the screen on/off
1284 * state should be synchronized with the Activity lifecycle.
1285 * <p>
1286 * Note that calling preventScreenOn(true) will NOT turn the screen
1287 * off if it's currently on. (This API only affects *future*
1288 * acquisitions of full wake locks.)
1289 * But calling preventScreenOn(false) WILL turn the screen on if
1290 * it's currently off because of a prior preventScreenOn(true) call.
1291 * <p>
1292 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1293 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1294 * call doesn't occur within 5 seconds, we'll turn the screen back on
1295 * ourselves (and log a warning about it); this prevents a buggy app
1296 * from disabling the screen forever.)
1297 * <p>
1298 * TODO: this feature should really be controlled by a new type of poke
1299 * lock (rather than an IPowerManager call).
1300 */
1301 public void preventScreenOn(boolean prevent) {
1302 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1303
1304 synchronized (mLocks) {
1305 if (prevent) {
1306 // First of all, grab a partial wake lock to
1307 // make sure the CPU stays on during the entire
1308 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1309 mPreventScreenOnPartialLock.acquire();
1310
1311 // Post a forceReenableScreen() call (for 5 seconds in the
1312 // future) to make sure the matching preventScreenOn(false) call
1313 // has happened by then.
1314 mHandler.removeCallbacks(mForceReenableScreenTask);
1315 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1316
1317 // Finally, set the flag that prevents the screen from turning on.
1318 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001319 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 mPreventScreenOn = true;
1321 } else {
1322 // (Re)enable the screen.
1323 mPreventScreenOn = false;
1324
1325 // We're "undoing" a the prior preventScreenOn(true) call, so we
1326 // no longer need the 5-second safeguard.
1327 mHandler.removeCallbacks(mForceReenableScreenTask);
1328
1329 // Forcibly turn on the screen if it's supposed to be on. (This
1330 // handles the case where the screen is currently off because of
1331 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001332 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001334 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1336 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001337 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001339 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 }
1341 }
1342
1343 // Release the partial wake lock that we held during the
1344 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1345 mPreventScreenOnPartialLock.release();
1346 }
1347 }
1348 }
1349
1350 public void setScreenBrightnessOverride(int brightness) {
1351 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1352
Mike Lockwoodf527c712010-06-10 14:12:33 -04001353 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 synchronized (mLocks) {
1355 if (mScreenBrightnessOverride != brightness) {
1356 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001357 if (isScreenOn()) {
1358 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 }
1361 }
1362 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001363
1364 public void setButtonBrightnessOverride(int brightness) {
1365 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1366
Mike Lockwoodf527c712010-06-10 14:12:33 -04001367 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001368 synchronized (mLocks) {
1369 if (mButtonBrightnessOverride != brightness) {
1370 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001371 if (isScreenOn()) {
1372 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1373 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001374 }
1375 }
1376 }
1377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 /**
1379 * Sanity-check that gets called 5 seconds after any call to
1380 * preventScreenOn(true). This ensures that the original call
1381 * is followed promptly by a call to preventScreenOn(false).
1382 */
1383 private void forceReenableScreen() {
1384 // We shouldn't get here at all if mPreventScreenOn is false, since
1385 // we should have already removed any existing
1386 // mForceReenableScreenTask messages...
1387 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001388 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 return;
1390 }
1391
1392 // Uh oh. It's been 5 seconds since a call to
1393 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1394 // This means the app that called preventScreenOn(true) is either
1395 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1396 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1397 // crashed before doing so.)
1398
1399 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001400 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 + "Forcing the screen back on...");
1402 preventScreenOn(false);
1403 }
1404
1405 private Runnable mForceReenableScreenTask = new Runnable() {
1406 public void run() {
1407 forceReenableScreen();
1408 }
1409 };
1410
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001411 private int setScreenStateLocked(boolean on) {
1412 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001413 if (err == 0) {
1414 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1415 if (mUseSoftwareAutoBrightness) {
1416 enableLightSensor(on);
1417 if (!on) {
1418 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001419 mButtonLight.turnOff();
1420 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001421 // clear current value so we will update based on the new conditions
1422 // when the sensor is reenabled.
1423 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001424 // reset our highest light sensor value when the screen turns off
1425 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001426 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001427 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001428 }
1429 return err;
1430 }
1431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 private void setPowerState(int state)
1433 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001434 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
1436
Mike Lockwood435eb642009-12-03 08:40:18 -05001437 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 {
1439 synchronized (mLocks) {
1440 int err;
1441
1442 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001443 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001445 + " noChangeLights=" + noChangeLights
1446 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 }
1448
1449 if (noChangeLights) {
1450 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1451 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001452 if (mProximitySensorActive) {
1453 // don't turn on the screen when the proximity sensor lock is held
1454 newState = (newState & ~SCREEN_BRIGHT);
1455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456
1457 if (batteryIsLow()) {
1458 newState |= BATTERY_LOW_BIT;
1459 } else {
1460 newState &= ~BATTERY_LOW_BIT;
1461 }
1462 if (newState == mPowerState) {
1463 return;
1464 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001465
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001466 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 newState |= ALL_BRIGHT;
1468 }
1469
1470 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1471 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1472
Mike Lockwood51b84492009-11-16 21:51:18 -05001473 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001474 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001476 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001478 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001480 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001482 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001484 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1486 }
1487
1488 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001489 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1491 }
1492
1493 if (oldScreenOn != newScreenOn) {
1494 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001495 // When the user presses the power button, we need to always send out the
1496 // notification that it's going to sleep so the keyguard goes on. But
1497 // we can't do that until the screen fades out, so we don't show the keyguard
1498 // too early.
1499 if (mStillNeedSleepNotification) {
1500 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1501 }
1502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 // Turn on the screen UNLESS there was a prior
1504 // preventScreenOn(true) request. (Note that the lifetime
1505 // of a single preventScreenOn() request is limited to 5
1506 // seconds to prevent a buggy app from disabling the
1507 // screen forever; see forceReenableScreen().)
1508 boolean reallyTurnScreenOn = true;
1509 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001510 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 + mPreventScreenOn);
1512 }
1513
1514 if (mPreventScreenOn) {
1515 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001516 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 }
1518 reallyTurnScreenOn = false;
1519 }
1520 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001521 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 long identity = Binder.clearCallingIdentity();
1523 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001524 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 mBatteryStats.noteScreenOn();
1526 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001527 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 } finally {
1529 Binder.restoreCallingIdentity(identity);
1530 }
1531 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001532 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 // But continue as if we really did turn the screen on...
1534 err = 0;
1535 }
1536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 mLastTouchDown = 0;
1538 mTotalTouchDownTime = 0;
1539 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001540 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 mTotalTouchDownTime, mTouchCycles);
1542 if (err == 0) {
1543 mPowerState |= SCREEN_ON_BIT;
1544 sendNotificationLocked(true, -1);
1545 }
1546 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001547 // cancel light sensor task
1548 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 mScreenOffTime = SystemClock.elapsedRealtime();
1550 long identity = Binder.clearCallingIdentity();
1551 try {
1552 mBatteryStats.noteScreenOff();
1553 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001554 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 } finally {
1556 Binder.restoreCallingIdentity(identity);
1557 }
1558 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001559 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001561 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 err = 0;
1564 mLastTouchDown = 0;
1565 }
1566 }
1567 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001568
1569 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 }
1571 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001572
1573 private void updateNativePowerStateLocked() {
1574 nativeSetPowerState(
1575 (mPowerState & SCREEN_ON_BIT) != 0,
1576 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001578
Mike Lockwood435eb642009-12-03 08:40:18 -05001579 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001581 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001583 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001585 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001587 mScreenOffReason = reason;
1588 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 }
1590 return err;
1591 }
1592
1593 private boolean batteryIsLow() {
1594 return (!mIsPowered &&
1595 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1596 }
1597
The Android Open Source Project10592532009-03-18 17:39:46 -07001598 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001599 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001600 newState = applyButtonState(newState);
1601 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001602 final int realDifference = (newState ^ oldState);
1603 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001605 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 int offMask = 0;
1609 int dimMask = 0;
1610 int onMask = 0;
1611
1612 int preferredBrightness = getPreferredBrightness();
1613 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1616 if (ANIMATE_KEYBOARD_LIGHTS) {
1617 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1618 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001619 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001620 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001622 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001623 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1624 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 }
1626 startAnimation = true;
1627 } else {
1628 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001629 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001631 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 }
1633 }
1634 }
1635
1636 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1637 if (ANIMATE_BUTTON_LIGHTS) {
1638 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1639 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001640 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001641 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001643 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001644 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1645 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 }
1647 startAnimation = true;
1648 } else {
1649 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001650 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001652 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 }
1654 }
1655 }
1656
1657 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1658 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001659 int nominalCurrentValue = -1;
1660 // If there was an actual difference in the light state, then
1661 // figure out the "ideal" current value based on the previous
1662 // state. Otherwise, this is a change due to the brightness
1663 // override, so we want to animate from whatever the current
1664 // value is.
1665 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1666 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1667 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1668 nominalCurrentValue = preferredBrightness;
1669 break;
1670 case SCREEN_ON_BIT:
1671 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1672 break;
1673 case 0:
1674 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1675 break;
1676 case SCREEN_BRIGHT_BIT:
1677 default:
1678 // not possible
1679 nominalCurrentValue = (int)mScreenBrightness.curValue;
1680 break;
1681 }
Joe Onorato128e7292009-03-24 18:41:31 -07001682 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001683 int brightness = preferredBrightness;
1684 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1686 // dim or turn off backlight, depending on if the screen is on
1687 // the scale is because the brightness ramp isn't linear and this biases
1688 // it so the later parts take longer.
1689 final float scale = 1.5f;
1690 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1691 if (ratio > 1.0f) ratio = 1.0f;
1692 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1694 // was bright
1695 steps = ANIM_STEPS;
1696 } else {
1697 // was dim
1698 steps = (int)(ANIM_STEPS*ratio*scale);
1699 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001700 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 if ((oldState & SCREEN_ON_BIT) != 0) {
1703 // was bright
1704 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1705 } else {
1706 // was dim
1707 steps = (int)(ANIM_STEPS*ratio);
1708 }
1709 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1710 // If the "stay on while plugged in" option is
1711 // turned on, then the screen will often not
1712 // automatically turn off while plugged in. To
1713 // still have a sense of when it is inactive, we
1714 // will then count going dim as turning off.
1715 mScreenOffTime = SystemClock.elapsedRealtime();
1716 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001717 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001720 long identity = Binder.clearCallingIdentity();
1721 try {
1722 mBatteryStats.noteScreenBrightness(brightness);
1723 } catch (RemoteException e) {
1724 // Nothing interesting to do.
1725 } finally {
1726 Binder.restoreCallingIdentity(identity);
1727 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001728 if (mScreenBrightness.setTargetLocked(brightness,
1729 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1730 startAnimation = true;
1731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 } else {
1733 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1734 // dim or turn off backlight, depending on if the screen is on
1735 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001736 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001738 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 }
1740 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001741 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 }
1743 }
1744 }
1745
1746 if (startAnimation) {
1747 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001748 Slog.i(TAG, "Scheduling light animator!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 }
1750 mHandler.removeCallbacks(mLightAnimator);
1751 mHandler.post(mLightAnimator);
1752 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001755 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001756 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 }
1758 if (dimMask != 0) {
1759 int brightness = Power.BRIGHTNESS_DIM;
1760 if ((newState & BATTERY_LOW_BIT) != 0 &&
1761 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1762 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1763 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001764 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001765 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
1767 if (onMask != 0) {
1768 int brightness = getPreferredBrightness();
1769 if ((newState & BATTERY_LOW_BIT) != 0 &&
1770 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1771 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1772 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001773 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001774 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777
The Android Open Source Project10592532009-03-18 17:39:46 -07001778 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001779 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001780 ? LightsService.BRIGHTNESS_MODE_SENSOR
1781 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001782 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001783 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001784 }
1785 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001786 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001787 }
1788 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001789 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 }
1792
1793 class BrightnessState {
1794 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 boolean initialized;
1797 int targetValue;
1798 float curValue;
1799 float delta;
1800 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 BrightnessState(int m) {
1803 mask = m;
1804 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 public void dump(PrintWriter pw, String prefix) {
1807 pw.println(prefix + "animating=" + animating
1808 + " targetValue=" + targetValue
1809 + " curValue=" + curValue
1810 + " delta=" + delta);
1811 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001812
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001813 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001814 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 if (!initialized) {
1816 initialized = true;
1817 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001818 } else if (targetValue == target) {
1819 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 }
1821 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001822 delta = (targetValue -
1823 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1824 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001826 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato8a9b2202010-02-26 18:56:32 -08001827 Slog.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001828 + " target=" + targetValue + " delta=" + delta
1829 + " nominalCurrentValue=" + nominalCurrentValue
1830 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 }
1832 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001833 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 boolean stepLocked() {
1837 if (!animating) return false;
1838 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001839 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 + " target=" + targetValue + " delta=" + delta);
1841 }
1842 curValue += delta;
1843 int curIntValue = (int)curValue;
1844 boolean more = true;
1845 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001846 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 more = false;
1848 } else if (delta > 0) {
1849 if (curIntValue >= targetValue) {
1850 curValue = curIntValue = targetValue;
1851 more = false;
1852 }
1853 } else {
1854 if (curIntValue <= targetValue) {
1855 curValue = curIntValue = targetValue;
1856 more = false;
1857 }
1858 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001859 //Slog.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001860 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 animating = more;
1862 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001863 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001864 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 }
1866 }
1867 return more;
1868 }
1869 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 private class LightAnimator implements Runnable {
1872 public void run() {
1873 synchronized (mLocks) {
1874 long now = SystemClock.uptimeMillis();
1875 boolean more = mScreenBrightness.stepLocked();
1876 if (mKeyboardBrightness.stepLocked()) {
1877 more = true;
1878 }
1879 if (mButtonBrightness.stepLocked()) {
1880 more = true;
1881 }
1882 if (more) {
1883 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1884 }
1885 }
1886 }
1887 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 private int getPreferredBrightness() {
1890 try {
1891 if (mScreenBrightnessOverride >= 0) {
1892 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001893 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001894 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001895 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 }
1897 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1898 SCREEN_BRIGHTNESS);
1899 // Don't let applications turn the screen all the way off
1900 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1901 } catch (SettingNotFoundException snfe) {
1902 return Power.BRIGHTNESS_ON;
1903 }
1904 }
1905
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001906 private int applyButtonState(int state) {
1907 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04001908 if ((state & BATTERY_LOW_BIT) != 0) {
1909 // do not override brightness if the battery is low
1910 return state;
1911 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001912 if (mButtonBrightnessOverride >= 0) {
1913 brightness = mButtonBrightnessOverride;
1914 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
1915 brightness = mLightSensorButtonBrightness;
1916 }
1917 if (brightness > 0) {
1918 return state | BUTTON_BRIGHT_BIT;
1919 } else if (brightness == 0) {
1920 return state & ~BUTTON_BRIGHT_BIT;
1921 } else {
1922 return state;
1923 }
1924 }
1925
1926 private int applyKeyboardState(int state) {
1927 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04001928 if ((state & BATTERY_LOW_BIT) != 0) {
1929 // do not override brightness if the battery is low
1930 return state;
1931 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001932 if (!mKeyboardVisible) {
1933 brightness = 0;
1934 } else if (mButtonBrightnessOverride >= 0) {
1935 brightness = mButtonBrightnessOverride;
1936 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
1937 brightness = mLightSensorKeyboardBrightness;
1938 }
1939 if (brightness > 0) {
1940 return state | KEYBOARD_BRIGHT_BIT;
1941 } else if (brightness == 0) {
1942 return state & ~KEYBOARD_BRIGHT_BIT;
1943 } else {
1944 return state;
1945 }
1946 }
1947
Charles Mendis322591c2009-10-29 11:06:59 -07001948 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 synchronized (mLocks) {
1950 return (mPowerState & SCREEN_ON_BIT) != 0;
1951 }
1952 }
1953
Charles Mendis322591c2009-10-29 11:06:59 -07001954 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 synchronized (mLocks) {
1956 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1957 }
1958 }
1959
Mike Lockwood497087e32009-11-08 18:33:03 -05001960 private boolean isScreenTurningOffLocked() {
1961 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1962 }
1963
Mike Lockwood200b30b2009-09-20 00:23:59 -04001964 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05001965 if (isScreenTurningOffLocked()) {
1966 // cancel animation so userActivity will succeed
1967 mScreenBrightness.animating = false;
1968 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04001969 boolean savedActivityAllowed = mUserActivityAllowed;
1970 mUserActivityAllowed = true;
1971 userActivity(SystemClock.uptimeMillis(), false);
1972 mUserActivityAllowed = savedActivityAllowed;
1973 }
1974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1976 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1977 userActivity(time, noChangeLights, OTHER_EVENT, force);
1978 }
1979
1980 public void userActivity(long time, boolean noChangeLights) {
1981 userActivity(time, noChangeLights, OTHER_EVENT, false);
1982 }
1983
1984 public void userActivity(long time, boolean noChangeLights, int eventType) {
1985 userActivity(time, noChangeLights, eventType, false);
1986 }
1987
1988 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1989 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1990
1991 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001992 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001994 Slog.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 }
1996 return;
1997 }
1998
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001999 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
2000 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
2001 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
2002 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002003 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002004 }
2005 return;
2006 }
2007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 if (false) {
2009 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002010 Slog.d(TAG, "userActivity !!!");//, new RuntimeException());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002012 Slog.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 }
2014 }
2015
2016 synchronized (mLocks) {
2017 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002018 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 + " mUserActivityAllowed=" + mUserActivityAllowed
2020 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002021 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2022 + " mProximitySensorActive=" + mProximitySensorActive
2023 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 }
Mike Lockwood05067122009-10-27 23:07:25 -04002025 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002026 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002027 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002028 return;
2029 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002030 // Disable proximity sensor if if user presses power key while we are in the
2031 // "waiting for proximity sensor to go negative" state.
2032 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2033 mProximitySensorActive = false;
2034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 if (mLastEventTime <= time || force) {
2036 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002037 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002038 // Only turn on button backlights if a button was pressed
2039 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002040 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2042 } else {
2043 // don't clear button/keyboard backlights when the screen is touched.
2044 mUserState |= SCREEN_BRIGHT;
2045 }
2046
Dianne Hackborn617f8772009-03-31 15:04:46 -07002047 int uid = Binder.getCallingUid();
2048 long ident = Binder.clearCallingIdentity();
2049 try {
2050 mBatteryStats.noteUserActivity(uid, eventType);
2051 } catch (RemoteException e) {
2052 // Ignore
2053 } finally {
2054 Binder.restoreCallingIdentity(ident);
2055 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002056
Michael Chane96440f2009-05-06 10:27:36 -07002057 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002058 setPowerState(mUserState | mWakeLockState, noChangeLights,
2059 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 setTimeoutLocked(time, SCREEN_BRIGHT);
2061 }
2062 }
2063 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002064
2065 if (mPolicy != null) {
2066 mPolicy.userActivity();
2067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 }
2069
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002070 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2071 try {
2072 int i;
2073 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2074 if (sensorValue < mAutoBrightnessLevels[i]) {
2075 break;
2076 }
2077 }
2078 return values[i];
2079 } catch (Exception e) {
2080 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002081 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002082 return 255;
2083 }
2084 }
2085
Mike Lockwood20f87d72009-11-05 16:08:51 -05002086 private Runnable mProximityTask = new Runnable() {
2087 public void run() {
2088 synchronized (mLocks) {
2089 if (mProximityPendingValue != -1) {
2090 proximityChangedLocked(mProximityPendingValue == 1);
2091 mProximityPendingValue = -1;
2092 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002093 if (mProximityPartialLock.isHeld()) {
2094 mProximityPartialLock.release();
2095 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002096 }
2097 }
2098 };
2099
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002100 private Runnable mAutoBrightnessTask = new Runnable() {
2101 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002102 synchronized (mLocks) {
2103 int value = (int)mLightSensorPendingValue;
2104 if (value >= 0) {
2105 mLightSensorPendingValue = -1;
2106 lightSensorChangedLocked(value);
2107 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002108 }
2109 }
2110 };
2111
Mike Lockwoodb2865412010-02-02 22:40:33 -05002112 private void dockStateChanged(int state) {
2113 synchronized (mLocks) {
2114 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2115 if (mIsDocked) {
2116 mHighestLightSensorValue = -1;
2117 }
2118 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2119 // force lights recalculation
2120 int value = (int)mLightSensorValue;
2121 mLightSensorValue = -1;
2122 lightSensorChangedLocked(value);
2123 }
2124 }
2125 }
2126
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002127 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002128 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002129 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002130 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002131
Mike Lockwoodb2865412010-02-02 22:40:33 -05002132 // do not allow light sensor value to decrease
2133 if (mHighestLightSensorValue < value) {
2134 mHighestLightSensorValue = value;
2135 }
2136
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002137 if (mLightSensorValue != value) {
2138 mLightSensorValue = value;
2139 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002140 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2141 // we only do this if we are undocked, since lighting should be stable when
2142 // stationary in a dock.
2143 int lcdValue = getAutoBrightnessValue(
2144 (mIsDocked ? value : mHighestLightSensorValue),
2145 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002146 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002147 int keyboardValue;
2148 if (mKeyboardVisible) {
2149 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2150 } else {
2151 keyboardValue = 0;
2152 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002153 mLightSensorScreenBrightness = lcdValue;
2154 mLightSensorButtonBrightness = buttonValue;
2155 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002156
2157 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002158 Slog.d(TAG, "lcdValue " + lcdValue);
2159 Slog.d(TAG, "buttonValue " + buttonValue);
2160 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002161 }
2162
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002163 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002164 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002165 if (ANIMATE_SCREEN_LIGHTS) {
2166 if (mScreenBrightness.setTargetLocked(lcdValue,
2167 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2168 (int)mScreenBrightness.curValue)) {
2169 startAnimation = true;
2170 }
2171 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002172 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002173 ? LightsService.BRIGHTNESS_MODE_SENSOR
2174 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002175 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002176 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002177 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002178 if (mButtonBrightnessOverride < 0) {
2179 if (ANIMATE_BUTTON_LIGHTS) {
2180 if (mButtonBrightness.setTargetLocked(buttonValue,
2181 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2182 (int)mButtonBrightness.curValue)) {
2183 startAnimation = true;
2184 }
2185 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002186 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002187 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002188 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002189 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2190 if (ANIMATE_KEYBOARD_LIGHTS) {
2191 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2192 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2193 (int)mKeyboardBrightness.curValue)) {
2194 startAnimation = true;
2195 }
2196 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002197 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002198 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002199 }
2200 if (startAnimation) {
2201 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002202 Slog.i(TAG, "lightSensorChangedLocked scheduling light animator");
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002203 }
2204 mHandler.removeCallbacks(mLightAnimator);
2205 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002206 }
2207 }
2208 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002209 }
2210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 /**
2212 * The user requested that we go to sleep (probably with the power button).
2213 * This overrides all wake locks that are held.
2214 */
2215 public void goToSleep(long time)
2216 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002217 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2218 }
2219
2220 /**
2221 * The user requested that we go to sleep (probably with the power button).
2222 * This overrides all wake locks that are held.
2223 */
2224 public void goToSleepWithReason(long time, int reason)
2225 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2227 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002228 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002229 }
2230 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002233 * Reboot the device immediately, passing 'reason' (may be null)
2234 * to the underlying __reboot system call. Should not return.
2235 */
2236 public void reboot(String reason)
2237 {
2238 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002239
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002240 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2241 throw new IllegalStateException("Too early to call reboot()");
2242 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002243
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002244 final String finalReason = reason;
2245 Runnable runnable = new Runnable() {
2246 public void run() {
2247 synchronized (this) {
2248 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002249 }
2250
San Mehat1e512792010-01-07 10:40:29 -08002251 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002252 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002253 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002254 mHandler.post(runnable);
2255
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002256 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002257 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002258 while (true) {
2259 try {
2260 runnable.wait();
2261 } catch (InterruptedException e) {
2262 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002263 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002264 }
2265 }
2266
Dan Egnor60d87622009-12-16 16:32:58 -08002267 /**
2268 * Crash the runtime (causing a complete restart of the Android framework).
2269 * Requires REBOOT permission. Mostly for testing. Should not return.
2270 */
2271 public void crash(final String message)
2272 {
2273 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2274 Thread t = new Thread("PowerManagerService.crash()") {
2275 public void run() { throw new RuntimeException(message); }
2276 };
2277 try {
2278 t.start();
2279 t.join();
2280 } catch (InterruptedException e) {
2281 Log.wtf(TAG, e);
2282 }
2283 }
2284
Mike Lockwood435eb642009-12-03 08:40:18 -05002285 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286
2287 if (mLastEventTime <= time) {
2288 mLastEventTime = time;
2289 // cancel all of the wake locks
2290 mWakeLockState = SCREEN_OFF;
2291 int N = mLocks.size();
2292 int numCleared = 0;
2293 for (int i=0; i<N; i++) {
2294 WakeLock wl = mLocks.get(i);
2295 if (isScreenLock(wl.flags)) {
2296 mLocks.get(i).activated = false;
2297 numCleared++;
2298 }
2299 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002300 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002301 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002302 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002303 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 cancelTimerLocked();
2305 }
2306 }
2307
2308 public long timeSinceScreenOn() {
2309 synchronized (mLocks) {
2310 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2311 return 0;
2312 }
2313 return SystemClock.elapsedRealtime() - mScreenOffTime;
2314 }
2315 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002318 synchronized (mLocks) {
2319 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002320 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002321 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002322 if (mKeyboardVisible != visible) {
2323 mKeyboardVisible = visible;
2324 // don't signal user activity if the screen is off; other code
2325 // will take care of turning on due to a true change to the lid
2326 // switch and synchronized with the lock screen.
2327 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002328 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002329 // force recompute of backlight values
2330 if (mLightSensorValue >= 0) {
2331 int value = (int)mLightSensorValue;
2332 mLightSensorValue = -1;
2333 lightSensorChangedLocked(value);
2334 }
2335 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002336 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2337 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002338 }
2339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 }
2341
2342 /**
2343 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002344 * When disabling user activity we also reset user power state so the keyguard can reset its
2345 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 */
2347 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002348 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002349 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 synchronized (mLocks) {
2352 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002353 if (!enabled) {
2354 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2355 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 }
2358 }
2359
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002360 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002361 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002362 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002363 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002364 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002365 // force recompute of backlight values
2366 if (mLightSensorValue >= 0) {
2367 int value = (int)mLightSensorValue;
2368 mLightSensorValue = -1;
2369 lightSensorChangedLocked(value);
2370 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002371 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002372 }
2373 }
2374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 /** Sets the screen off timeouts:
2376 * mKeylightDelay
2377 * mDimDelay
2378 * mScreenOffDelay
2379 * */
2380 private void setScreenOffTimeoutsLocked() {
2381 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002382 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 mDimDelay = -1;
2384 mScreenOffDelay = 0;
2385 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2386 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2387 mDimDelay = -1;
2388 mScreenOffDelay = 0;
2389 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002390 int totalDelay = mScreenOffTimeoutSetting;
2391 if (totalDelay > mMaximumScreenOffTimeout) {
2392 totalDelay = mMaximumScreenOffTimeout;
2393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2395 if (totalDelay < 0) {
2396 mScreenOffDelay = Integer.MAX_VALUE;
2397 } else if (mKeylightDelay < totalDelay) {
2398 // subtract the time that the keylight delay. This will give us the
2399 // remainder of the time that we need to sleep to get the accurate
2400 // screen off timeout.
2401 mScreenOffDelay = totalDelay - mKeylightDelay;
2402 } else {
2403 mScreenOffDelay = 0;
2404 }
2405 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2406 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2407 mScreenOffDelay = LONG_DIM_TIME;
2408 } else {
2409 mDimDelay = -1;
2410 }
2411 }
2412 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002413 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2415 + " mDimScreen=" + mDimScreen);
2416 }
2417 }
2418
2419 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002420 * Refreshes cached secure settings. Called once on startup, and
2421 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 */
Doug Zongker43866e02010-01-07 12:09:54 -08002423 private void updateSettingsValues() {
2424 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002426 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002427 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002428 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 }
2430
2431 private class LockList extends ArrayList<WakeLock>
2432 {
2433 void addLock(WakeLock wl)
2434 {
2435 int index = getIndex(wl.binder);
2436 if (index < 0) {
2437 this.add(wl);
2438 }
2439 }
2440
2441 WakeLock removeLock(IBinder binder)
2442 {
2443 int index = getIndex(binder);
2444 if (index >= 0) {
2445 return this.remove(index);
2446 } else {
2447 return null;
2448 }
2449 }
2450
2451 int getIndex(IBinder binder)
2452 {
2453 int N = this.size();
2454 for (int i=0; i<N; i++) {
2455 if (this.get(i).binder == binder) {
2456 return i;
2457 }
2458 }
2459 return -1;
2460 }
2461
2462 int gatherState()
2463 {
2464 int result = 0;
2465 int N = this.size();
2466 for (int i=0; i<N; i++) {
2467 WakeLock wl = this.get(i);
2468 if (wl.activated) {
2469 if (isScreenLock(wl.flags)) {
2470 result |= wl.minState;
2471 }
2472 }
2473 }
2474 return result;
2475 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002476
Michael Chane96440f2009-05-06 10:27:36 -07002477 int reactivateScreenLocksLocked()
2478 {
2479 int result = 0;
2480 int N = this.size();
2481 for (int i=0; i<N; i++) {
2482 WakeLock wl = this.get(i);
2483 if (isScreenLock(wl.flags)) {
2484 wl.activated = true;
2485 result |= wl.minState;
2486 }
2487 }
2488 return result;
2489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 }
2491
2492 void setPolicy(WindowManagerPolicy p) {
2493 synchronized (mLocks) {
2494 mPolicy = p;
2495 mLocks.notifyAll();
2496 }
2497 }
2498
2499 WindowManagerPolicy getPolicyLocked() {
2500 while (mPolicy == null || !mDoneBooting) {
2501 try {
2502 mLocks.wait();
2503 } catch (InterruptedException e) {
2504 // Ignore
2505 }
2506 }
2507 return mPolicy;
2508 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002511 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2512 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2513 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002514 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002515 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002516 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002517 }
2518
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002519 // wait until sensors are enabled before turning on screen.
2520 // some devices will not activate the light sensor properly on boot
2521 // unless we do this.
2522 if (mUseSoftwareAutoBrightness) {
2523 // turn the screen on
2524 setPowerState(SCREEN_BRIGHT);
2525 } else {
2526 // turn everything on
2527 setPowerState(ALL_BRIGHT);
2528 }
2529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002531 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002533
Dianne Hackborn617f8772009-03-31 15:04:46 -07002534 long identity = Binder.clearCallingIdentity();
2535 try {
2536 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2537 mBatteryStats.noteScreenOn();
2538 } catch (RemoteException e) {
2539 // Nothing interesting to do.
2540 } finally {
2541 Binder.restoreCallingIdentity(identity);
2542 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002543 }
2544 }
2545
2546 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002547 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002548 synchronized (mLocks) {
2549 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2551 updateWakeLockLocked();
2552 mLocks.notifyAll();
2553 }
2554 }
2555
2556 public void monitor() {
2557 synchronized (mLocks) { }
2558 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002559
2560 public int getSupportedWakeLockFlags() {
2561 int result = PowerManager.PARTIAL_WAKE_LOCK
2562 | PowerManager.FULL_WAKE_LOCK
2563 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2564
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002565 if (mProximitySensor != null) {
2566 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2567 }
2568
2569 return result;
2570 }
2571
Mike Lockwood237a2992009-09-15 14:42:16 -04002572 public void setBacklightBrightness(int brightness) {
2573 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2574 // Don't let applications turn the screen all the way off
2575 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002576 mLcdLight.setBrightness(brightness);
2577 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2578 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002579 long identity = Binder.clearCallingIdentity();
2580 try {
2581 mBatteryStats.noteScreenBrightness(brightness);
2582 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002583 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
Mike Lockwood237a2992009-09-15 14:42:16 -04002584 } finally {
2585 Binder.restoreCallingIdentity(identity);
2586 }
2587
2588 // update our animation state
2589 if (ANIMATE_SCREEN_LIGHTS) {
2590 mScreenBrightness.curValue = brightness;
2591 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002592 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002593 }
2594 if (ANIMATE_KEYBOARD_LIGHTS) {
2595 mKeyboardBrightness.curValue = brightness;
2596 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002597 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002598 }
2599 if (ANIMATE_BUTTON_LIGHTS) {
2600 mButtonBrightness.curValue = brightness;
2601 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002602 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002603 }
2604 }
2605
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002606 public void setAttentionLight(boolean on, int color) {
2607 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002608 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002609 }
2610
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002611 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002612 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002613 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002614 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002615 if (!mProximitySensorEnabled) {
2616 // clear calling identity so sensor manager battery stats are accurate
2617 long identity = Binder.clearCallingIdentity();
2618 try {
2619 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2620 SensorManager.SENSOR_DELAY_NORMAL);
2621 mProximitySensorEnabled = true;
2622 } finally {
2623 Binder.restoreCallingIdentity(identity);
2624 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002625 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002626 }
2627
2628 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002629 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002630 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002631 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002632 if (mProximitySensorEnabled) {
2633 // clear calling identity so sensor manager battery stats are accurate
2634 long identity = Binder.clearCallingIdentity();
2635 try {
2636 mSensorManager.unregisterListener(mProximityListener);
2637 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002638 if (mProximityPartialLock.isHeld()) {
2639 mProximityPartialLock.release();
2640 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002641 mProximitySensorEnabled = false;
2642 } finally {
2643 Binder.restoreCallingIdentity(identity);
2644 }
2645 if (mProximitySensorActive) {
2646 mProximitySensorActive = false;
2647 forceUserActivityLocked();
2648 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002649 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002650 }
2651
Mike Lockwood20f87d72009-11-05 16:08:51 -05002652 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002653 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002654 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002655 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002656 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002657 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002658 return;
2659 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002660 if (active) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002661 goToSleepLocked(SystemClock.uptimeMillis(),
2662 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002663 mProximitySensorActive = true;
2664 } else {
2665 // proximity sensor negative events trigger as user activity.
2666 // temporarily set mUserActivityAllowed to true so this will work
2667 // even when the keyguard is on.
2668 mProximitySensorActive = false;
2669 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002670
2671 if (mProximityWakeLockCount == 0) {
2672 // disable sensor if we have no listeners left after proximity negative
2673 disableProximityLockLocked();
2674 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002675 }
2676 }
2677
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002678 private void enableLightSensor(boolean enable) {
2679 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002680 Slog.d(TAG, "enableLightSensor " + enable);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002681 }
2682 if (mSensorManager != null && mLightSensorEnabled != enable) {
2683 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002684 // clear calling identity so sensor manager battery stats are accurate
2685 long identity = Binder.clearCallingIdentity();
2686 try {
2687 if (enable) {
2688 mSensorManager.registerListener(mLightListener, mLightSensor,
2689 SensorManager.SENSOR_DELAY_NORMAL);
2690 } else {
2691 mSensorManager.unregisterListener(mLightListener);
2692 mHandler.removeCallbacks(mAutoBrightnessTask);
2693 }
2694 } finally {
2695 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002696 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002697 }
2698 }
2699
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002700 SensorEventListener mProximityListener = new SensorEventListener() {
2701 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002702 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002703 synchronized (mLocks) {
2704 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002705 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2706 mLastProximityEventTime = milliseconds;
2707 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002708 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002709
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002710 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002711 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2712 distance < mProximitySensor.getMaximumRange());
2713
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002714 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002715 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002716 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002717 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2718 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2719 mProximityPendingValue = (active ? 1 : 0);
2720 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002721 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002722 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002723 // process the value immediately
2724 mProximityPendingValue = -1;
2725 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002726 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002727
2728 // update mProximityPartialLock state
2729 boolean held = mProximityPartialLock.isHeld();
2730 if (!held && proximityTaskQueued) {
2731 // hold wakelock until mProximityTask runs
2732 mProximityPartialLock.acquire();
2733 } else if (held && !proximityTaskQueued) {
2734 mProximityPartialLock.release();
2735 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002736 }
2737 }
2738
2739 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2740 // ignore
2741 }
2742 };
2743
2744 SensorEventListener mLightListener = new SensorEventListener() {
2745 public void onSensorChanged(SensorEvent event) {
2746 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002747 // ignore light sensor while screen is turning off
2748 if (isScreenTurningOffLocked()) {
2749 return;
2750 }
2751
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002752 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002753 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002754 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002755 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002756 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002757 mHandler.removeCallbacks(mAutoBrightnessTask);
2758 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002759 if (mLightSensorValue == -1 ||
2760 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2761 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002762 lightSensorChangedLocked(value);
2763 } else {
2764 // delay processing to debounce the sensor
2765 mLightSensorPendingValue = value;
2766 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2767 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002768 } else {
2769 mLightSensorPendingValue = -1;
2770 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002771 }
2772 }
2773
2774 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2775 // ignore
2776 }
2777 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778}