blob: 4ee89ccbd2ac5c71fb798b6a5cfc5da3890091df [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;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700154 private final int MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155
156 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500157 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500159 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
160 private final int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 private int mPartialCount = 0;
162 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500163 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
164 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
165 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 private int mUserState;
167 private boolean mKeyboardVisible = false;
168 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500169 private int mProximityWakeLockCount = 0;
170 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700171 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500172 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
173 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800174 private int mScreenOffTimeoutSetting;
175 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 private int mKeylightDelay;
177 private int mDimDelay;
178 private int mScreenOffDelay;
179 private int mWakeLockState;
180 private long mLastEventTime = 0;
181 private long mScreenOffTime;
182 private volatile WindowManagerPolicy mPolicy;
183 private final LockList mLocks = new LockList();
184 private Intent mScreenOffIntent;
185 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500186 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500188 private LightsService.Light mLcdLight;
189 private LightsService.Light mButtonLight;
190 private LightsService.Light mKeyboardLight;
191 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 private UnsynchronizedWakeLock mBroadcastWakeLock;
193 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
194 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
195 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500196 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 private HandlerThread mHandlerThread;
198 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500199 private final TimeoutTask mTimeoutTask = new TimeoutTask();
200 private final LightAnimator mLightAnimator = new LightAnimator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700202 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700204 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700206 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700207 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 private boolean mIsPowered = false;
209 private IActivityManager mActivityService;
210 private IBatteryStats mBatteryStats;
211 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700212 private SensorManager mSensorManager;
213 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400214 private Sensor mLightSensor;
215 private boolean mLightSensorEnabled;
216 private float mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500217 private int mHighestLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700218 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500219 private int mLightSensorScreenBrightness = -1;
220 private int mLightSensorButtonBrightness = -1;
221 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500223 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 private long mNextTimeout;
225 private volatile int mPokey = 0;
226 private volatile boolean mPokeAwakeOnSet = false;
227 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500228 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500229 // mLastScreenOnTime is the time the screen was last turned on
230 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 private boolean mPreventScreenOn;
232 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500233 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400234 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700235 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700236 private int[] mAutoBrightnessLevels;
237 private int[] mLcdBacklightValues;
238 private int[] mButtonBacklightValues;
239 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500240 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 // Used when logging number and duration of touch-down cycles
243 private long mTotalTouchDownTime;
244 private long mLastTouchDown;
245 private int mTouchCycles;
246
247 // could be either static or controllable at runtime
248 private static final boolean mSpew = false;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500249 private static final boolean mDebugProximitySensor = (true || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400250 private static final boolean mDebugLightSensor = (false || mSpew);
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700251
252 private native void nativeInit();
253 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254
255 /*
256 static PrintStream mLog;
257 static {
258 try {
259 mLog = new PrintStream("/data/power.log");
260 }
261 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800262 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 }
264 }
265 static class Log {
266 static void d(String tag, String s) {
267 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800268 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 }
270 static void i(String tag, String s) {
271 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800272 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 }
274 static void w(String tag, String s) {
275 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800276 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 }
278 static void e(String tag, String s) {
279 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800280 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 }
282 }
283 */
284
285 /**
286 * This class works around a deadlock between the lock in PowerManager.WakeLock
287 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
288 * mToken object so it can be accessed from any thread, but it calls into here
289 * with its lock held. This class is essentially a reimplementation of
290 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
291 * only call it with our own locks held.
292 */
293 private class UnsynchronizedWakeLock {
294 int mFlags;
295 String mTag;
296 IBinder mToken;
297 int mCount = 0;
298 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500299 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300
301 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
302 mFlags = flags;
303 mTag = tag;
304 mToken = new Binder();
305 mRefCounted = refCounted;
306 }
307
308 public void acquire() {
309 if (!mRefCounted || mCount++ == 0) {
310 long ident = Binder.clearCallingIdentity();
311 try {
312 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700313 MY_UID, MY_PID, mTag);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500314 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 } finally {
316 Binder.restoreCallingIdentity(ident);
317 }
318 }
319 }
320
321 public void release() {
322 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500323 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500324 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 }
326 if (mCount < 0) {
327 throw new RuntimeException("WakeLock under-locked " + mTag);
328 }
329 }
330
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500331 public boolean isHeld()
332 {
333 return mHeld;
334 }
335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 public String toString() {
337 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500338 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 }
340 }
341
342 private final class BatteryReceiver extends BroadcastReceiver {
343 @Override
344 public void onReceive(Context context, Intent intent) {
345 synchronized (mLocks) {
346 boolean wasPowered = mIsPowered;
347 mIsPowered = mBatteryService.isPowered();
348
349 if (mIsPowered != wasPowered) {
350 // update mStayOnWhilePluggedIn wake lock
351 updateWakeLockLocked();
352
353 // treat plugging and unplugging the devices as a user activity.
354 // users find it disconcerting when they unplug the device
355 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500356 // to avoid turning on the screen when unplugging, we only trigger
357 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 // temporarily set mUserActivityAllowed to true so this will work
359 // even when the keyguard is on.
360 synchronized (mLocks) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500361 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0) {
362 forceUserActivityLocked();
363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 }
365 }
366 }
367 }
368 }
369
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500370 private final class BootCompletedReceiver extends BroadcastReceiver {
371 @Override
372 public void onReceive(Context context, Intent intent) {
373 bootCompleted();
374 }
375 }
376
Mike Lockwoodb2865412010-02-02 22:40:33 -0500377 private final class DockReceiver extends BroadcastReceiver {
378 @Override
379 public void onReceive(Context context, Intent intent) {
380 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
381 Intent.EXTRA_DOCK_STATE_UNDOCKED);
382 dockStateChanged(state);
383 }
384 }
385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 /**
387 * Set the setting that determines whether the device stays on when plugged in.
388 * The argument is a bit string, with each bit specifying a power source that,
389 * when the device is connected to that source, causes the device to stay on.
390 * See {@link android.os.BatteryManager} for the list of power sources that
391 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
392 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
393 * @param val an {@code int} containing the bits that specify which power sources
394 * should cause the device to stay on.
395 */
396 public void setStayOnSetting(int val) {
397 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
398 Settings.System.putInt(mContext.getContentResolver(),
399 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
400 }
401
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800402 public void setMaximumScreenOffTimeount(int timeMs) {
403 mContext.enforceCallingOrSelfPermission(
404 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
405 synchronized (mLocks) {
406 mMaximumScreenOffTimeout = timeMs;
407 // recalculate everything
408 setScreenOffTimeoutsLocked();
409 }
410 }
411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 private class SettingsObserver implements Observer {
413 private int getInt(String name) {
414 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
415 }
416
417 public void update(Observable o, Object arg) {
418 synchronized (mLocks) {
419 // STAY_ON_WHILE_PLUGGED_IN
420 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
421 updateWakeLockLocked();
422
423 // SCREEN_OFF_TIMEOUT
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800424 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425
426 // DIM_SCREEN
427 //mDimScreen = getInt(DIM_SCREEN) != 0;
428
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700429 // SCREEN_BRIGHTNESS_MODE
430 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 // recalculate everything
433 setScreenOffTimeoutsLocked();
434 }
435 }
436 }
437
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700438 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 // Hack to get our uid... should have a func for this.
440 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700441 MY_UID = Process.myUid();
442 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 Binder.restoreCallingIdentity(token);
444
445 // XXX remove this when the kernel doesn't timeout wake locks
446 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
447
448 // assume nothing is on yet
449 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 // Add ourself to the Watchdog monitors.
452 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 }
454
455 private ContentQueryMap mSettings;
456
Mike Lockwood3a322132009-11-24 00:30:52 -0500457 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700458 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500459 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 mContext = context;
461 mActivityService = activity;
462 mBatteryStats = BatteryStatsService.getService();
463 mBatteryService = battery;
464
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500465 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
466 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
467 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
468 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800470 mHandlerThread = new HandlerThread("PowerManagerService") {
471 @Override
472 protected void onLooperPrepared() {
473 super.onLooperPrepared();
474 initInThread();
475 }
476 };
477 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 synchronized (mHandlerThread) {
480 while (!mInitComplete) {
481 try {
482 mHandlerThread.wait();
483 } catch (InterruptedException e) {
484 // Ignore
485 }
486 }
487 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700488
489 nativeInit();
490 synchronized (mLocks) {
491 updateNativePowerStateLocked();
492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 void initInThread() {
496 mHandler = new Handler();
497
498 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700499 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
501 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
502 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
503 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
504 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
505 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500506 mProximityPartialLock = new UnsynchronizedWakeLock(
507 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508
509 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
510 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
511 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
512 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
513
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700514 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400515
516 // read settings for auto-brightness
517 mUseSoftwareAutoBrightness = resources.getBoolean(
518 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400519 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700520 mAutoBrightnessLevels = resources.getIntArray(
521 com.android.internal.R.array.config_autoBrightnessLevels);
522 mLcdBacklightValues = resources.getIntArray(
523 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
524 mButtonBacklightValues = resources.getIntArray(
525 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
526 mKeyboardBacklightValues = resources.getIntArray(
527 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500528 mLightSensorWarmupTime = resources.getInteger(
529 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700530 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700531
532 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
534 "(" + Settings.System.NAME + "=?) or ("
535 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700536 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700538 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
539 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 null);
541 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
542 SettingsObserver settingsObserver = new SettingsObserver();
543 mSettings.addObserver(settingsObserver);
544
545 // pretend that the settings changed so we will get their initial state
546 settingsObserver.update(mSettings, null);
547
548 // register for the battery changed notifications
549 IntentFilter filter = new IntentFilter();
550 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
551 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500552 filter = new IntentFilter();
553 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
554 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500555 filter = new IntentFilter();
556 filter.addAction(Intent.ACTION_DOCK_EVENT);
557 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558
Doug Zongker43866e02010-01-07 12:09:54 -0800559 // Listen for secure settings changes
560 mContext.getContentResolver().registerContentObserver(
561 Settings.Secure.CONTENT_URI, true,
562 new ContentObserver(new Handler()) {
563 public void onChange(boolean selfChange) {
564 updateSettingsValues();
565 }
566 });
567 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 synchronized (mHandlerThread) {
570 mInitComplete = true;
571 mHandlerThread.notifyAll();
572 }
573 }
574
575 private class WakeLock implements IBinder.DeathRecipient
576 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700577 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 super();
579 flags = f;
580 binder = b;
581 tag = t;
582 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700583 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 if (u != MY_UID || (
585 !"KEEP_SCREEN_ON_FLAG".equals(tag)
586 && !"KeyInputQueue".equals(tag))) {
587 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
588 ? BatteryStats.WAKE_TYPE_PARTIAL
589 : BatteryStats.WAKE_TYPE_FULL;
590 } else {
591 monitorType = -1;
592 }
593 try {
594 b.linkToDeath(this, 0);
595 } catch (RemoteException e) {
596 binderDied();
597 }
598 }
599 public void binderDied() {
600 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500601 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 }
603 }
604 final int flags;
605 final IBinder binder;
606 final String tag;
607 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400608 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 final int monitorType;
610 boolean activated = true;
611 int minState;
612 }
613
614 private void updateWakeLockLocked() {
615 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
616 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
617 mStayOnWhilePluggedInScreenDimLock.acquire();
618 mStayOnWhilePluggedInPartialLock.acquire();
619 } else {
620 mStayOnWhilePluggedInScreenDimLock.release();
621 mStayOnWhilePluggedInPartialLock.release();
622 }
623 }
624
625 private boolean isScreenLock(int flags)
626 {
627 int n = flags & LOCK_MASK;
628 return n == PowerManager.FULL_WAKE_LOCK
629 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
630 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
631 }
632
633 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700635 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700636 if (uid != Process.myUid()) {
637 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 long ident = Binder.clearCallingIdentity();
640 try {
641 synchronized (mLocks) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700642 acquireWakeLockLocked(flags, lock, uid, pid, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 }
644 } finally {
645 Binder.restoreCallingIdentity(ident);
646 }
647 }
648
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700649 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 int acquireUid = -1;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700651 int acquirePid = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 String acquireName = null;
653 int acquireType = -1;
654
655 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800656 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 }
658
659 int index = mLocks.getIndex(lock);
660 WakeLock wl;
661 boolean newlock;
662 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700663 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 switch (wl.flags & LOCK_MASK)
665 {
666 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500667 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400668 wl.minState = SCREEN_BRIGHT;
669 } else {
670 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 break;
673 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
674 wl.minState = SCREEN_BRIGHT;
675 break;
676 case PowerManager.SCREEN_DIM_WAKE_LOCK:
677 wl.minState = SCREEN_DIM;
678 break;
679 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700680 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 break;
682 default:
683 // just log and bail. we're in the server, so don't
684 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800685 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 + " flags=" + flags);
687 return;
688 }
689 mLocks.addLock(wl);
690 newlock = true;
691 } else {
692 wl = mLocks.get(index);
693 newlock = false;
694 }
695 if (isScreenLock(flags)) {
696 // if this causes a wakeup, we reactivate all of the locks and
697 // set it to whatever they want. otherwise, we modulate that
698 // by the current state so we never turn it more on than
699 // it already is.
700 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700701 int oldWakeLockState = mWakeLockState;
702 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800704 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700705 + " mWakeLockState=0x"
706 + Integer.toHexString(mWakeLockState)
707 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 } else {
710 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800711 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 + " mLocks.gatherState()=0x"
713 + Integer.toHexString(mLocks.gatherState())
714 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
715 }
716 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
717 }
718 setPowerState(mWakeLockState | mUserState);
719 }
720 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
721 if (newlock) {
722 mPartialCount++;
723 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800724 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 }
726 }
727 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700728 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500729 mProximityWakeLockCount++;
730 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700731 enableProximityLockLocked();
732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 }
734 if (newlock) {
735 acquireUid = wl.uid;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700736 acquirePid = wl.pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 acquireName = wl.tag;
738 acquireType = wl.monitorType;
739 }
740
741 if (acquireType >= 0) {
742 try {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700743 mBatteryStats.noteStartWakelock(acquireUid, acquirePid, acquireName, acquireType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 } catch (RemoteException e) {
745 // Ignore
746 }
747 }
748 }
749
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500750 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700751 int uid = Binder.getCallingUid();
752 if (uid != Process.myUid()) {
753 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755
756 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500757 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 }
759 }
760
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500761 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 int releaseUid;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700763 int releasePid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 String releaseName;
765 int releaseType;
766
767 WakeLock wl = mLocks.removeLock(lock);
768 if (wl == null) {
769 return;
770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800773 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
775 }
776
777 if (isScreenLock(wl.flags)) {
778 mWakeLockState = mLocks.gatherState();
779 // goes in the middle to reduce flicker
780 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
781 userActivity(SystemClock.uptimeMillis(), false);
782 }
783 setPowerState(mWakeLockState | mUserState);
784 }
785 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
786 mPartialCount--;
787 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800788 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 Power.releaseWakeLock(PARTIAL_NAME);
790 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700791 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500792 mProximityWakeLockCount--;
793 if (mProximityWakeLockCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500794 if (mProximitySensorActive &&
795 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500796 // wait for proximity sensor to go negative before disabling sensor
797 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800798 Slog.d(TAG, "waiting for proximity sensor to go negative");
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500799 }
800 } else {
801 disableProximityLockLocked();
802 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 }
805 // Unlink the lock from the binder.
806 wl.binder.unlinkToDeath(wl, 0);
807 releaseUid = wl.uid;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700808 releasePid = wl.pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 releaseName = wl.tag;
810 releaseType = wl.monitorType;
811
812 if (releaseType >= 0) {
813 long origId = Binder.clearCallingIdentity();
814 try {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700815 mBatteryStats.noteStopWakelock(releaseUid, releasePid, releaseName, releaseType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 } catch (RemoteException e) {
817 // Ignore
818 } finally {
819 Binder.restoreCallingIdentity(origId);
820 }
821 }
822 }
823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 private class PokeLock implements IBinder.DeathRecipient
825 {
826 PokeLock(int p, IBinder b, String t) {
827 super();
828 this.pokey = p;
829 this.binder = b;
830 this.tag = t;
831 try {
832 b.linkToDeath(this, 0);
833 } catch (RemoteException e) {
834 binderDied();
835 }
836 }
837 public void binderDied() {
838 setPokeLock(0, this.binder, this.tag);
839 }
840 int pokey;
841 IBinder binder;
842 String tag;
843 boolean awakeOnSet;
844 }
845
846 public void setPokeLock(int pokey, IBinder token, String tag) {
847 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
848 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800849 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 return;
851 }
852
853 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
854 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
855 + " and POKE_LOCK_MEDIUM_TIMEOUT");
856 }
857
858 synchronized (mLocks) {
859 if (pokey != 0) {
860 PokeLock p = mPokeLocks.get(token);
861 int oldPokey = 0;
862 if (p != null) {
863 oldPokey = p.pokey;
864 p.pokey = pokey;
865 } else {
866 p = new PokeLock(pokey, token, tag);
867 mPokeLocks.put(token, p);
868 }
869 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
870 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
871 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
872 p.awakeOnSet = true;
873 }
874 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700875 PokeLock rLock = mPokeLocks.remove(token);
876 if (rLock != null) {
877 token.unlinkToDeath(rLock, 0);
878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 }
880
881 int oldPokey = mPokey;
882 int cumulative = 0;
883 boolean oldAwakeOnSet = mPokeAwakeOnSet;
884 boolean awakeOnSet = false;
885 for (PokeLock p: mPokeLocks.values()) {
886 cumulative |= p.pokey;
887 if (p.awakeOnSet) {
888 awakeOnSet = true;
889 }
890 }
891 mPokey = cumulative;
892 mPokeAwakeOnSet = awakeOnSet;
893
894 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
895 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 if (oldCumulativeTimeout != newCumulativeTimeout) {
898 setScreenOffTimeoutsLocked();
899 // reset the countdown timer, but use the existing nextState so it doesn't
900 // change anything
901 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
902 }
903 }
904 }
905
906 private static String lockType(int type)
907 {
908 switch (type)
909 {
910 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700911 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700913 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700915 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700917 return "PARTIAL_WAKE_LOCK ";
918 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
919 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 default:
David Brown251faa62009-08-02 22:04:36 -0700921 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 }
923 }
924
925 private static String dumpPowerState(int state) {
926 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
927 ? "KEYBOARD_BRIGHT_BIT " : "")
928 + (((state & SCREEN_BRIGHT_BIT) != 0)
929 ? "SCREEN_BRIGHT_BIT " : "")
930 + (((state & SCREEN_ON_BIT) != 0)
931 ? "SCREEN_ON_BIT " : "")
932 + (((state & BATTERY_LOW_BIT) != 0)
933 ? "BATTERY_LOW_BIT " : "");
934 }
935
936 @Override
937 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
938 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
939 != PackageManager.PERMISSION_GRANTED) {
940 pw.println("Permission Denial: can't dump PowerManager from from pid="
941 + Binder.getCallingPid()
942 + ", uid=" + Binder.getCallingUid());
943 return;
944 }
945
946 long now = SystemClock.uptimeMillis();
947
Mike Lockwoodca44df82010-02-25 13:48:49 -0500948 synchronized (mLocks) {
949 pw.println("Power Manager State:");
950 pw.println(" mIsPowered=" + mIsPowered
951 + " mPowerState=" + mPowerState
952 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
953 + " ms");
954 pw.println(" mPartialCount=" + mPartialCount);
955 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
956 pw.println(" mUserState=" + dumpPowerState(mUserState));
957 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
958 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
959 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
960 + " " + ((mNextTimeout-now)/1000) + "s from now");
961 pw.println(" mDimScreen=" + mDimScreen
962 + " mStayOnConditions=" + mStayOnConditions);
963 pw.println(" mScreenOffReason=" + mScreenOffReason
964 + " mUserState=" + mUserState);
965 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
966 + ',' + mBroadcastQueue[2] + "}");
967 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
968 + ',' + mBroadcastWhy[2] + "}");
969 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
970 pw.println(" mKeyboardVisible=" + mKeyboardVisible
971 + " mUserActivityAllowed=" + mUserActivityAllowed);
972 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
973 + " mScreenOffDelay=" + mScreenOffDelay);
974 pw.println(" mPreventScreenOn=" + mPreventScreenOn
975 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
976 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
977 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
978 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
979 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
980 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
981 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
982 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
983 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
984 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
985 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
986 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
987 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
988 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
989 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
990 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
991 pw.println(" mLightSensorValue=" + mLightSensorValue
992 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
993 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
994 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
995 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
996 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
997 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
998 mScreenBrightness.dump(pw, " mScreenBrightness: ");
999 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
1000 mButtonBrightness.dump(pw, " mButtonBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001001
Mike Lockwoodca44df82010-02-25 13:48:49 -05001002 int N = mLocks.size();
1003 pw.println();
1004 pw.println("mLocks.size=" + N + ":");
1005 for (int i=0; i<N; i++) {
1006 WakeLock wl = mLocks.get(i);
1007 String type = lockType(wl.flags & LOCK_MASK);
1008 String acquireCausesWakeup = "";
1009 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1010 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1011 }
1012 String activated = "";
1013 if (wl.activated) {
1014 activated = " activated";
1015 }
1016 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001017 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1018 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001020
1021 pw.println();
1022 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1023 for (PokeLock p: mPokeLocks.values()) {
1024 pw.println(" poke lock '" + p.tag + "':"
1025 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
1026 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
1027 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
1028 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
1029 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1030 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1031 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1032 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001034
Mike Lockwoodca44df82010-02-25 13:48:49 -05001035 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
1038
Joe Onorato7999bff2010-07-24 11:50:05 -04001039 private void setTimeoutLocked(long now, int nextState) {
1040 setTimeoutLocked(now, -1, nextState);
1041 }
1042
1043 // If they gave a timeoutOverride it is the number of seconds
1044 // to screen-off. Figure out where in the countdown cycle we
1045 // should jump to.
1046 private void setTimeoutLocked(long now, long timeoutOverride, int nextState) {
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001047 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001048 synchronized (mLocks) {
1049 mHandler.removeCallbacks(mTimeoutTask);
1050 mTimeoutTask.nextState = nextState;
1051 long when = 0;
1052 if (timeoutOverride <= 0) {
1053 switch (nextState)
1054 {
1055 case SCREEN_BRIGHT:
1056 when = now + mKeylightDelay;
1057 break;
1058 case SCREEN_DIM:
1059 if (mDimDelay >= 0) {
1060 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001061 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001062 } else {
1063 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1064 }
1065 case SCREEN_OFF:
1066 synchronized (mLocks) {
1067 when = now + mScreenOffDelay;
1068 }
1069 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001070 default:
1071 when = now;
1072 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001074 } else {
1075 override: {
1076 if (timeoutOverride <= mScreenOffDelay) {
1077 when = now + timeoutOverride;
1078 nextState = SCREEN_OFF;
1079 break override;
1080 }
1081 timeoutOverride -= mScreenOffDelay;
1082
1083 if (mDimDelay >= 0) {
1084 if (timeoutOverride <= mDimDelay) {
1085 when = now + timeoutOverride;
1086 nextState = SCREEN_DIM;
1087 break override;
1088 }
1089 timeoutOverride -= mDimDelay;
1090 }
1091
1092 when = now + timeoutOverride;
1093 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001095 }
1096 if (mSpew) {
1097 Slog.d(TAG, "setTimeoutLocked now=" + now
1098 + " timeoutOverride=" + timeoutOverride
1099 + " nextState=" + nextState + " when=" + when);
1100 }
1101 mHandler.postAtTime(mTimeoutTask, when);
1102 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 }
1105 }
1106
1107 private void cancelTimerLocked()
1108 {
1109 mHandler.removeCallbacks(mTimeoutTask);
1110 mTimeoutTask.nextState = -1;
1111 }
1112
1113 private class TimeoutTask implements Runnable
1114 {
1115 int nextState; // access should be synchronized on mLocks
1116 public void run()
1117 {
1118 synchronized (mLocks) {
1119 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001120 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 }
1122
1123 if (nextState == -1) {
1124 return;
1125 }
1126
1127 mUserState = this.nextState;
1128 setPowerState(this.nextState | mWakeLockState);
1129
1130 long now = SystemClock.uptimeMillis();
1131
1132 switch (this.nextState)
1133 {
1134 case SCREEN_BRIGHT:
1135 if (mDimDelay >= 0) {
1136 setTimeoutLocked(now, SCREEN_DIM);
1137 break;
1138 }
1139 case SCREEN_DIM:
1140 setTimeoutLocked(now, SCREEN_OFF);
1141 break;
1142 }
1143 }
1144 }
1145 }
1146
1147 private void sendNotificationLocked(boolean on, int why)
1148 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001149 if (!on) {
1150 mStillNeedSleepNotification = false;
1151 }
1152
Joe Onorato128e7292009-03-24 18:41:31 -07001153 // Add to the queue.
1154 int index = 0;
1155 while (mBroadcastQueue[index] != -1) {
1156 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 }
Joe Onorato128e7292009-03-24 18:41:31 -07001158 mBroadcastQueue[index] = on ? 1 : 0;
1159 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160
Joe Onorato128e7292009-03-24 18:41:31 -07001161 // If we added it position 2, then there is a pair that can be stripped.
1162 // If we added it position 1 and we're turning the screen off, we can strip
1163 // the pair and do nothing, because the screen is already off, and therefore
1164 // keyguard has already been enabled.
1165 // However, if we added it at position 1 and we're turning it on, then position
1166 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1167 // on, so have to run the queue then.
1168 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001169 // While we're collapsing them, if it's going off, and the new reason
1170 // is more significant than the first, then use the new one.
1171 if (!on && mBroadcastWhy[0] > why) {
1172 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001173 }
1174 mBroadcastQueue[0] = on ? 1 : 0;
1175 mBroadcastQueue[1] = -1;
1176 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001177 mBroadcastWakeLock.release();
1178 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001179 index = 0;
1180 }
1181 if (index == 1 && !on) {
1182 mBroadcastQueue[0] = -1;
1183 mBroadcastQueue[1] = -1;
1184 index = -1;
1185 // The wake lock was being held, but we're not actually going to do any
1186 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001187 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001189 }
1190
1191 // Now send the message.
1192 if (index >= 0) {
1193 // Acquire the broadcast wake lock before changing the power
1194 // state. It will be release after the broadcast is sent.
1195 // We always increment the ref count for each notification in the queue
1196 // and always decrement when that notification is handled.
1197 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001198 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001199 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 }
1201 }
1202
1203 private Runnable mNotificationTask = new Runnable()
1204 {
1205 public void run()
1206 {
Joe Onorato128e7292009-03-24 18:41:31 -07001207 while (true) {
1208 int value;
1209 int why;
1210 WindowManagerPolicy policy;
1211 synchronized (mLocks) {
1212 value = mBroadcastQueue[0];
1213 why = mBroadcastWhy[0];
1214 for (int i=0; i<2; i++) {
1215 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1216 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1217 }
1218 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 }
Joe Onorato128e7292009-03-24 18:41:31 -07001220 if (value == 1) {
1221 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001222
Joe Onorato128e7292009-03-24 18:41:31 -07001223 policy.screenTurnedOn();
1224 try {
1225 ActivityManagerNative.getDefault().wakingUp();
1226 } catch (RemoteException e) {
1227 // ignore it
1228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229
Joe Onorato128e7292009-03-24 18:41:31 -07001230 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001231 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001232 }
1233 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1234 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1235 mScreenOnBroadcastDone, mHandler, 0, null, null);
1236 } else {
1237 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001238 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001239 mBroadcastWakeLock.mCount);
1240 mBroadcastWakeLock.release();
1241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 }
1243 }
Joe Onorato128e7292009-03-24 18:41:31 -07001244 else if (value == 0) {
1245 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001246
Joe Onorato128e7292009-03-24 18:41:31 -07001247 policy.screenTurnedOff(why);
1248 try {
1249 ActivityManagerNative.getDefault().goingToSleep();
1250 } catch (RemoteException e) {
1251 // ignore it.
1252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253
Joe Onorato128e7292009-03-24 18:41:31 -07001254 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1255 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1256 mScreenOffBroadcastDone, mHandler, 0, null, null);
1257 } else {
1258 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001259 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001260 mBroadcastWakeLock.mCount);
1261 mBroadcastWakeLock.release();
1262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 }
1264 }
Joe Onorato128e7292009-03-24 18:41:31 -07001265 else {
1266 // If we're in this case, then this handler is running for a previous
1267 // paired transaction. mBroadcastWakeLock will already have been released.
1268 break;
1269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 }
1271 }
1272 };
1273
1274 long mScreenOnStart;
1275 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1276 public void onReceive(Context context, Intent intent) {
1277 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001278 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1280 mBroadcastWakeLock.release();
1281 }
1282 }
1283 };
1284
1285 long mScreenOffStart;
1286 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1287 public void onReceive(Context context, Intent intent) {
1288 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001289 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1291 mBroadcastWakeLock.release();
1292 }
1293 }
1294 };
1295
1296 void logPointerUpEvent() {
1297 if (LOG_TOUCH_DOWNS) {
1298 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1299 mLastTouchDown = 0;
1300 }
1301 }
1302
1303 void logPointerDownEvent() {
1304 if (LOG_TOUCH_DOWNS) {
1305 // If we are not already timing a down/up sequence
1306 if (mLastTouchDown == 0) {
1307 mLastTouchDown = SystemClock.elapsedRealtime();
1308 mTouchCycles++;
1309 }
1310 }
1311 }
1312
1313 /**
1314 * Prevents the screen from turning on even if it *should* turn on due
1315 * to a subsequent full wake lock being acquired.
1316 * <p>
1317 * This is a temporary hack that allows an activity to "cover up" any
1318 * display glitches that happen during the activity's startup
1319 * sequence. (Specifically, this API was added to work around a
1320 * cosmetic bug in the "incoming call" sequence, where the lock screen
1321 * would flicker briefly before the incoming call UI became visible.)
1322 * TODO: There ought to be a more elegant way of doing this,
1323 * probably by having the PowerManager and ActivityManager
1324 * work together to let apps specify that the screen on/off
1325 * state should be synchronized with the Activity lifecycle.
1326 * <p>
1327 * Note that calling preventScreenOn(true) will NOT turn the screen
1328 * off if it's currently on. (This API only affects *future*
1329 * acquisitions of full wake locks.)
1330 * But calling preventScreenOn(false) WILL turn the screen on if
1331 * it's currently off because of a prior preventScreenOn(true) call.
1332 * <p>
1333 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1334 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1335 * call doesn't occur within 5 seconds, we'll turn the screen back on
1336 * ourselves (and log a warning about it); this prevents a buggy app
1337 * from disabling the screen forever.)
1338 * <p>
1339 * TODO: this feature should really be controlled by a new type of poke
1340 * lock (rather than an IPowerManager call).
1341 */
1342 public void preventScreenOn(boolean prevent) {
1343 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1344
1345 synchronized (mLocks) {
1346 if (prevent) {
1347 // First of all, grab a partial wake lock to
1348 // make sure the CPU stays on during the entire
1349 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1350 mPreventScreenOnPartialLock.acquire();
1351
1352 // Post a forceReenableScreen() call (for 5 seconds in the
1353 // future) to make sure the matching preventScreenOn(false) call
1354 // has happened by then.
1355 mHandler.removeCallbacks(mForceReenableScreenTask);
1356 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1357
1358 // Finally, set the flag that prevents the screen from turning on.
1359 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001360 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 mPreventScreenOn = true;
1362 } else {
1363 // (Re)enable the screen.
1364 mPreventScreenOn = false;
1365
1366 // We're "undoing" a the prior preventScreenOn(true) call, so we
1367 // no longer need the 5-second safeguard.
1368 mHandler.removeCallbacks(mForceReenableScreenTask);
1369
1370 // Forcibly turn on the screen if it's supposed to be on. (This
1371 // handles the case where the screen is currently off because of
1372 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001373 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001375 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1377 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001378 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001380 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 }
1382 }
1383
1384 // Release the partial wake lock that we held during the
1385 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1386 mPreventScreenOnPartialLock.release();
1387 }
1388 }
1389 }
1390
1391 public void setScreenBrightnessOverride(int brightness) {
1392 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1393
Mike Lockwoodf527c712010-06-10 14:12:33 -04001394 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 synchronized (mLocks) {
1396 if (mScreenBrightnessOverride != brightness) {
1397 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001398 if (isScreenOn()) {
1399 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 }
1402 }
1403 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001404
1405 public void setButtonBrightnessOverride(int brightness) {
1406 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1407
Mike Lockwoodf527c712010-06-10 14:12:33 -04001408 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001409 synchronized (mLocks) {
1410 if (mButtonBrightnessOverride != brightness) {
1411 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001412 if (isScreenOn()) {
1413 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1414 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001415 }
1416 }
1417 }
1418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 /**
1420 * Sanity-check that gets called 5 seconds after any call to
1421 * preventScreenOn(true). This ensures that the original call
1422 * is followed promptly by a call to preventScreenOn(false).
1423 */
1424 private void forceReenableScreen() {
1425 // We shouldn't get here at all if mPreventScreenOn is false, since
1426 // we should have already removed any existing
1427 // mForceReenableScreenTask messages...
1428 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001429 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 return;
1431 }
1432
1433 // Uh oh. It's been 5 seconds since a call to
1434 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1435 // This means the app that called preventScreenOn(true) is either
1436 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1437 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1438 // crashed before doing so.)
1439
1440 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001441 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 + "Forcing the screen back on...");
1443 preventScreenOn(false);
1444 }
1445
1446 private Runnable mForceReenableScreenTask = new Runnable() {
1447 public void run() {
1448 forceReenableScreen();
1449 }
1450 };
1451
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001452 private int setScreenStateLocked(boolean on) {
1453 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001454 if (err == 0) {
1455 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1456 if (mUseSoftwareAutoBrightness) {
1457 enableLightSensor(on);
1458 if (!on) {
1459 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001460 mButtonLight.turnOff();
1461 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001462 // clear current value so we will update based on the new conditions
1463 // when the sensor is reenabled.
1464 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001465 // reset our highest light sensor value when the screen turns off
1466 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001467 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001468 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001469 }
1470 return err;
1471 }
1472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 private void setPowerState(int state)
1474 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001475 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
1477
Mike Lockwood435eb642009-12-03 08:40:18 -05001478 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 {
1480 synchronized (mLocks) {
1481 int err;
1482
1483 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001484 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001486 + " noChangeLights=" + noChangeLights
1487 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 }
1489
1490 if (noChangeLights) {
1491 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1492 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001493 if (mProximitySensorActive) {
1494 // don't turn on the screen when the proximity sensor lock is held
1495 newState = (newState & ~SCREEN_BRIGHT);
1496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497
1498 if (batteryIsLow()) {
1499 newState |= BATTERY_LOW_BIT;
1500 } else {
1501 newState &= ~BATTERY_LOW_BIT;
1502 }
1503 if (newState == mPowerState) {
1504 return;
1505 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001506
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001507 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 newState |= ALL_BRIGHT;
1509 }
1510
1511 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1512 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1513
Mike Lockwood51b84492009-11-16 21:51:18 -05001514 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001515 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001517 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001519 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001521 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001523 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001525 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1527 }
1528
1529 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001530 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1532 }
1533
1534 if (oldScreenOn != newScreenOn) {
1535 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001536 // When the user presses the power button, we need to always send out the
1537 // notification that it's going to sleep so the keyguard goes on. But
1538 // we can't do that until the screen fades out, so we don't show the keyguard
1539 // too early.
1540 if (mStillNeedSleepNotification) {
1541 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1542 }
1543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 // Turn on the screen UNLESS there was a prior
1545 // preventScreenOn(true) request. (Note that the lifetime
1546 // of a single preventScreenOn() request is limited to 5
1547 // seconds to prevent a buggy app from disabling the
1548 // screen forever; see forceReenableScreen().)
1549 boolean reallyTurnScreenOn = true;
1550 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001551 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 + mPreventScreenOn);
1553 }
1554
1555 if (mPreventScreenOn) {
1556 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001557 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 }
1559 reallyTurnScreenOn = false;
1560 }
1561 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001562 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 long identity = Binder.clearCallingIdentity();
1564 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001565 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 mBatteryStats.noteScreenOn();
1567 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001568 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 } finally {
1570 Binder.restoreCallingIdentity(identity);
1571 }
1572 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001573 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 // But continue as if we really did turn the screen on...
1575 err = 0;
1576 }
1577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 mLastTouchDown = 0;
1579 mTotalTouchDownTime = 0;
1580 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001581 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 mTotalTouchDownTime, mTouchCycles);
1583 if (err == 0) {
1584 mPowerState |= SCREEN_ON_BIT;
1585 sendNotificationLocked(true, -1);
1586 }
1587 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001588 // cancel light sensor task
1589 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 mScreenOffTime = SystemClock.elapsedRealtime();
1591 long identity = Binder.clearCallingIdentity();
1592 try {
1593 mBatteryStats.noteScreenOff();
1594 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001595 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 } finally {
1597 Binder.restoreCallingIdentity(identity);
1598 }
1599 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001600 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001602 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 err = 0;
1605 mLastTouchDown = 0;
1606 }
1607 }
1608 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001609
1610 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001613
1614 private void updateNativePowerStateLocked() {
1615 nativeSetPowerState(
1616 (mPowerState & SCREEN_ON_BIT) != 0,
1617 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001619
Mike Lockwood435eb642009-12-03 08:40:18 -05001620 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001622 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001624 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001626 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001628 mScreenOffReason = reason;
1629 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 }
1631 return err;
1632 }
1633
1634 private boolean batteryIsLow() {
1635 return (!mIsPowered &&
1636 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1637 }
1638
The Android Open Source Project10592532009-03-18 17:39:46 -07001639 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001640 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001641 newState = applyButtonState(newState);
1642 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001643 final int realDifference = (newState ^ oldState);
1644 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001646 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 int offMask = 0;
1650 int dimMask = 0;
1651 int onMask = 0;
1652
1653 int preferredBrightness = getPreferredBrightness();
1654 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1657 if (ANIMATE_KEYBOARD_LIGHTS) {
1658 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1659 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001660 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001661 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001663 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001664 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1665 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 }
1667 startAnimation = true;
1668 } else {
1669 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001670 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001672 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 }
1674 }
1675 }
1676
1677 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1678 if (ANIMATE_BUTTON_LIGHTS) {
1679 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1680 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001681 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001682 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001684 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001685 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1686 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
1688 startAnimation = true;
1689 } else {
1690 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001691 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001693 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
1695 }
1696 }
1697
1698 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1699 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001700 int nominalCurrentValue = -1;
1701 // If there was an actual difference in the light state, then
1702 // figure out the "ideal" current value based on the previous
1703 // state. Otherwise, this is a change due to the brightness
1704 // override, so we want to animate from whatever the current
1705 // value is.
1706 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1707 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1708 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1709 nominalCurrentValue = preferredBrightness;
1710 break;
1711 case SCREEN_ON_BIT:
1712 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1713 break;
1714 case 0:
1715 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1716 break;
1717 case SCREEN_BRIGHT_BIT:
1718 default:
1719 // not possible
1720 nominalCurrentValue = (int)mScreenBrightness.curValue;
1721 break;
1722 }
Joe Onorato128e7292009-03-24 18:41:31 -07001723 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001724 int brightness = preferredBrightness;
1725 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1727 // dim or turn off backlight, depending on if the screen is on
1728 // the scale is because the brightness ramp isn't linear and this biases
1729 // it so the later parts take longer.
1730 final float scale = 1.5f;
1731 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1732 if (ratio > 1.0f) ratio = 1.0f;
1733 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1735 // was bright
1736 steps = ANIM_STEPS;
1737 } else {
1738 // was dim
1739 steps = (int)(ANIM_STEPS*ratio*scale);
1740 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001741 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 if ((oldState & SCREEN_ON_BIT) != 0) {
1744 // was bright
1745 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1746 } else {
1747 // was dim
1748 steps = (int)(ANIM_STEPS*ratio);
1749 }
1750 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1751 // If the "stay on while plugged in" option is
1752 // turned on, then the screen will often not
1753 // automatically turn off while plugged in. To
1754 // still have a sense of when it is inactive, we
1755 // will then count going dim as turning off.
1756 mScreenOffTime = SystemClock.elapsedRealtime();
1757 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001758 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001761 long identity = Binder.clearCallingIdentity();
1762 try {
1763 mBatteryStats.noteScreenBrightness(brightness);
1764 } catch (RemoteException e) {
1765 // Nothing interesting to do.
1766 } finally {
1767 Binder.restoreCallingIdentity(identity);
1768 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001769 if (mScreenBrightness.setTargetLocked(brightness,
1770 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1771 startAnimation = true;
1772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 } else {
1774 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1775 // dim or turn off backlight, depending on if the screen is on
1776 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001777 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001779 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 }
1781 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001782 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 }
1784 }
1785 }
1786
1787 if (startAnimation) {
1788 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001789 Slog.i(TAG, "Scheduling light animator!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 }
1791 mHandler.removeCallbacks(mLightAnimator);
1792 mHandler.post(mLightAnimator);
1793 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001796 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001797 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 }
1799 if (dimMask != 0) {
1800 int brightness = Power.BRIGHTNESS_DIM;
1801 if ((newState & BATTERY_LOW_BIT) != 0 &&
1802 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1803 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1804 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001805 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001806 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 }
1808 if (onMask != 0) {
1809 int brightness = getPreferredBrightness();
1810 if ((newState & BATTERY_LOW_BIT) != 0 &&
1811 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1812 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1813 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001814 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001815 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818
The Android Open Source Project10592532009-03-18 17:39:46 -07001819 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001820 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001821 ? LightsService.BRIGHTNESS_MODE_SENSOR
1822 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001823 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001824 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001825 }
1826 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001827 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001828 }
1829 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001830 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 }
1833
1834 class BrightnessState {
1835 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 boolean initialized;
1838 int targetValue;
1839 float curValue;
1840 float delta;
1841 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 BrightnessState(int m) {
1844 mask = m;
1845 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 public void dump(PrintWriter pw, String prefix) {
1848 pw.println(prefix + "animating=" + animating
1849 + " targetValue=" + targetValue
1850 + " curValue=" + curValue
1851 + " delta=" + delta);
1852 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001853
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001854 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001855 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 if (!initialized) {
1857 initialized = true;
1858 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001859 } else if (targetValue == target) {
1860 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 }
1862 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001863 delta = (targetValue -
1864 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1865 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001867 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato8a9b2202010-02-26 18:56:32 -08001868 Slog.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001869 + " target=" + targetValue + " delta=" + delta
1870 + " nominalCurrentValue=" + nominalCurrentValue
1871 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 }
1873 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001874 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 boolean stepLocked() {
1878 if (!animating) return false;
1879 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001880 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 + " target=" + targetValue + " delta=" + delta);
1882 }
1883 curValue += delta;
1884 int curIntValue = (int)curValue;
1885 boolean more = true;
1886 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001887 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 more = false;
1889 } else if (delta > 0) {
1890 if (curIntValue >= targetValue) {
1891 curValue = curIntValue = targetValue;
1892 more = false;
1893 }
1894 } else {
1895 if (curIntValue <= targetValue) {
1896 curValue = curIntValue = targetValue;
1897 more = false;
1898 }
1899 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001900 //Slog.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001901 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 animating = more;
1903 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001904 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001905 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 }
1907 }
1908 return more;
1909 }
1910 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 private class LightAnimator implements Runnable {
1913 public void run() {
1914 synchronized (mLocks) {
1915 long now = SystemClock.uptimeMillis();
1916 boolean more = mScreenBrightness.stepLocked();
1917 if (mKeyboardBrightness.stepLocked()) {
1918 more = true;
1919 }
1920 if (mButtonBrightness.stepLocked()) {
1921 more = true;
1922 }
1923 if (more) {
1924 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1925 }
1926 }
1927 }
1928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 private int getPreferredBrightness() {
1931 try {
1932 if (mScreenBrightnessOverride >= 0) {
1933 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001934 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001935 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001936 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 }
1938 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1939 SCREEN_BRIGHTNESS);
1940 // Don't let applications turn the screen all the way off
1941 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1942 } catch (SettingNotFoundException snfe) {
1943 return Power.BRIGHTNESS_ON;
1944 }
1945 }
1946
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001947 private int applyButtonState(int state) {
1948 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04001949 if ((state & BATTERY_LOW_BIT) != 0) {
1950 // do not override brightness if the battery is low
1951 return state;
1952 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001953 if (mButtonBrightnessOverride >= 0) {
1954 brightness = mButtonBrightnessOverride;
1955 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
1956 brightness = mLightSensorButtonBrightness;
1957 }
1958 if (brightness > 0) {
1959 return state | BUTTON_BRIGHT_BIT;
1960 } else if (brightness == 0) {
1961 return state & ~BUTTON_BRIGHT_BIT;
1962 } else {
1963 return state;
1964 }
1965 }
1966
1967 private int applyKeyboardState(int state) {
1968 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04001969 if ((state & BATTERY_LOW_BIT) != 0) {
1970 // do not override brightness if the battery is low
1971 return state;
1972 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001973 if (!mKeyboardVisible) {
1974 brightness = 0;
1975 } else if (mButtonBrightnessOverride >= 0) {
1976 brightness = mButtonBrightnessOverride;
1977 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
1978 brightness = mLightSensorKeyboardBrightness;
1979 }
1980 if (brightness > 0) {
1981 return state | KEYBOARD_BRIGHT_BIT;
1982 } else if (brightness == 0) {
1983 return state & ~KEYBOARD_BRIGHT_BIT;
1984 } else {
1985 return state;
1986 }
1987 }
1988
Charles Mendis322591c2009-10-29 11:06:59 -07001989 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 synchronized (mLocks) {
1991 return (mPowerState & SCREEN_ON_BIT) != 0;
1992 }
1993 }
1994
Charles Mendis322591c2009-10-29 11:06:59 -07001995 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 synchronized (mLocks) {
1997 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1998 }
1999 }
2000
Mike Lockwood497087e32009-11-08 18:33:03 -05002001 private boolean isScreenTurningOffLocked() {
2002 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2003 }
2004
Mike Lockwood200b30b2009-09-20 00:23:59 -04002005 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002006 if (isScreenTurningOffLocked()) {
2007 // cancel animation so userActivity will succeed
2008 mScreenBrightness.animating = false;
2009 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002010 boolean savedActivityAllowed = mUserActivityAllowed;
2011 mUserActivityAllowed = true;
2012 userActivity(SystemClock.uptimeMillis(), false);
2013 mUserActivityAllowed = savedActivityAllowed;
2014 }
2015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2017 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002018 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 }
2020
2021 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002022 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 }
2024
2025 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002026 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 }
2028
2029 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002030 userActivity(time, -1, noChangeLights, eventType, force);
2031 }
2032
2033 /*
2034 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2035 * on with user activity. Don't use this function.
2036 */
2037 public void clearUserActivityTimeout(long now, long timeout) {
2038 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2039 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2040 userActivity(now, timeout, false, OTHER_EVENT, false);
2041 }
2042
2043 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2044 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2046
2047 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002048 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002050 Slog.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 }
2052 return;
2053 }
2054
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002055 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
2056 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
2057 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
2058 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002059 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002060 }
2061 return;
2062 }
2063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 if (false) {
2065 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002066 Slog.d(TAG, "userActivity !!!");//, new RuntimeException());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002068 Slog.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 }
2070 }
2071
2072 synchronized (mLocks) {
2073 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002074 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 + " mUserActivityAllowed=" + mUserActivityAllowed
2076 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002077 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2078 + " mProximitySensorActive=" + mProximitySensorActive
2079 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 }
Mike Lockwood05067122009-10-27 23:07:25 -04002081 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002082 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002083 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002084 return;
2085 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002086 // Disable proximity sensor if if user presses power key while we are in the
2087 // "waiting for proximity sensor to go negative" state.
2088 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2089 mProximitySensorActive = false;
2090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 if (mLastEventTime <= time || force) {
2092 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002093 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002094 // Only turn on button backlights if a button was pressed
2095 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002096 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2098 } else {
2099 // don't clear button/keyboard backlights when the screen is touched.
2100 mUserState |= SCREEN_BRIGHT;
2101 }
2102
Dianne Hackborn617f8772009-03-31 15:04:46 -07002103 int uid = Binder.getCallingUid();
2104 long ident = Binder.clearCallingIdentity();
2105 try {
2106 mBatteryStats.noteUserActivity(uid, eventType);
2107 } catch (RemoteException e) {
2108 // Ignore
2109 } finally {
2110 Binder.restoreCallingIdentity(ident);
2111 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002112
Michael Chane96440f2009-05-06 10:27:36 -07002113 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002114 setPowerState(mUserState | mWakeLockState, noChangeLights,
2115 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002116 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 }
2118 }
2119 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002120
2121 if (mPolicy != null) {
2122 mPolicy.userActivity();
2123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 }
2125
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002126 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2127 try {
2128 int i;
2129 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2130 if (sensorValue < mAutoBrightnessLevels[i]) {
2131 break;
2132 }
2133 }
2134 return values[i];
2135 } catch (Exception e) {
2136 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002137 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002138 return 255;
2139 }
2140 }
2141
Mike Lockwood20f87d72009-11-05 16:08:51 -05002142 private Runnable mProximityTask = new Runnable() {
2143 public void run() {
2144 synchronized (mLocks) {
2145 if (mProximityPendingValue != -1) {
2146 proximityChangedLocked(mProximityPendingValue == 1);
2147 mProximityPendingValue = -1;
2148 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002149 if (mProximityPartialLock.isHeld()) {
2150 mProximityPartialLock.release();
2151 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002152 }
2153 }
2154 };
2155
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002156 private Runnable mAutoBrightnessTask = new Runnable() {
2157 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002158 synchronized (mLocks) {
2159 int value = (int)mLightSensorPendingValue;
2160 if (value >= 0) {
2161 mLightSensorPendingValue = -1;
2162 lightSensorChangedLocked(value);
2163 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002164 }
2165 }
2166 };
2167
Mike Lockwoodb2865412010-02-02 22:40:33 -05002168 private void dockStateChanged(int state) {
2169 synchronized (mLocks) {
2170 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2171 if (mIsDocked) {
2172 mHighestLightSensorValue = -1;
2173 }
2174 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2175 // force lights recalculation
2176 int value = (int)mLightSensorValue;
2177 mLightSensorValue = -1;
2178 lightSensorChangedLocked(value);
2179 }
2180 }
2181 }
2182
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002183 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002184 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002185 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002186 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002187
Mike Lockwoodb2865412010-02-02 22:40:33 -05002188 // do not allow light sensor value to decrease
2189 if (mHighestLightSensorValue < value) {
2190 mHighestLightSensorValue = value;
2191 }
2192
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002193 if (mLightSensorValue != value) {
2194 mLightSensorValue = value;
2195 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002196 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2197 // we only do this if we are undocked, since lighting should be stable when
2198 // stationary in a dock.
2199 int lcdValue = getAutoBrightnessValue(
2200 (mIsDocked ? value : mHighestLightSensorValue),
2201 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002202 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002203 int keyboardValue;
2204 if (mKeyboardVisible) {
2205 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2206 } else {
2207 keyboardValue = 0;
2208 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002209 mLightSensorScreenBrightness = lcdValue;
2210 mLightSensorButtonBrightness = buttonValue;
2211 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002212
2213 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002214 Slog.d(TAG, "lcdValue " + lcdValue);
2215 Slog.d(TAG, "buttonValue " + buttonValue);
2216 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002217 }
2218
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002219 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002220 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002221 if (ANIMATE_SCREEN_LIGHTS) {
2222 if (mScreenBrightness.setTargetLocked(lcdValue,
2223 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2224 (int)mScreenBrightness.curValue)) {
2225 startAnimation = true;
2226 }
2227 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002228 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002229 ? LightsService.BRIGHTNESS_MODE_SENSOR
2230 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002231 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002232 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002233 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002234 if (mButtonBrightnessOverride < 0) {
2235 if (ANIMATE_BUTTON_LIGHTS) {
2236 if (mButtonBrightness.setTargetLocked(buttonValue,
2237 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2238 (int)mButtonBrightness.curValue)) {
2239 startAnimation = true;
2240 }
2241 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002242 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002243 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002244 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002245 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2246 if (ANIMATE_KEYBOARD_LIGHTS) {
2247 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2248 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2249 (int)mKeyboardBrightness.curValue)) {
2250 startAnimation = true;
2251 }
2252 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002253 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002254 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002255 }
2256 if (startAnimation) {
2257 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002258 Slog.i(TAG, "lightSensorChangedLocked scheduling light animator");
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002259 }
2260 mHandler.removeCallbacks(mLightAnimator);
2261 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002262 }
2263 }
2264 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002265 }
2266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 /**
2268 * The user requested that we go to sleep (probably with the power button).
2269 * This overrides all wake locks that are held.
2270 */
2271 public void goToSleep(long time)
2272 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002273 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2274 }
2275
2276 /**
2277 * The user requested that we go to sleep (probably with the power button).
2278 * This overrides all wake locks that are held.
2279 */
2280 public void goToSleepWithReason(long time, int reason)
2281 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2283 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002284 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 }
2286 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002289 * Reboot the device immediately, passing 'reason' (may be null)
2290 * to the underlying __reboot system call. Should not return.
2291 */
2292 public void reboot(String reason)
2293 {
2294 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002295
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002296 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2297 throw new IllegalStateException("Too early to call reboot()");
2298 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002299
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002300 final String finalReason = reason;
2301 Runnable runnable = new Runnable() {
2302 public void run() {
2303 synchronized (this) {
2304 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002305 }
2306
San Mehat1e512792010-01-07 10:40:29 -08002307 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002308 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002309 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002310 mHandler.post(runnable);
2311
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002312 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002313 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002314 while (true) {
2315 try {
2316 runnable.wait();
2317 } catch (InterruptedException e) {
2318 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002319 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002320 }
2321 }
2322
Dan Egnor60d87622009-12-16 16:32:58 -08002323 /**
2324 * Crash the runtime (causing a complete restart of the Android framework).
2325 * Requires REBOOT permission. Mostly for testing. Should not return.
2326 */
2327 public void crash(final String message)
2328 {
2329 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2330 Thread t = new Thread("PowerManagerService.crash()") {
2331 public void run() { throw new RuntimeException(message); }
2332 };
2333 try {
2334 t.start();
2335 t.join();
2336 } catch (InterruptedException e) {
2337 Log.wtf(TAG, e);
2338 }
2339 }
2340
Mike Lockwood435eb642009-12-03 08:40:18 -05002341 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342
2343 if (mLastEventTime <= time) {
2344 mLastEventTime = time;
2345 // cancel all of the wake locks
2346 mWakeLockState = SCREEN_OFF;
2347 int N = mLocks.size();
2348 int numCleared = 0;
2349 for (int i=0; i<N; i++) {
2350 WakeLock wl = mLocks.get(i);
2351 if (isScreenLock(wl.flags)) {
2352 mLocks.get(i).activated = false;
2353 numCleared++;
2354 }
2355 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002356 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002357 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002359 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 cancelTimerLocked();
2361 }
2362 }
2363
2364 public long timeSinceScreenOn() {
2365 synchronized (mLocks) {
2366 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2367 return 0;
2368 }
2369 return SystemClock.elapsedRealtime() - mScreenOffTime;
2370 }
2371 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002374 synchronized (mLocks) {
2375 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002376 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002377 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002378 if (mKeyboardVisible != visible) {
2379 mKeyboardVisible = visible;
2380 // don't signal user activity if the screen is off; other code
2381 // will take care of turning on due to a true change to the lid
2382 // switch and synchronized with the lock screen.
2383 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002384 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002385 // force recompute of backlight values
2386 if (mLightSensorValue >= 0) {
2387 int value = (int)mLightSensorValue;
2388 mLightSensorValue = -1;
2389 lightSensorChangedLocked(value);
2390 }
2391 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002392 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2393 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002394 }
2395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 }
2397
2398 /**
2399 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002400 * When disabling user activity we also reset user power state so the keyguard can reset its
2401 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 */
2403 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002404 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002405 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 synchronized (mLocks) {
2408 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002409 if (!enabled) {
2410 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2411 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 }
2414 }
2415
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002416 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002417 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002418 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002419 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002420 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002421 // force recompute of backlight values
2422 if (mLightSensorValue >= 0) {
2423 int value = (int)mLightSensorValue;
2424 mLightSensorValue = -1;
2425 lightSensorChangedLocked(value);
2426 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002427 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002428 }
2429 }
2430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 /** Sets the screen off timeouts:
2432 * mKeylightDelay
2433 * mDimDelay
2434 * mScreenOffDelay
2435 * */
2436 private void setScreenOffTimeoutsLocked() {
2437 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002438 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 mDimDelay = -1;
2440 mScreenOffDelay = 0;
2441 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2442 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2443 mDimDelay = -1;
2444 mScreenOffDelay = 0;
2445 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002446 int totalDelay = mScreenOffTimeoutSetting;
2447 if (totalDelay > mMaximumScreenOffTimeout) {
2448 totalDelay = mMaximumScreenOffTimeout;
2449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2451 if (totalDelay < 0) {
2452 mScreenOffDelay = Integer.MAX_VALUE;
2453 } else if (mKeylightDelay < totalDelay) {
2454 // subtract the time that the keylight delay. This will give us the
2455 // remainder of the time that we need to sleep to get the accurate
2456 // screen off timeout.
2457 mScreenOffDelay = totalDelay - mKeylightDelay;
2458 } else {
2459 mScreenOffDelay = 0;
2460 }
2461 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2462 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2463 mScreenOffDelay = LONG_DIM_TIME;
2464 } else {
2465 mDimDelay = -1;
2466 }
2467 }
2468 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002469 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2471 + " mDimScreen=" + mDimScreen);
2472 }
2473 }
2474
2475 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002476 * Refreshes cached secure settings. Called once on startup, and
2477 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 */
Doug Zongker43866e02010-01-07 12:09:54 -08002479 private void updateSettingsValues() {
2480 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002482 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002484 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 }
2486
2487 private class LockList extends ArrayList<WakeLock>
2488 {
2489 void addLock(WakeLock wl)
2490 {
2491 int index = getIndex(wl.binder);
2492 if (index < 0) {
2493 this.add(wl);
2494 }
2495 }
2496
2497 WakeLock removeLock(IBinder binder)
2498 {
2499 int index = getIndex(binder);
2500 if (index >= 0) {
2501 return this.remove(index);
2502 } else {
2503 return null;
2504 }
2505 }
2506
2507 int getIndex(IBinder binder)
2508 {
2509 int N = this.size();
2510 for (int i=0; i<N; i++) {
2511 if (this.get(i).binder == binder) {
2512 return i;
2513 }
2514 }
2515 return -1;
2516 }
2517
2518 int gatherState()
2519 {
2520 int result = 0;
2521 int N = this.size();
2522 for (int i=0; i<N; i++) {
2523 WakeLock wl = this.get(i);
2524 if (wl.activated) {
2525 if (isScreenLock(wl.flags)) {
2526 result |= wl.minState;
2527 }
2528 }
2529 }
2530 return result;
2531 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002532
Michael Chane96440f2009-05-06 10:27:36 -07002533 int reactivateScreenLocksLocked()
2534 {
2535 int result = 0;
2536 int N = this.size();
2537 for (int i=0; i<N; i++) {
2538 WakeLock wl = this.get(i);
2539 if (isScreenLock(wl.flags)) {
2540 wl.activated = true;
2541 result |= wl.minState;
2542 }
2543 }
2544 return result;
2545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 }
2547
2548 void setPolicy(WindowManagerPolicy p) {
2549 synchronized (mLocks) {
2550 mPolicy = p;
2551 mLocks.notifyAll();
2552 }
2553 }
2554
2555 WindowManagerPolicy getPolicyLocked() {
2556 while (mPolicy == null || !mDoneBooting) {
2557 try {
2558 mLocks.wait();
2559 } catch (InterruptedException e) {
2560 // Ignore
2561 }
2562 }
2563 return mPolicy;
2564 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002567 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2568 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2569 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002570 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002571 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002572 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002573 }
2574
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002575 // wait until sensors are enabled before turning on screen.
2576 // some devices will not activate the light sensor properly on boot
2577 // unless we do this.
2578 if (mUseSoftwareAutoBrightness) {
2579 // turn the screen on
2580 setPowerState(SCREEN_BRIGHT);
2581 } else {
2582 // turn everything on
2583 setPowerState(ALL_BRIGHT);
2584 }
2585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002587 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002589
Dianne Hackborn617f8772009-03-31 15:04:46 -07002590 long identity = Binder.clearCallingIdentity();
2591 try {
2592 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2593 mBatteryStats.noteScreenOn();
2594 } catch (RemoteException e) {
2595 // Nothing interesting to do.
2596 } finally {
2597 Binder.restoreCallingIdentity(identity);
2598 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002599 }
2600 }
2601
2602 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002603 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002604 synchronized (mLocks) {
2605 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2607 updateWakeLockLocked();
2608 mLocks.notifyAll();
2609 }
2610 }
2611
2612 public void monitor() {
2613 synchronized (mLocks) { }
2614 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002615
2616 public int getSupportedWakeLockFlags() {
2617 int result = PowerManager.PARTIAL_WAKE_LOCK
2618 | PowerManager.FULL_WAKE_LOCK
2619 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2620
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002621 if (mProximitySensor != null) {
2622 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2623 }
2624
2625 return result;
2626 }
2627
Mike Lockwood237a2992009-09-15 14:42:16 -04002628 public void setBacklightBrightness(int brightness) {
2629 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2630 // Don't let applications turn the screen all the way off
2631 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002632 mLcdLight.setBrightness(brightness);
2633 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2634 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002635 long identity = Binder.clearCallingIdentity();
2636 try {
2637 mBatteryStats.noteScreenBrightness(brightness);
2638 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002639 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
Mike Lockwood237a2992009-09-15 14:42:16 -04002640 } finally {
2641 Binder.restoreCallingIdentity(identity);
2642 }
2643
2644 // update our animation state
2645 if (ANIMATE_SCREEN_LIGHTS) {
2646 mScreenBrightness.curValue = brightness;
2647 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002648 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002649 }
2650 if (ANIMATE_KEYBOARD_LIGHTS) {
2651 mKeyboardBrightness.curValue = brightness;
2652 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002653 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002654 }
2655 if (ANIMATE_BUTTON_LIGHTS) {
2656 mButtonBrightness.curValue = brightness;
2657 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002658 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002659 }
2660 }
2661
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002662 public void setAttentionLight(boolean on, int color) {
2663 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002664 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002665 }
2666
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002667 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002668 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002669 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002670 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002671 if (!mProximitySensorEnabled) {
2672 // clear calling identity so sensor manager battery stats are accurate
2673 long identity = Binder.clearCallingIdentity();
2674 try {
2675 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2676 SensorManager.SENSOR_DELAY_NORMAL);
2677 mProximitySensorEnabled = true;
2678 } finally {
2679 Binder.restoreCallingIdentity(identity);
2680 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002681 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002682 }
2683
2684 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002685 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002686 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002687 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002688 if (mProximitySensorEnabled) {
2689 // clear calling identity so sensor manager battery stats are accurate
2690 long identity = Binder.clearCallingIdentity();
2691 try {
2692 mSensorManager.unregisterListener(mProximityListener);
2693 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002694 if (mProximityPartialLock.isHeld()) {
2695 mProximityPartialLock.release();
2696 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002697 mProximitySensorEnabled = false;
2698 } finally {
2699 Binder.restoreCallingIdentity(identity);
2700 }
2701 if (mProximitySensorActive) {
2702 mProximitySensorActive = false;
2703 forceUserActivityLocked();
2704 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002705 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002706 }
2707
Mike Lockwood20f87d72009-11-05 16:08:51 -05002708 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002709 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002710 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002711 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002712 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002713 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002714 return;
2715 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002716 if (active) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002717 goToSleepLocked(SystemClock.uptimeMillis(),
2718 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002719 mProximitySensorActive = true;
2720 } else {
2721 // proximity sensor negative events trigger as user activity.
2722 // temporarily set mUserActivityAllowed to true so this will work
2723 // even when the keyguard is on.
2724 mProximitySensorActive = false;
2725 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002726
2727 if (mProximityWakeLockCount == 0) {
2728 // disable sensor if we have no listeners left after proximity negative
2729 disableProximityLockLocked();
2730 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002731 }
2732 }
2733
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002734 private void enableLightSensor(boolean enable) {
2735 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002736 Slog.d(TAG, "enableLightSensor " + enable);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002737 }
2738 if (mSensorManager != null && mLightSensorEnabled != enable) {
2739 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002740 // clear calling identity so sensor manager battery stats are accurate
2741 long identity = Binder.clearCallingIdentity();
2742 try {
2743 if (enable) {
2744 mSensorManager.registerListener(mLightListener, mLightSensor,
2745 SensorManager.SENSOR_DELAY_NORMAL);
2746 } else {
2747 mSensorManager.unregisterListener(mLightListener);
2748 mHandler.removeCallbacks(mAutoBrightnessTask);
2749 }
2750 } finally {
2751 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002752 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002753 }
2754 }
2755
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002756 SensorEventListener mProximityListener = new SensorEventListener() {
2757 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002758 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002759 synchronized (mLocks) {
2760 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002761 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2762 mLastProximityEventTime = milliseconds;
2763 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002764 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002765
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002766 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002767 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2768 distance < mProximitySensor.getMaximumRange());
2769
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002770 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002771 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002772 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002773 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2774 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2775 mProximityPendingValue = (active ? 1 : 0);
2776 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002777 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002778 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002779 // process the value immediately
2780 mProximityPendingValue = -1;
2781 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002782 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002783
2784 // update mProximityPartialLock state
2785 boolean held = mProximityPartialLock.isHeld();
2786 if (!held && proximityTaskQueued) {
2787 // hold wakelock until mProximityTask runs
2788 mProximityPartialLock.acquire();
2789 } else if (held && !proximityTaskQueued) {
2790 mProximityPartialLock.release();
2791 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002792 }
2793 }
2794
2795 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2796 // ignore
2797 }
2798 };
2799
2800 SensorEventListener mLightListener = new SensorEventListener() {
2801 public void onSensorChanged(SensorEvent event) {
2802 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002803 // ignore light sensor while screen is turning off
2804 if (isScreenTurningOffLocked()) {
2805 return;
2806 }
2807
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002808 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002809 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002810 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002811 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002812 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002813 mHandler.removeCallbacks(mAutoBrightnessTask);
2814 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002815 if (mLightSensorValue == -1 ||
2816 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2817 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002818 lightSensorChangedLocked(value);
2819 } else {
2820 // delay processing to debounce the sensor
2821 mLightSensorPendingValue = value;
2822 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2823 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002824 } else {
2825 mLightSensorPendingValue = -1;
2826 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002827 }
2828 }
2829
2830 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2831 // ignore
2832 }
2833 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834}