blob: 2e32e60233217b298a7a580d95b80a97614aa1e4 [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.
Joe Onorato797e6882010-08-26 14:46:01 -04001046 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1047 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001048 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001049 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001050 long when = 0;
1051 if (timeoutOverride <= 0) {
1052 switch (nextState)
1053 {
1054 case SCREEN_BRIGHT:
1055 when = now + mKeylightDelay;
1056 break;
1057 case SCREEN_DIM:
1058 if (mDimDelay >= 0) {
1059 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001060 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001061 } else {
1062 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1063 }
1064 case SCREEN_OFF:
1065 synchronized (mLocks) {
1066 when = now + mScreenOffDelay;
1067 }
1068 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001069 default:
1070 when = now;
1071 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001073 } else {
1074 override: {
1075 if (timeoutOverride <= mScreenOffDelay) {
1076 when = now + timeoutOverride;
1077 nextState = SCREEN_OFF;
1078 break override;
1079 }
1080 timeoutOverride -= mScreenOffDelay;
1081
1082 if (mDimDelay >= 0) {
1083 if (timeoutOverride <= mDimDelay) {
1084 when = now + timeoutOverride;
1085 nextState = SCREEN_DIM;
1086 break override;
1087 }
1088 timeoutOverride -= mDimDelay;
1089 }
1090
1091 when = now + timeoutOverride;
1092 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001094 }
1095 if (mSpew) {
1096 Slog.d(TAG, "setTimeoutLocked now=" + now
1097 + " timeoutOverride=" + timeoutOverride
1098 + " nextState=" + nextState + " when=" + when);
1099 }
Joe Onorato797e6882010-08-26 14:46:01 -04001100
1101 mHandler.removeCallbacks(mTimeoutTask);
1102 mTimeoutTask.nextState = nextState;
1103 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1104 ? (originalTimeoutOverride - timeoutOverride)
1105 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001106 mHandler.postAtTime(mTimeoutTask, when);
1107 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 }
1110 }
1111
1112 private void cancelTimerLocked()
1113 {
1114 mHandler.removeCallbacks(mTimeoutTask);
1115 mTimeoutTask.nextState = -1;
1116 }
1117
1118 private class TimeoutTask implements Runnable
1119 {
1120 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001121 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 public void run()
1123 {
1124 synchronized (mLocks) {
1125 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001126 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 }
1128
1129 if (nextState == -1) {
1130 return;
1131 }
1132
1133 mUserState = this.nextState;
1134 setPowerState(this.nextState | mWakeLockState);
1135
1136 long now = SystemClock.uptimeMillis();
1137
1138 switch (this.nextState)
1139 {
1140 case SCREEN_BRIGHT:
1141 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001142 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 break;
1144 }
1145 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001146 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 break;
1148 }
1149 }
1150 }
1151 }
1152
1153 private void sendNotificationLocked(boolean on, int why)
1154 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001155 if (!on) {
1156 mStillNeedSleepNotification = false;
1157 }
1158
Joe Onorato128e7292009-03-24 18:41:31 -07001159 // Add to the queue.
1160 int index = 0;
1161 while (mBroadcastQueue[index] != -1) {
1162 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 }
Joe Onorato128e7292009-03-24 18:41:31 -07001164 mBroadcastQueue[index] = on ? 1 : 0;
1165 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166
Joe Onorato128e7292009-03-24 18:41:31 -07001167 // If we added it position 2, then there is a pair that can be stripped.
1168 // If we added it position 1 and we're turning the screen off, we can strip
1169 // the pair and do nothing, because the screen is already off, and therefore
1170 // keyguard has already been enabled.
1171 // However, if we added it at position 1 and we're turning it on, then position
1172 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1173 // on, so have to run the queue then.
1174 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001175 // While we're collapsing them, if it's going off, and the new reason
1176 // is more significant than the first, then use the new one.
1177 if (!on && mBroadcastWhy[0] > why) {
1178 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001179 }
1180 mBroadcastQueue[0] = on ? 1 : 0;
1181 mBroadcastQueue[1] = -1;
1182 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001183 mBroadcastWakeLock.release();
1184 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001185 index = 0;
1186 }
1187 if (index == 1 && !on) {
1188 mBroadcastQueue[0] = -1;
1189 mBroadcastQueue[1] = -1;
1190 index = -1;
1191 // The wake lock was being held, but we're not actually going to do any
1192 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001193 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001195 }
1196
1197 // Now send the message.
1198 if (index >= 0) {
1199 // Acquire the broadcast wake lock before changing the power
1200 // state. It will be release after the broadcast is sent.
1201 // We always increment the ref count for each notification in the queue
1202 // and always decrement when that notification is handled.
1203 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001204 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001205 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 }
1207 }
1208
1209 private Runnable mNotificationTask = new Runnable()
1210 {
1211 public void run()
1212 {
Joe Onorato128e7292009-03-24 18:41:31 -07001213 while (true) {
1214 int value;
1215 int why;
1216 WindowManagerPolicy policy;
1217 synchronized (mLocks) {
1218 value = mBroadcastQueue[0];
1219 why = mBroadcastWhy[0];
1220 for (int i=0; i<2; i++) {
1221 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1222 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1223 }
1224 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 }
Joe Onorato128e7292009-03-24 18:41:31 -07001226 if (value == 1) {
1227 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001228
Joe Onorato128e7292009-03-24 18:41:31 -07001229 policy.screenTurnedOn();
1230 try {
1231 ActivityManagerNative.getDefault().wakingUp();
1232 } catch (RemoteException e) {
1233 // ignore it
1234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235
Joe Onorato128e7292009-03-24 18:41:31 -07001236 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001237 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001238 }
1239 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1240 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1241 mScreenOnBroadcastDone, mHandler, 0, null, null);
1242 } else {
1243 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001244 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001245 mBroadcastWakeLock.mCount);
1246 mBroadcastWakeLock.release();
1247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 }
1249 }
Joe Onorato128e7292009-03-24 18:41:31 -07001250 else if (value == 0) {
1251 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001252
Joe Onorato128e7292009-03-24 18:41:31 -07001253 policy.screenTurnedOff(why);
1254 try {
1255 ActivityManagerNative.getDefault().goingToSleep();
1256 } catch (RemoteException e) {
1257 // ignore it.
1258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259
Joe Onorato128e7292009-03-24 18:41:31 -07001260 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1261 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1262 mScreenOffBroadcastDone, mHandler, 0, null, null);
1263 } else {
1264 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001265 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001266 mBroadcastWakeLock.mCount);
1267 mBroadcastWakeLock.release();
1268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 }
1270 }
Joe Onorato128e7292009-03-24 18:41:31 -07001271 else {
1272 // If we're in this case, then this handler is running for a previous
1273 // paired transaction. mBroadcastWakeLock will already have been released.
1274 break;
1275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 }
1277 }
1278 };
1279
1280 long mScreenOnStart;
1281 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1282 public void onReceive(Context context, Intent intent) {
1283 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001284 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1286 mBroadcastWakeLock.release();
1287 }
1288 }
1289 };
1290
1291 long mScreenOffStart;
1292 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1293 public void onReceive(Context context, Intent intent) {
1294 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001295 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1297 mBroadcastWakeLock.release();
1298 }
1299 }
1300 };
1301
1302 void logPointerUpEvent() {
1303 if (LOG_TOUCH_DOWNS) {
1304 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1305 mLastTouchDown = 0;
1306 }
1307 }
1308
1309 void logPointerDownEvent() {
1310 if (LOG_TOUCH_DOWNS) {
1311 // If we are not already timing a down/up sequence
1312 if (mLastTouchDown == 0) {
1313 mLastTouchDown = SystemClock.elapsedRealtime();
1314 mTouchCycles++;
1315 }
1316 }
1317 }
1318
1319 /**
1320 * Prevents the screen from turning on even if it *should* turn on due
1321 * to a subsequent full wake lock being acquired.
1322 * <p>
1323 * This is a temporary hack that allows an activity to "cover up" any
1324 * display glitches that happen during the activity's startup
1325 * sequence. (Specifically, this API was added to work around a
1326 * cosmetic bug in the "incoming call" sequence, where the lock screen
1327 * would flicker briefly before the incoming call UI became visible.)
1328 * TODO: There ought to be a more elegant way of doing this,
1329 * probably by having the PowerManager and ActivityManager
1330 * work together to let apps specify that the screen on/off
1331 * state should be synchronized with the Activity lifecycle.
1332 * <p>
1333 * Note that calling preventScreenOn(true) will NOT turn the screen
1334 * off if it's currently on. (This API only affects *future*
1335 * acquisitions of full wake locks.)
1336 * But calling preventScreenOn(false) WILL turn the screen on if
1337 * it's currently off because of a prior preventScreenOn(true) call.
1338 * <p>
1339 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1340 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1341 * call doesn't occur within 5 seconds, we'll turn the screen back on
1342 * ourselves (and log a warning about it); this prevents a buggy app
1343 * from disabling the screen forever.)
1344 * <p>
1345 * TODO: this feature should really be controlled by a new type of poke
1346 * lock (rather than an IPowerManager call).
1347 */
1348 public void preventScreenOn(boolean prevent) {
1349 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1350
1351 synchronized (mLocks) {
1352 if (prevent) {
1353 // First of all, grab a partial wake lock to
1354 // make sure the CPU stays on during the entire
1355 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1356 mPreventScreenOnPartialLock.acquire();
1357
1358 // Post a forceReenableScreen() call (for 5 seconds in the
1359 // future) to make sure the matching preventScreenOn(false) call
1360 // has happened by then.
1361 mHandler.removeCallbacks(mForceReenableScreenTask);
1362 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1363
1364 // Finally, set the flag that prevents the screen from turning on.
1365 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001366 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 mPreventScreenOn = true;
1368 } else {
1369 // (Re)enable the screen.
1370 mPreventScreenOn = false;
1371
1372 // We're "undoing" a the prior preventScreenOn(true) call, so we
1373 // no longer need the 5-second safeguard.
1374 mHandler.removeCallbacks(mForceReenableScreenTask);
1375
1376 // Forcibly turn on the screen if it's supposed to be on. (This
1377 // handles the case where the screen is currently off because of
1378 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001379 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001381 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1383 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001384 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001386 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
1388 }
1389
1390 // Release the partial wake lock that we held during the
1391 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1392 mPreventScreenOnPartialLock.release();
1393 }
1394 }
1395 }
1396
1397 public void setScreenBrightnessOverride(int brightness) {
1398 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1399
Mike Lockwoodf527c712010-06-10 14:12:33 -04001400 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 synchronized (mLocks) {
1402 if (mScreenBrightnessOverride != brightness) {
1403 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001404 if (isScreenOn()) {
1405 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 }
1408 }
1409 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001410
1411 public void setButtonBrightnessOverride(int brightness) {
1412 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1413
Mike Lockwoodf527c712010-06-10 14:12:33 -04001414 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001415 synchronized (mLocks) {
1416 if (mButtonBrightnessOverride != brightness) {
1417 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001418 if (isScreenOn()) {
1419 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1420 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001421 }
1422 }
1423 }
1424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 /**
1426 * Sanity-check that gets called 5 seconds after any call to
1427 * preventScreenOn(true). This ensures that the original call
1428 * is followed promptly by a call to preventScreenOn(false).
1429 */
1430 private void forceReenableScreen() {
1431 // We shouldn't get here at all if mPreventScreenOn is false, since
1432 // we should have already removed any existing
1433 // mForceReenableScreenTask messages...
1434 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001435 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 return;
1437 }
1438
1439 // Uh oh. It's been 5 seconds since a call to
1440 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1441 // This means the app that called preventScreenOn(true) is either
1442 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1443 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1444 // crashed before doing so.)
1445
1446 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001447 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 + "Forcing the screen back on...");
1449 preventScreenOn(false);
1450 }
1451
1452 private Runnable mForceReenableScreenTask = new Runnable() {
1453 public void run() {
1454 forceReenableScreen();
1455 }
1456 };
1457
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001458 private int setScreenStateLocked(boolean on) {
1459 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001460 if (err == 0) {
1461 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1462 if (mUseSoftwareAutoBrightness) {
1463 enableLightSensor(on);
1464 if (!on) {
1465 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001466 mButtonLight.turnOff();
1467 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001468 // clear current value so we will update based on the new conditions
1469 // when the sensor is reenabled.
1470 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001471 // reset our highest light sensor value when the screen turns off
1472 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001473 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001474 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001475 }
1476 return err;
1477 }
1478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 private void setPowerState(int state)
1480 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001481 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
1483
Mike Lockwood435eb642009-12-03 08:40:18 -05001484 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 {
1486 synchronized (mLocks) {
1487 int err;
1488
1489 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001490 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001492 + " noChangeLights=" + noChangeLights
1493 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
1495
1496 if (noChangeLights) {
1497 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1498 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001499 if (mProximitySensorActive) {
1500 // don't turn on the screen when the proximity sensor lock is held
1501 newState = (newState & ~SCREEN_BRIGHT);
1502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503
1504 if (batteryIsLow()) {
1505 newState |= BATTERY_LOW_BIT;
1506 } else {
1507 newState &= ~BATTERY_LOW_BIT;
1508 }
1509 if (newState == mPowerState) {
1510 return;
1511 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001512
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001513 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 newState |= ALL_BRIGHT;
1515 }
1516
1517 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1518 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1519
Mike Lockwood51b84492009-11-16 21:51:18 -05001520 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001521 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001523 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001525 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001527 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001529 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001531 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1533 }
1534
1535 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001536 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1538 }
1539
1540 if (oldScreenOn != newScreenOn) {
1541 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001542 // When the user presses the power button, we need to always send out the
1543 // notification that it's going to sleep so the keyguard goes on. But
1544 // we can't do that until the screen fades out, so we don't show the keyguard
1545 // too early.
1546 if (mStillNeedSleepNotification) {
1547 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1548 }
1549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 // Turn on the screen UNLESS there was a prior
1551 // preventScreenOn(true) request. (Note that the lifetime
1552 // of a single preventScreenOn() request is limited to 5
1553 // seconds to prevent a buggy app from disabling the
1554 // screen forever; see forceReenableScreen().)
1555 boolean reallyTurnScreenOn = true;
1556 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001557 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 + mPreventScreenOn);
1559 }
1560
1561 if (mPreventScreenOn) {
1562 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001563 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
1565 reallyTurnScreenOn = false;
1566 }
1567 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001568 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 long identity = Binder.clearCallingIdentity();
1570 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001571 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 mBatteryStats.noteScreenOn();
1573 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001574 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 } finally {
1576 Binder.restoreCallingIdentity(identity);
1577 }
1578 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001579 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 // But continue as if we really did turn the screen on...
1581 err = 0;
1582 }
1583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 mLastTouchDown = 0;
1585 mTotalTouchDownTime = 0;
1586 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001587 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 mTotalTouchDownTime, mTouchCycles);
1589 if (err == 0) {
1590 mPowerState |= SCREEN_ON_BIT;
1591 sendNotificationLocked(true, -1);
1592 }
1593 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001594 // cancel light sensor task
1595 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 mScreenOffTime = SystemClock.elapsedRealtime();
1597 long identity = Binder.clearCallingIdentity();
1598 try {
1599 mBatteryStats.noteScreenOff();
1600 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001601 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 } finally {
1603 Binder.restoreCallingIdentity(identity);
1604 }
1605 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001606 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001608 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 err = 0;
1611 mLastTouchDown = 0;
1612 }
1613 }
1614 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001615
1616 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 }
1618 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001619
1620 private void updateNativePowerStateLocked() {
1621 nativeSetPowerState(
1622 (mPowerState & SCREEN_ON_BIT) != 0,
1623 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1624 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001625
Mike Lockwood435eb642009-12-03 08:40:18 -05001626 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001628 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001630 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001632 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001634 mScreenOffReason = reason;
1635 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 }
1637 return err;
1638 }
1639
1640 private boolean batteryIsLow() {
1641 return (!mIsPowered &&
1642 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1643 }
1644
The Android Open Source Project10592532009-03-18 17:39:46 -07001645 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001646 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001647 newState = applyButtonState(newState);
1648 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001649 final int realDifference = (newState ^ oldState);
1650 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001652 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 int offMask = 0;
1656 int dimMask = 0;
1657 int onMask = 0;
1658
1659 int preferredBrightness = getPreferredBrightness();
1660 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1663 if (ANIMATE_KEYBOARD_LIGHTS) {
1664 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1665 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001666 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001667 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001669 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001670 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1671 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
1673 startAnimation = true;
1674 } else {
1675 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001676 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001678 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 }
1680 }
1681 }
1682
1683 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1684 if (ANIMATE_BUTTON_LIGHTS) {
1685 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1686 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001687 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001688 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001690 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001691 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1692 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 }
1694 startAnimation = true;
1695 } else {
1696 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001697 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001699 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 }
1701 }
1702 }
1703
1704 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1705 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001706 int nominalCurrentValue = -1;
1707 // If there was an actual difference in the light state, then
1708 // figure out the "ideal" current value based on the previous
1709 // state. Otherwise, this is a change due to the brightness
1710 // override, so we want to animate from whatever the current
1711 // value is.
1712 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1713 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1714 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1715 nominalCurrentValue = preferredBrightness;
1716 break;
1717 case SCREEN_ON_BIT:
1718 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1719 break;
1720 case 0:
1721 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1722 break;
1723 case SCREEN_BRIGHT_BIT:
1724 default:
1725 // not possible
1726 nominalCurrentValue = (int)mScreenBrightness.curValue;
1727 break;
1728 }
Joe Onorato128e7292009-03-24 18:41:31 -07001729 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001730 int brightness = preferredBrightness;
1731 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1733 // dim or turn off backlight, depending on if the screen is on
1734 // the scale is because the brightness ramp isn't linear and this biases
1735 // it so the later parts take longer.
1736 final float scale = 1.5f;
1737 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1738 if (ratio > 1.0f) ratio = 1.0f;
1739 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1741 // was bright
1742 steps = ANIM_STEPS;
1743 } else {
1744 // was dim
1745 steps = (int)(ANIM_STEPS*ratio*scale);
1746 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001747 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 if ((oldState & SCREEN_ON_BIT) != 0) {
1750 // was bright
1751 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1752 } else {
1753 // was dim
1754 steps = (int)(ANIM_STEPS*ratio);
1755 }
1756 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1757 // If the "stay on while plugged in" option is
1758 // turned on, then the screen will often not
1759 // automatically turn off while plugged in. To
1760 // still have a sense of when it is inactive, we
1761 // will then count going dim as turning off.
1762 mScreenOffTime = SystemClock.elapsedRealtime();
1763 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001764 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001767 long identity = Binder.clearCallingIdentity();
1768 try {
1769 mBatteryStats.noteScreenBrightness(brightness);
1770 } catch (RemoteException e) {
1771 // Nothing interesting to do.
1772 } finally {
1773 Binder.restoreCallingIdentity(identity);
1774 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001775 if (mScreenBrightness.setTargetLocked(brightness,
1776 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1777 startAnimation = true;
1778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 } else {
1780 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1781 // dim or turn off backlight, depending on if the screen is on
1782 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001783 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001785 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 }
1787 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001788 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 }
1790 }
1791 }
1792
1793 if (startAnimation) {
1794 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001795 Slog.i(TAG, "Scheduling light animator!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 }
1797 mHandler.removeCallbacks(mLightAnimator);
1798 mHandler.post(mLightAnimator);
1799 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001802 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001803 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 }
1805 if (dimMask != 0) {
1806 int brightness = Power.BRIGHTNESS_DIM;
1807 if ((newState & BATTERY_LOW_BIT) != 0 &&
1808 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1809 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1810 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001811 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001812 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 }
1814 if (onMask != 0) {
1815 int brightness = getPreferredBrightness();
1816 if ((newState & BATTERY_LOW_BIT) != 0 &&
1817 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1818 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1819 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001820 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001821 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824
The Android Open Source Project10592532009-03-18 17:39:46 -07001825 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001826 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001827 ? LightsService.BRIGHTNESS_MODE_SENSOR
1828 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001829 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001830 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001831 }
1832 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001833 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001834 }
1835 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001836 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 }
1839
1840 class BrightnessState {
1841 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 boolean initialized;
1844 int targetValue;
1845 float curValue;
1846 float delta;
1847 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 BrightnessState(int m) {
1850 mask = m;
1851 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 public void dump(PrintWriter pw, String prefix) {
1854 pw.println(prefix + "animating=" + animating
1855 + " targetValue=" + targetValue
1856 + " curValue=" + curValue
1857 + " delta=" + delta);
1858 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001859
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001860 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001861 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 if (!initialized) {
1863 initialized = true;
1864 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001865 } else if (targetValue == target) {
1866 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 }
1868 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001869 delta = (targetValue -
1870 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1871 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001873 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato8a9b2202010-02-26 18:56:32 -08001874 Slog.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001875 + " target=" + targetValue + " delta=" + delta
1876 + " nominalCurrentValue=" + nominalCurrentValue
1877 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 }
1879 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001880 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 boolean stepLocked() {
1884 if (!animating) return false;
1885 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001886 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 + " target=" + targetValue + " delta=" + delta);
1888 }
1889 curValue += delta;
1890 int curIntValue = (int)curValue;
1891 boolean more = true;
1892 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001893 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 more = false;
1895 } else if (delta > 0) {
1896 if (curIntValue >= targetValue) {
1897 curValue = curIntValue = targetValue;
1898 more = false;
1899 }
1900 } else {
1901 if (curIntValue <= targetValue) {
1902 curValue = curIntValue = targetValue;
1903 more = false;
1904 }
1905 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001906 //Slog.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001907 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 animating = more;
1909 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001910 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001911 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 }
1913 }
1914 return more;
1915 }
1916 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 private class LightAnimator implements Runnable {
1919 public void run() {
1920 synchronized (mLocks) {
1921 long now = SystemClock.uptimeMillis();
1922 boolean more = mScreenBrightness.stepLocked();
1923 if (mKeyboardBrightness.stepLocked()) {
1924 more = true;
1925 }
1926 if (mButtonBrightness.stepLocked()) {
1927 more = true;
1928 }
1929 if (more) {
1930 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1931 }
1932 }
1933 }
1934 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 private int getPreferredBrightness() {
1937 try {
1938 if (mScreenBrightnessOverride >= 0) {
1939 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001940 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001941 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001942 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 }
1944 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1945 SCREEN_BRIGHTNESS);
1946 // Don't let applications turn the screen all the way off
1947 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1948 } catch (SettingNotFoundException snfe) {
1949 return Power.BRIGHTNESS_ON;
1950 }
1951 }
1952
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001953 private int applyButtonState(int state) {
1954 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04001955 if ((state & BATTERY_LOW_BIT) != 0) {
1956 // do not override brightness if the battery is low
1957 return state;
1958 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001959 if (mButtonBrightnessOverride >= 0) {
1960 brightness = mButtonBrightnessOverride;
1961 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
1962 brightness = mLightSensorButtonBrightness;
1963 }
1964 if (brightness > 0) {
1965 return state | BUTTON_BRIGHT_BIT;
1966 } else if (brightness == 0) {
1967 return state & ~BUTTON_BRIGHT_BIT;
1968 } else {
1969 return state;
1970 }
1971 }
1972
1973 private int applyKeyboardState(int state) {
1974 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04001975 if ((state & BATTERY_LOW_BIT) != 0) {
1976 // do not override brightness if the battery is low
1977 return state;
1978 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001979 if (!mKeyboardVisible) {
1980 brightness = 0;
1981 } else if (mButtonBrightnessOverride >= 0) {
1982 brightness = mButtonBrightnessOverride;
1983 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
1984 brightness = mLightSensorKeyboardBrightness;
1985 }
1986 if (brightness > 0) {
1987 return state | KEYBOARD_BRIGHT_BIT;
1988 } else if (brightness == 0) {
1989 return state & ~KEYBOARD_BRIGHT_BIT;
1990 } else {
1991 return state;
1992 }
1993 }
1994
Charles Mendis322591c2009-10-29 11:06:59 -07001995 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 synchronized (mLocks) {
1997 return (mPowerState & SCREEN_ON_BIT) != 0;
1998 }
1999 }
2000
Charles Mendis322591c2009-10-29 11:06:59 -07002001 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 synchronized (mLocks) {
2003 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2004 }
2005 }
2006
Mike Lockwood497087e32009-11-08 18:33:03 -05002007 private boolean isScreenTurningOffLocked() {
2008 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2009 }
2010
Mike Lockwood200b30b2009-09-20 00:23:59 -04002011 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002012 if (isScreenTurningOffLocked()) {
2013 // cancel animation so userActivity will succeed
2014 mScreenBrightness.animating = false;
2015 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002016 boolean savedActivityAllowed = mUserActivityAllowed;
2017 mUserActivityAllowed = true;
2018 userActivity(SystemClock.uptimeMillis(), false);
2019 mUserActivityAllowed = savedActivityAllowed;
2020 }
2021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2023 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002024 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 }
2026
2027 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002028 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 }
2030
2031 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002032 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 }
2034
2035 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002036 userActivity(time, -1, noChangeLights, eventType, force);
2037 }
2038
2039 /*
2040 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2041 * on with user activity. Don't use this function.
2042 */
2043 public void clearUserActivityTimeout(long now, long timeout) {
2044 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2045 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2046 userActivity(now, timeout, false, OTHER_EVENT, false);
2047 }
2048
2049 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2050 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2052
2053 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002054 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002056 Slog.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 }
2058 return;
2059 }
2060
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002061 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
2062 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
2063 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
2064 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002065 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002066 }
2067 return;
2068 }
2069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 if (false) {
2071 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002072 Slog.d(TAG, "userActivity !!!");//, new RuntimeException());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002074 Slog.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 }
2076 }
2077
2078 synchronized (mLocks) {
2079 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002080 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 + " mUserActivityAllowed=" + mUserActivityAllowed
2082 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002083 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2084 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002085 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002086 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 }
Mike Lockwood05067122009-10-27 23:07:25 -04002088 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002089 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002090 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002091 return;
2092 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002093 // Disable proximity sensor if if user presses power key while we are in the
2094 // "waiting for proximity sensor to go negative" state.
2095 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2096 mProximitySensorActive = false;
2097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 if (mLastEventTime <= time || force) {
2099 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002100 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002101 // Only turn on button backlights if a button was pressed
2102 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002103 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2105 } else {
2106 // don't clear button/keyboard backlights when the screen is touched.
2107 mUserState |= SCREEN_BRIGHT;
2108 }
2109
Dianne Hackborn617f8772009-03-31 15:04:46 -07002110 int uid = Binder.getCallingUid();
2111 long ident = Binder.clearCallingIdentity();
2112 try {
2113 mBatteryStats.noteUserActivity(uid, eventType);
2114 } catch (RemoteException e) {
2115 // Ignore
2116 } finally {
2117 Binder.restoreCallingIdentity(ident);
2118 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002119
Michael Chane96440f2009-05-06 10:27:36 -07002120 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002121 setPowerState(mUserState | mWakeLockState, noChangeLights,
2122 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002123 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 }
2125 }
2126 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002127
2128 if (mPolicy != null) {
2129 mPolicy.userActivity();
2130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 }
2132
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002133 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2134 try {
2135 int i;
2136 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2137 if (sensorValue < mAutoBrightnessLevels[i]) {
2138 break;
2139 }
2140 }
2141 return values[i];
2142 } catch (Exception e) {
2143 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002144 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002145 return 255;
2146 }
2147 }
2148
Mike Lockwood20f87d72009-11-05 16:08:51 -05002149 private Runnable mProximityTask = new Runnable() {
2150 public void run() {
2151 synchronized (mLocks) {
2152 if (mProximityPendingValue != -1) {
2153 proximityChangedLocked(mProximityPendingValue == 1);
2154 mProximityPendingValue = -1;
2155 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002156 if (mProximityPartialLock.isHeld()) {
2157 mProximityPartialLock.release();
2158 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002159 }
2160 }
2161 };
2162
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002163 private Runnable mAutoBrightnessTask = new Runnable() {
2164 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002165 synchronized (mLocks) {
2166 int value = (int)mLightSensorPendingValue;
2167 if (value >= 0) {
2168 mLightSensorPendingValue = -1;
2169 lightSensorChangedLocked(value);
2170 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002171 }
2172 }
2173 };
2174
Mike Lockwoodb2865412010-02-02 22:40:33 -05002175 private void dockStateChanged(int state) {
2176 synchronized (mLocks) {
2177 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2178 if (mIsDocked) {
2179 mHighestLightSensorValue = -1;
2180 }
2181 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2182 // force lights recalculation
2183 int value = (int)mLightSensorValue;
2184 mLightSensorValue = -1;
2185 lightSensorChangedLocked(value);
2186 }
2187 }
2188 }
2189
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002190 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002191 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002192 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002193 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002194
Mike Lockwoodb2865412010-02-02 22:40:33 -05002195 // do not allow light sensor value to decrease
2196 if (mHighestLightSensorValue < value) {
2197 mHighestLightSensorValue = value;
2198 }
2199
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002200 if (mLightSensorValue != value) {
2201 mLightSensorValue = value;
2202 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002203 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2204 // we only do this if we are undocked, since lighting should be stable when
2205 // stationary in a dock.
2206 int lcdValue = getAutoBrightnessValue(
2207 (mIsDocked ? value : mHighestLightSensorValue),
2208 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002209 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002210 int keyboardValue;
2211 if (mKeyboardVisible) {
2212 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2213 } else {
2214 keyboardValue = 0;
2215 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002216 mLightSensorScreenBrightness = lcdValue;
2217 mLightSensorButtonBrightness = buttonValue;
2218 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002219
2220 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002221 Slog.d(TAG, "lcdValue " + lcdValue);
2222 Slog.d(TAG, "buttonValue " + buttonValue);
2223 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002224 }
2225
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002226 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002227 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002228 if (ANIMATE_SCREEN_LIGHTS) {
2229 if (mScreenBrightness.setTargetLocked(lcdValue,
2230 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2231 (int)mScreenBrightness.curValue)) {
2232 startAnimation = true;
2233 }
2234 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002235 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002236 ? LightsService.BRIGHTNESS_MODE_SENSOR
2237 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002238 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002239 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002240 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002241 if (mButtonBrightnessOverride < 0) {
2242 if (ANIMATE_BUTTON_LIGHTS) {
2243 if (mButtonBrightness.setTargetLocked(buttonValue,
2244 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2245 (int)mButtonBrightness.curValue)) {
2246 startAnimation = true;
2247 }
2248 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002249 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002250 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002251 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002252 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2253 if (ANIMATE_KEYBOARD_LIGHTS) {
2254 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2255 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2256 (int)mKeyboardBrightness.curValue)) {
2257 startAnimation = true;
2258 }
2259 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002260 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002261 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002262 }
2263 if (startAnimation) {
2264 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002265 Slog.i(TAG, "lightSensorChangedLocked scheduling light animator");
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002266 }
2267 mHandler.removeCallbacks(mLightAnimator);
2268 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002269 }
2270 }
2271 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002272 }
2273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 /**
2275 * The user requested that we go to sleep (probably with the power button).
2276 * This overrides all wake locks that are held.
2277 */
2278 public void goToSleep(long time)
2279 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002280 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2281 }
2282
2283 /**
2284 * The user requested that we go to sleep (probably with the power button).
2285 * This overrides all wake locks that are held.
2286 */
2287 public void goToSleepWithReason(long time, int reason)
2288 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2290 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002291 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 }
2293 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002296 * Reboot the device immediately, passing 'reason' (may be null)
2297 * to the underlying __reboot system call. Should not return.
2298 */
2299 public void reboot(String reason)
2300 {
2301 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002302
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002303 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2304 throw new IllegalStateException("Too early to call reboot()");
2305 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002306
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002307 final String finalReason = reason;
2308 Runnable runnable = new Runnable() {
2309 public void run() {
2310 synchronized (this) {
2311 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002312 }
2313
San Mehat1e512792010-01-07 10:40:29 -08002314 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002315 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002316 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002317 mHandler.post(runnable);
2318
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002319 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002320 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002321 while (true) {
2322 try {
2323 runnable.wait();
2324 } catch (InterruptedException e) {
2325 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002326 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002327 }
2328 }
2329
Dan Egnor60d87622009-12-16 16:32:58 -08002330 /**
2331 * Crash the runtime (causing a complete restart of the Android framework).
2332 * Requires REBOOT permission. Mostly for testing. Should not return.
2333 */
2334 public void crash(final String message)
2335 {
2336 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2337 Thread t = new Thread("PowerManagerService.crash()") {
2338 public void run() { throw new RuntimeException(message); }
2339 };
2340 try {
2341 t.start();
2342 t.join();
2343 } catch (InterruptedException e) {
2344 Log.wtf(TAG, e);
2345 }
2346 }
2347
Mike Lockwood435eb642009-12-03 08:40:18 -05002348 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349
2350 if (mLastEventTime <= time) {
2351 mLastEventTime = time;
2352 // cancel all of the wake locks
2353 mWakeLockState = SCREEN_OFF;
2354 int N = mLocks.size();
2355 int numCleared = 0;
2356 for (int i=0; i<N; i++) {
2357 WakeLock wl = mLocks.get(i);
2358 if (isScreenLock(wl.flags)) {
2359 mLocks.get(i).activated = false;
2360 numCleared++;
2361 }
2362 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002363 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002364 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002366 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 cancelTimerLocked();
2368 }
2369 }
2370
2371 public long timeSinceScreenOn() {
2372 synchronized (mLocks) {
2373 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2374 return 0;
2375 }
2376 return SystemClock.elapsedRealtime() - mScreenOffTime;
2377 }
2378 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002381 synchronized (mLocks) {
2382 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002383 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002384 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002385 if (mKeyboardVisible != visible) {
2386 mKeyboardVisible = visible;
2387 // don't signal user activity if the screen is off; other code
2388 // will take care of turning on due to a true change to the lid
2389 // switch and synchronized with the lock screen.
2390 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002391 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002392 // force recompute of backlight values
2393 if (mLightSensorValue >= 0) {
2394 int value = (int)mLightSensorValue;
2395 mLightSensorValue = -1;
2396 lightSensorChangedLocked(value);
2397 }
2398 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002399 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2400 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002401 }
2402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 }
2404
2405 /**
2406 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002407 * When disabling user activity we also reset user power state so the keyguard can reset its
2408 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 */
2410 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002411 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002412 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 synchronized (mLocks) {
2415 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002416 if (!enabled) {
2417 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2418 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 }
2421 }
2422
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002423 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002424 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002425 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002426 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002427 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002428 // force recompute of backlight values
2429 if (mLightSensorValue >= 0) {
2430 int value = (int)mLightSensorValue;
2431 mLightSensorValue = -1;
2432 lightSensorChangedLocked(value);
2433 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002434 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002435 }
2436 }
2437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 /** Sets the screen off timeouts:
2439 * mKeylightDelay
2440 * mDimDelay
2441 * mScreenOffDelay
2442 * */
2443 private void setScreenOffTimeoutsLocked() {
2444 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002445 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 mDimDelay = -1;
2447 mScreenOffDelay = 0;
2448 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2449 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2450 mDimDelay = -1;
2451 mScreenOffDelay = 0;
2452 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002453 int totalDelay = mScreenOffTimeoutSetting;
2454 if (totalDelay > mMaximumScreenOffTimeout) {
2455 totalDelay = mMaximumScreenOffTimeout;
2456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2458 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002459 // negative number means stay on as long as possible.
2460 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 } else if (mKeylightDelay < totalDelay) {
2462 // subtract the time that the keylight delay. This will give us the
2463 // remainder of the time that we need to sleep to get the accurate
2464 // screen off timeout.
2465 mScreenOffDelay = totalDelay - mKeylightDelay;
2466 } else {
2467 mScreenOffDelay = 0;
2468 }
2469 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2470 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2471 mScreenOffDelay = LONG_DIM_TIME;
2472 } else {
2473 mDimDelay = -1;
2474 }
2475 }
2476 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002477 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2479 + " mDimScreen=" + mDimScreen);
2480 }
2481 }
2482
2483 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002484 * Refreshes cached secure settings. Called once on startup, and
2485 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 */
Doug Zongker43866e02010-01-07 12:09:54 -08002487 private void updateSettingsValues() {
2488 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002490 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002492 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 }
2494
2495 private class LockList extends ArrayList<WakeLock>
2496 {
2497 void addLock(WakeLock wl)
2498 {
2499 int index = getIndex(wl.binder);
2500 if (index < 0) {
2501 this.add(wl);
2502 }
2503 }
2504
2505 WakeLock removeLock(IBinder binder)
2506 {
2507 int index = getIndex(binder);
2508 if (index >= 0) {
2509 return this.remove(index);
2510 } else {
2511 return null;
2512 }
2513 }
2514
2515 int getIndex(IBinder binder)
2516 {
2517 int N = this.size();
2518 for (int i=0; i<N; i++) {
2519 if (this.get(i).binder == binder) {
2520 return i;
2521 }
2522 }
2523 return -1;
2524 }
2525
2526 int gatherState()
2527 {
2528 int result = 0;
2529 int N = this.size();
2530 for (int i=0; i<N; i++) {
2531 WakeLock wl = this.get(i);
2532 if (wl.activated) {
2533 if (isScreenLock(wl.flags)) {
2534 result |= wl.minState;
2535 }
2536 }
2537 }
2538 return result;
2539 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002540
Michael Chane96440f2009-05-06 10:27:36 -07002541 int reactivateScreenLocksLocked()
2542 {
2543 int result = 0;
2544 int N = this.size();
2545 for (int i=0; i<N; i++) {
2546 WakeLock wl = this.get(i);
2547 if (isScreenLock(wl.flags)) {
2548 wl.activated = true;
2549 result |= wl.minState;
2550 }
2551 }
2552 return result;
2553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 }
2555
2556 void setPolicy(WindowManagerPolicy p) {
2557 synchronized (mLocks) {
2558 mPolicy = p;
2559 mLocks.notifyAll();
2560 }
2561 }
2562
2563 WindowManagerPolicy getPolicyLocked() {
2564 while (mPolicy == null || !mDoneBooting) {
2565 try {
2566 mLocks.wait();
2567 } catch (InterruptedException e) {
2568 // Ignore
2569 }
2570 }
2571 return mPolicy;
2572 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002575 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2576 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2577 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002578 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002579 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002580 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002581 }
2582
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002583 // wait until sensors are enabled before turning on screen.
2584 // some devices will not activate the light sensor properly on boot
2585 // unless we do this.
2586 if (mUseSoftwareAutoBrightness) {
2587 // turn the screen on
2588 setPowerState(SCREEN_BRIGHT);
2589 } else {
2590 // turn everything on
2591 setPowerState(ALL_BRIGHT);
2592 }
2593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002595 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002597
Dianne Hackborn617f8772009-03-31 15:04:46 -07002598 long identity = Binder.clearCallingIdentity();
2599 try {
2600 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2601 mBatteryStats.noteScreenOn();
2602 } catch (RemoteException e) {
2603 // Nothing interesting to do.
2604 } finally {
2605 Binder.restoreCallingIdentity(identity);
2606 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002607 }
2608 }
2609
2610 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002611 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002612 synchronized (mLocks) {
2613 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2615 updateWakeLockLocked();
2616 mLocks.notifyAll();
2617 }
2618 }
2619
2620 public void monitor() {
2621 synchronized (mLocks) { }
2622 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002623
2624 public int getSupportedWakeLockFlags() {
2625 int result = PowerManager.PARTIAL_WAKE_LOCK
2626 | PowerManager.FULL_WAKE_LOCK
2627 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2628
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002629 if (mProximitySensor != null) {
2630 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2631 }
2632
2633 return result;
2634 }
2635
Mike Lockwood237a2992009-09-15 14:42:16 -04002636 public void setBacklightBrightness(int brightness) {
2637 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2638 // Don't let applications turn the screen all the way off
2639 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002640 mLcdLight.setBrightness(brightness);
2641 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2642 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002643 long identity = Binder.clearCallingIdentity();
2644 try {
2645 mBatteryStats.noteScreenBrightness(brightness);
2646 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002647 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
Mike Lockwood237a2992009-09-15 14:42:16 -04002648 } finally {
2649 Binder.restoreCallingIdentity(identity);
2650 }
2651
2652 // update our animation state
2653 if (ANIMATE_SCREEN_LIGHTS) {
2654 mScreenBrightness.curValue = brightness;
2655 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002656 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002657 }
2658 if (ANIMATE_KEYBOARD_LIGHTS) {
2659 mKeyboardBrightness.curValue = brightness;
2660 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002661 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002662 }
2663 if (ANIMATE_BUTTON_LIGHTS) {
2664 mButtonBrightness.curValue = brightness;
2665 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002666 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002667 }
2668 }
2669
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002670 public void setAttentionLight(boolean on, int color) {
2671 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002672 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002673 }
2674
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002675 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002676 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002677 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002678 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002679 if (!mProximitySensorEnabled) {
2680 // clear calling identity so sensor manager battery stats are accurate
2681 long identity = Binder.clearCallingIdentity();
2682 try {
2683 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2684 SensorManager.SENSOR_DELAY_NORMAL);
2685 mProximitySensorEnabled = true;
2686 } finally {
2687 Binder.restoreCallingIdentity(identity);
2688 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002689 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002690 }
2691
2692 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002693 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002694 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002695 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002696 if (mProximitySensorEnabled) {
2697 // clear calling identity so sensor manager battery stats are accurate
2698 long identity = Binder.clearCallingIdentity();
2699 try {
2700 mSensorManager.unregisterListener(mProximityListener);
2701 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002702 if (mProximityPartialLock.isHeld()) {
2703 mProximityPartialLock.release();
2704 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002705 mProximitySensorEnabled = false;
2706 } finally {
2707 Binder.restoreCallingIdentity(identity);
2708 }
2709 if (mProximitySensorActive) {
2710 mProximitySensorActive = false;
2711 forceUserActivityLocked();
2712 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002713 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002714 }
2715
Mike Lockwood20f87d72009-11-05 16:08:51 -05002716 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002717 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002718 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002719 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002720 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002721 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002722 return;
2723 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002724 if (active) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002725 goToSleepLocked(SystemClock.uptimeMillis(),
2726 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002727 mProximitySensorActive = true;
2728 } else {
2729 // proximity sensor negative events trigger as user activity.
2730 // temporarily set mUserActivityAllowed to true so this will work
2731 // even when the keyguard is on.
2732 mProximitySensorActive = false;
2733 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002734
2735 if (mProximityWakeLockCount == 0) {
2736 // disable sensor if we have no listeners left after proximity negative
2737 disableProximityLockLocked();
2738 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002739 }
2740 }
2741
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002742 private void enableLightSensor(boolean enable) {
2743 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002744 Slog.d(TAG, "enableLightSensor " + enable);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002745 }
2746 if (mSensorManager != null && mLightSensorEnabled != enable) {
2747 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002748 // clear calling identity so sensor manager battery stats are accurate
2749 long identity = Binder.clearCallingIdentity();
2750 try {
2751 if (enable) {
2752 mSensorManager.registerListener(mLightListener, mLightSensor,
2753 SensorManager.SENSOR_DELAY_NORMAL);
2754 } else {
2755 mSensorManager.unregisterListener(mLightListener);
2756 mHandler.removeCallbacks(mAutoBrightnessTask);
2757 }
2758 } finally {
2759 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002760 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002761 }
2762 }
2763
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002764 SensorEventListener mProximityListener = new SensorEventListener() {
2765 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002766 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002767 synchronized (mLocks) {
2768 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002769 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2770 mLastProximityEventTime = milliseconds;
2771 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002772 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002773
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002774 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002775 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2776 distance < mProximitySensor.getMaximumRange());
2777
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002778 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002779 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002780 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002781 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2782 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2783 mProximityPendingValue = (active ? 1 : 0);
2784 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002785 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002786 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002787 // process the value immediately
2788 mProximityPendingValue = -1;
2789 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002790 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002791
2792 // update mProximityPartialLock state
2793 boolean held = mProximityPartialLock.isHeld();
2794 if (!held && proximityTaskQueued) {
2795 // hold wakelock until mProximityTask runs
2796 mProximityPartialLock.acquire();
2797 } else if (held && !proximityTaskQueued) {
2798 mProximityPartialLock.release();
2799 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002800 }
2801 }
2802
2803 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2804 // ignore
2805 }
2806 };
2807
2808 SensorEventListener mLightListener = new SensorEventListener() {
2809 public void onSensorChanged(SensorEvent event) {
2810 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002811 // ignore light sensor while screen is turning off
2812 if (isScreenTurningOffLocked()) {
2813 return;
2814 }
2815
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002816 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002817 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002818 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002819 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002820 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002821 mHandler.removeCallbacks(mAutoBrightnessTask);
2822 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002823 if (mLightSensorValue == -1 ||
2824 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2825 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002826 lightSensorChangedLocked(value);
2827 } else {
2828 // delay processing to debounce the sensor
2829 mLightSensorPendingValue = value;
2830 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2831 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002832 } else {
2833 mLightSensorPendingValue = -1;
2834 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002835 }
2836 }
2837
2838 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2839 // ignore
2840 }
2841 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842}