blob: 94cf6d4a617fd4b4f2c128ba934572efcaa248fa [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import com.android.internal.app.IBatteryStats;
20import com.android.server.am.BatteryStatsService;
21
22import android.app.ActivityManagerNative;
23import android.app.IActivityManager;
24import android.content.BroadcastReceiver;
25import android.content.ContentQueryMap;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070031import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070033import android.hardware.Sensor;
34import android.hardware.SensorEvent;
35import android.hardware.SensorEventListener;
36import android.hardware.SensorManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.BatteryStats;
38import android.os.Binder;
39import android.os.Handler;
40import android.os.HandlerThread;
41import android.os.IBinder;
42import android.os.IPowerManager;
43import android.os.LocalPowerManager;
44import android.os.Power;
45import android.os.PowerManager;
46import android.os.Process;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.provider.Settings.SettingNotFoundException;
50import android.provider.Settings;
51import android.util.EventLog;
52import android.util.Log;
53import android.view.WindowManagerPolicy;
54import static android.provider.Settings.System.DIM_SCREEN;
55import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050056import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070057import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
59import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
60
61import java.io.FileDescriptor;
62import java.io.PrintWriter;
63import java.util.ArrayList;
64import java.util.HashMap;
65import java.util.Observable;
66import java.util.Observer;
67
Mike Lockwoodbc706a02009-07-27 13:50:57 -070068class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040069 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070
71 private static final String TAG = "PowerManagerService";
72 static final String PARTIAL_NAME = "PowerManagerService";
73
74 private static final boolean LOG_PARTIAL_WL = false;
75
76 // Indicates whether touch-down cycles should be logged as part of the
77 // LOG_POWER_SCREEN_STATE log events
78 private static final boolean LOG_TOUCH_DOWNS = true;
79
80 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
81 | PowerManager.SCREEN_DIM_WAKE_LOCK
82 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070083 | PowerManager.FULL_WAKE_LOCK
84 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
86 // time since last state: time since last event:
87 // The short keylight delay comes from Gservices; this is the default.
88 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
89 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
90 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
91 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
92
Mike Lockwoodd7786b42009-10-15 17:09:16 -070093 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -050094 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070095
Mike Lockwood20f87d72009-11-05 16:08:51 -050096 // For debouncing the proximity sensor.
97 private static final int PROXIMITY_SENSOR_DELAY = 1000;
98
Mike Lockwoodd20ea362009-09-15 00:13:38 -040099 // trigger proximity if distance is less than 5 cm
100 private static final float PROXIMITY_THRESHOLD = 5.0f;
101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 // Cached Gservices settings; see updateGservicesValues()
103 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
104
105 // flags for setPowerState
106 private static final int SCREEN_ON_BIT = 0x00000001;
107 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
108 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
109 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
110 private static final int BATTERY_LOW_BIT = 0x00000010;
111
112 // values for setPowerState
113
114 // SCREEN_OFF == everything off
115 private static final int SCREEN_OFF = 0x00000000;
116
117 // SCREEN_DIM == screen on, screen backlight dim
118 private static final int SCREEN_DIM = SCREEN_ON_BIT;
119
120 // SCREEN_BRIGHT == screen on, screen backlight bright
121 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
122
123 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
124 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
125
126 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
127 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
128
129 // used for noChangeLights in setPowerState()
130 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
131
132 static final boolean ANIMATE_SCREEN_LIGHTS = true;
133 static final boolean ANIMATE_BUTTON_LIGHTS = false;
134 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
135
136 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400137 // Slower animation for autobrightness changes
138 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139
140 // These magic numbers are the initial state of the LEDs at boot. Ideally
141 // we should read them from the driver, but our current hardware returns 0
142 // for the initial value. Oops!
143 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
144 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
145 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
146
147 static final int LOG_POWER_SLEEP_REQUESTED = 2724;
148 static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
149 static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
150 static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
151 static final int LOG_POWER_SCREEN_STATE = 2728;
152 static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
153
154 private final int MY_UID;
155
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;
Joe Onorato128e7292009-03-24 18:41:31 -0700159 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
160 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 private int mPartialCount = 0;
162 private int mPowerState;
163 private boolean mOffBecauseOfUser;
164 private int mUserState;
165 private boolean mKeyboardVisible = false;
166 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500167 private int mProximityWakeLockCount = 0;
168 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700169 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500170 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
171 private long mLastProximityEventTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 private int mTotalDelaySetting;
173 private int mKeylightDelay;
174 private int mDimDelay;
175 private int mScreenOffDelay;
176 private int mWakeLockState;
177 private long mLastEventTime = 0;
178 private long mScreenOffTime;
179 private volatile WindowManagerPolicy mPolicy;
180 private final LockList mLocks = new LockList();
181 private Intent mScreenOffIntent;
182 private Intent mScreenOnIntent;
The Android Open Source Project10592532009-03-18 17:39:46 -0700183 private HardwareService mHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 private Context mContext;
185 private UnsynchronizedWakeLock mBroadcastWakeLock;
186 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
187 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
188 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500189 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 private HandlerThread mHandlerThread;
191 private Handler mHandler;
192 private TimeoutTask mTimeoutTask = new TimeoutTask();
193 private LightAnimator mLightAnimator = new LightAnimator();
194 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700195 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700197 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700199 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700200 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 private boolean mIsPowered = false;
202 private IActivityManager mActivityService;
203 private IBatteryStats mBatteryStats;
204 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700205 private SensorManager mSensorManager;
206 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400207 private Sensor mLightSensor;
208 private boolean mLightSensorEnabled;
209 private float mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700210 private float mLightSensorPendingValue = -1;
211 private int mLightSensorBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 private boolean mDimScreen = true;
213 private long mNextTimeout;
214 private volatile int mPokey = 0;
215 private volatile boolean mPokeAwakeOnSet = false;
216 private volatile boolean mInitComplete = false;
217 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500218 // mScreenOnTime and mScreenOnStartTime are used for computing total time screen
219 // has been on since boot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 private long mScreenOnTime;
221 private long mScreenOnStartTime;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500222 // mLastScreenOnTime is the time the screen was last turned on
223 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 private boolean mPreventScreenOn;
225 private int mScreenBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400226 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700227 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700228 private int[] mAutoBrightnessLevels;
229 private int[] mLcdBacklightValues;
230 private int[] mButtonBacklightValues;
231 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500232 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233
234 // Used when logging number and duration of touch-down cycles
235 private long mTotalTouchDownTime;
236 private long mLastTouchDown;
237 private int mTouchCycles;
238
239 // could be either static or controllable at runtime
240 private static final boolean mSpew = false;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500241 private static final boolean mDebugProximitySensor = (true || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400242 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
244 /*
245 static PrintStream mLog;
246 static {
247 try {
248 mLog = new PrintStream("/data/power.log");
249 }
250 catch (FileNotFoundException e) {
251 android.util.Log.e(TAG, "Life is hard", e);
252 }
253 }
254 static class Log {
255 static void d(String tag, String s) {
256 mLog.println(s);
257 android.util.Log.d(tag, s);
258 }
259 static void i(String tag, String s) {
260 mLog.println(s);
261 android.util.Log.i(tag, s);
262 }
263 static void w(String tag, String s) {
264 mLog.println(s);
265 android.util.Log.w(tag, s);
266 }
267 static void e(String tag, String s) {
268 mLog.println(s);
269 android.util.Log.e(tag, s);
270 }
271 }
272 */
273
274 /**
275 * This class works around a deadlock between the lock in PowerManager.WakeLock
276 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
277 * mToken object so it can be accessed from any thread, but it calls into here
278 * with its lock held. This class is essentially a reimplementation of
279 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
280 * only call it with our own locks held.
281 */
282 private class UnsynchronizedWakeLock {
283 int mFlags;
284 String mTag;
285 IBinder mToken;
286 int mCount = 0;
287 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500288 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289
290 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
291 mFlags = flags;
292 mTag = tag;
293 mToken = new Binder();
294 mRefCounted = refCounted;
295 }
296
297 public void acquire() {
298 if (!mRefCounted || mCount++ == 0) {
299 long ident = Binder.clearCallingIdentity();
300 try {
301 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
302 MY_UID, mTag);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500303 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 } finally {
305 Binder.restoreCallingIdentity(ident);
306 }
307 }
308 }
309
310 public void release() {
311 if (!mRefCounted || --mCount == 0) {
312 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500313 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 }
315 if (mCount < 0) {
316 throw new RuntimeException("WakeLock under-locked " + mTag);
317 }
318 }
319
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500320 public boolean isHeld()
321 {
322 return mHeld;
323 }
324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 public String toString() {
326 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500327 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 }
329 }
330
331 private final class BatteryReceiver extends BroadcastReceiver {
332 @Override
333 public void onReceive(Context context, Intent intent) {
334 synchronized (mLocks) {
335 boolean wasPowered = mIsPowered;
336 mIsPowered = mBatteryService.isPowered();
337
338 if (mIsPowered != wasPowered) {
339 // update mStayOnWhilePluggedIn wake lock
340 updateWakeLockLocked();
341
342 // treat plugging and unplugging the devices as a user activity.
343 // users find it disconcerting when they unplug the device
344 // and it shuts off right away.
345 // temporarily set mUserActivityAllowed to true so this will work
346 // even when the keyguard is on.
347 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400348 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 }
350 }
351 }
352 }
353 }
354
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500355 private final class BootCompletedReceiver extends BroadcastReceiver {
356 @Override
357 public void onReceive(Context context, Intent intent) {
358 bootCompleted();
359 }
360 }
361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 /**
363 * Set the setting that determines whether the device stays on when plugged in.
364 * The argument is a bit string, with each bit specifying a power source that,
365 * when the device is connected to that source, causes the device to stay on.
366 * See {@link android.os.BatteryManager} for the list of power sources that
367 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
368 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
369 * @param val an {@code int} containing the bits that specify which power sources
370 * should cause the device to stay on.
371 */
372 public void setStayOnSetting(int val) {
373 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
374 Settings.System.putInt(mContext.getContentResolver(),
375 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
376 }
377
378 private class SettingsObserver implements Observer {
379 private int getInt(String name) {
380 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
381 }
382
383 public void update(Observable o, Object arg) {
384 synchronized (mLocks) {
385 // STAY_ON_WHILE_PLUGGED_IN
386 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
387 updateWakeLockLocked();
388
389 // SCREEN_OFF_TIMEOUT
390 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
391
392 // DIM_SCREEN
393 //mDimScreen = getInt(DIM_SCREEN) != 0;
394
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700395 // SCREEN_BRIGHTNESS_MODE
396 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 // recalculate everything
399 setScreenOffTimeoutsLocked();
400 }
401 }
402 }
403
404 PowerManagerService()
405 {
406 // Hack to get our uid... should have a func for this.
407 long token = Binder.clearCallingIdentity();
408 MY_UID = Binder.getCallingUid();
409 Binder.restoreCallingIdentity(token);
410
411 // XXX remove this when the kernel doesn't timeout wake locks
412 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
413
414 // assume nothing is on yet
415 mUserState = mPowerState = 0;
416
417 // Add ourself to the Watchdog monitors.
418 Watchdog.getInstance().addMonitor(this);
419 mScreenOnStartTime = SystemClock.elapsedRealtime();
420 }
421
422 private ContentQueryMap mSettings;
423
The Android Open Source Project10592532009-03-18 17:39:46 -0700424 void init(Context context, HardwareService hardware, IActivityManager activity,
425 BatteryService battery) {
426 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 mContext = context;
428 mActivityService = activity;
429 mBatteryStats = BatteryStatsService.getService();
430 mBatteryService = battery;
431
432 mHandlerThread = new HandlerThread("PowerManagerService") {
433 @Override
434 protected void onLooperPrepared() {
435 super.onLooperPrepared();
436 initInThread();
437 }
438 };
439 mHandlerThread.start();
440
441 synchronized (mHandlerThread) {
442 while (!mInitComplete) {
443 try {
444 mHandlerThread.wait();
445 } catch (InterruptedException e) {
446 // Ignore
447 }
448 }
449 }
450 }
451
452 void initInThread() {
453 mHandler = new Handler();
454
455 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700456 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
458 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
459 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
460 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
461 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
462 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500463 mProximityPartialLock = new UnsynchronizedWakeLock(
464 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465
466 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
467 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
468 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
469 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
470
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700471 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400472
473 // read settings for auto-brightness
474 mUseSoftwareAutoBrightness = resources.getBoolean(
475 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400476 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700477 mAutoBrightnessLevels = resources.getIntArray(
478 com.android.internal.R.array.config_autoBrightnessLevels);
479 mLcdBacklightValues = resources.getIntArray(
480 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
481 mButtonBacklightValues = resources.getIntArray(
482 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
483 mKeyboardBacklightValues = resources.getIntArray(
484 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500485 mLightSensorWarmupTime = resources.getInteger(
486 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700487 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700488
489 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
491 "(" + Settings.System.NAME + "=?) or ("
492 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700493 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700495 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
496 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 null);
498 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
499 SettingsObserver settingsObserver = new SettingsObserver();
500 mSettings.addObserver(settingsObserver);
501
502 // pretend that the settings changed so we will get their initial state
503 settingsObserver.update(mSettings, null);
504
505 // register for the battery changed notifications
506 IntentFilter filter = new IntentFilter();
507 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
508 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500509 filter = new IntentFilter();
510 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
511 mContext.registerReceiver(new BootCompletedReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512
513 // Listen for Gservices changes
514 IntentFilter gservicesChangedFilter =
515 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
516 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
517 // And explicitly do the initial update of our cached settings
518 updateGservicesValues();
519
Mike Lockwood4984e732009-11-01 08:16:33 -0500520 if (mUseSoftwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400521 // turn the screen on
522 setPowerState(SCREEN_BRIGHT);
523 } else {
524 // turn everything on
525 setPowerState(ALL_BRIGHT);
526 }
Dan Murphy951764b2009-08-27 14:59:03 -0500527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 synchronized (mHandlerThread) {
529 mInitComplete = true;
530 mHandlerThread.notifyAll();
531 }
532 }
533
534 private class WakeLock implements IBinder.DeathRecipient
535 {
536 WakeLock(int f, IBinder b, String t, int u) {
537 super();
538 flags = f;
539 binder = b;
540 tag = t;
541 uid = u == MY_UID ? Process.SYSTEM_UID : u;
542 if (u != MY_UID || (
543 !"KEEP_SCREEN_ON_FLAG".equals(tag)
544 && !"KeyInputQueue".equals(tag))) {
545 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
546 ? BatteryStats.WAKE_TYPE_PARTIAL
547 : BatteryStats.WAKE_TYPE_FULL;
548 } else {
549 monitorType = -1;
550 }
551 try {
552 b.linkToDeath(this, 0);
553 } catch (RemoteException e) {
554 binderDied();
555 }
556 }
557 public void binderDied() {
558 synchronized (mLocks) {
559 releaseWakeLockLocked(this.binder, true);
560 }
561 }
562 final int flags;
563 final IBinder binder;
564 final String tag;
565 final int uid;
566 final int monitorType;
567 boolean activated = true;
568 int minState;
569 }
570
571 private void updateWakeLockLocked() {
572 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
573 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
574 mStayOnWhilePluggedInScreenDimLock.acquire();
575 mStayOnWhilePluggedInPartialLock.acquire();
576 } else {
577 mStayOnWhilePluggedInScreenDimLock.release();
578 mStayOnWhilePluggedInPartialLock.release();
579 }
580 }
581
582 private boolean isScreenLock(int flags)
583 {
584 int n = flags & LOCK_MASK;
585 return n == PowerManager.FULL_WAKE_LOCK
586 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
587 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
588 }
589
590 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700592 if (uid != Process.myUid()) {
593 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 long ident = Binder.clearCallingIdentity();
596 try {
597 synchronized (mLocks) {
598 acquireWakeLockLocked(flags, lock, uid, tag);
599 }
600 } finally {
601 Binder.restoreCallingIdentity(ident);
602 }
603 }
604
605 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
606 int acquireUid = -1;
607 String acquireName = null;
608 int acquireType = -1;
609
610 if (mSpew) {
611 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
612 }
613
614 int index = mLocks.getIndex(lock);
615 WakeLock wl;
616 boolean newlock;
617 if (index < 0) {
618 wl = new WakeLock(flags, lock, tag, uid);
619 switch (wl.flags & LOCK_MASK)
620 {
621 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500622 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400623 wl.minState = SCREEN_BRIGHT;
624 } else {
625 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 break;
628 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
629 wl.minState = SCREEN_BRIGHT;
630 break;
631 case PowerManager.SCREEN_DIM_WAKE_LOCK:
632 wl.minState = SCREEN_DIM;
633 break;
634 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700635 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 break;
637 default:
638 // just log and bail. we're in the server, so don't
639 // throw an exception.
640 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
641 + " flags=" + flags);
642 return;
643 }
644 mLocks.addLock(wl);
645 newlock = true;
646 } else {
647 wl = mLocks.get(index);
648 newlock = false;
649 }
650 if (isScreenLock(flags)) {
651 // if this causes a wakeup, we reactivate all of the locks and
652 // set it to whatever they want. otherwise, we modulate that
653 // by the current state so we never turn it more on than
654 // it already is.
655 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700656 int oldWakeLockState = mWakeLockState;
657 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 if (mSpew) {
659 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700660 + " mWakeLockState=0x"
661 + Integer.toHexString(mWakeLockState)
662 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 } else {
665 if (mSpew) {
666 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
667 + " mLocks.gatherState()=0x"
668 + Integer.toHexString(mLocks.gatherState())
669 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
670 }
671 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
672 }
673 setPowerState(mWakeLockState | mUserState);
674 }
675 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
676 if (newlock) {
677 mPartialCount++;
678 if (mPartialCount == 1) {
679 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
680 }
681 }
682 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700683 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500684 mProximityWakeLockCount++;
685 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700686 enableProximityLockLocked();
687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 }
689 if (newlock) {
690 acquireUid = wl.uid;
691 acquireName = wl.tag;
692 acquireType = wl.monitorType;
693 }
694
695 if (acquireType >= 0) {
696 try {
697 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
698 } catch (RemoteException e) {
699 // Ignore
700 }
701 }
702 }
703
704 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700705 int uid = Binder.getCallingUid();
706 if (uid != Process.myUid()) {
707 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709
710 synchronized (mLocks) {
711 releaseWakeLockLocked(lock, false);
712 }
713 }
714
715 private void releaseWakeLockLocked(IBinder lock, boolean death) {
716 int releaseUid;
717 String releaseName;
718 int releaseType;
719
720 WakeLock wl = mLocks.removeLock(lock);
721 if (wl == null) {
722 return;
723 }
724
725 if (mSpew) {
726 Log.d(TAG, "releaseWakeLock flags=0x"
727 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
728 }
729
730 if (isScreenLock(wl.flags)) {
731 mWakeLockState = mLocks.gatherState();
732 // goes in the middle to reduce flicker
733 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
734 userActivity(SystemClock.uptimeMillis(), false);
735 }
736 setPowerState(mWakeLockState | mUserState);
737 }
738 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
739 mPartialCount--;
740 if (mPartialCount == 0) {
741 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
742 Power.releaseWakeLock(PARTIAL_NAME);
743 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700744 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500745 mProximityWakeLockCount--;
746 if (mProximityWakeLockCount == 0) {
747 if (mProximitySensorActive) {
748 // wait for proximity sensor to go negative before disabling sensor
749 if (mDebugProximitySensor) {
750 Log.d(TAG, "waiting for proximity sensor to go negative");
751 }
752 } else {
753 disableProximityLockLocked();
754 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 }
757 // Unlink the lock from the binder.
758 wl.binder.unlinkToDeath(wl, 0);
759 releaseUid = wl.uid;
760 releaseName = wl.tag;
761 releaseType = wl.monitorType;
762
763 if (releaseType >= 0) {
764 long origId = Binder.clearCallingIdentity();
765 try {
766 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
767 } catch (RemoteException e) {
768 // Ignore
769 } finally {
770 Binder.restoreCallingIdentity(origId);
771 }
772 }
773 }
774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 private class PokeLock implements IBinder.DeathRecipient
776 {
777 PokeLock(int p, IBinder b, String t) {
778 super();
779 this.pokey = p;
780 this.binder = b;
781 this.tag = t;
782 try {
783 b.linkToDeath(this, 0);
784 } catch (RemoteException e) {
785 binderDied();
786 }
787 }
788 public void binderDied() {
789 setPokeLock(0, this.binder, this.tag);
790 }
791 int pokey;
792 IBinder binder;
793 String tag;
794 boolean awakeOnSet;
795 }
796
797 public void setPokeLock(int pokey, IBinder token, String tag) {
798 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
799 if (token == null) {
800 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
801 return;
802 }
803
804 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
805 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
806 + " and POKE_LOCK_MEDIUM_TIMEOUT");
807 }
808
809 synchronized (mLocks) {
810 if (pokey != 0) {
811 PokeLock p = mPokeLocks.get(token);
812 int oldPokey = 0;
813 if (p != null) {
814 oldPokey = p.pokey;
815 p.pokey = pokey;
816 } else {
817 p = new PokeLock(pokey, token, tag);
818 mPokeLocks.put(token, p);
819 }
820 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
821 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
822 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
823 p.awakeOnSet = true;
824 }
825 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700826 PokeLock rLock = mPokeLocks.remove(token);
827 if (rLock != null) {
828 token.unlinkToDeath(rLock, 0);
829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 }
831
832 int oldPokey = mPokey;
833 int cumulative = 0;
834 boolean oldAwakeOnSet = mPokeAwakeOnSet;
835 boolean awakeOnSet = false;
836 for (PokeLock p: mPokeLocks.values()) {
837 cumulative |= p.pokey;
838 if (p.awakeOnSet) {
839 awakeOnSet = true;
840 }
841 }
842 mPokey = cumulative;
843 mPokeAwakeOnSet = awakeOnSet;
844
845 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
846 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
847
848 if (oldCumulativeTimeout != newCumulativeTimeout) {
849 setScreenOffTimeoutsLocked();
850 // reset the countdown timer, but use the existing nextState so it doesn't
851 // change anything
852 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
853 }
854 }
855 }
856
857 private static String lockType(int type)
858 {
859 switch (type)
860 {
861 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700862 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700864 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700866 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700868 return "PARTIAL_WAKE_LOCK ";
869 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
870 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 default:
David Brown251faa62009-08-02 22:04:36 -0700872 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 }
874 }
875
876 private static String dumpPowerState(int state) {
877 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
878 ? "KEYBOARD_BRIGHT_BIT " : "")
879 + (((state & SCREEN_BRIGHT_BIT) != 0)
880 ? "SCREEN_BRIGHT_BIT " : "")
881 + (((state & SCREEN_ON_BIT) != 0)
882 ? "SCREEN_ON_BIT " : "")
883 + (((state & BATTERY_LOW_BIT) != 0)
884 ? "BATTERY_LOW_BIT " : "");
885 }
886
887 @Override
888 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
889 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
890 != PackageManager.PERMISSION_GRANTED) {
891 pw.println("Permission Denial: can't dump PowerManager from from pid="
892 + Binder.getCallingPid()
893 + ", uid=" + Binder.getCallingUid());
894 return;
895 }
896
897 long now = SystemClock.uptimeMillis();
898
899 pw.println("Power Manager State:");
900 pw.println(" mIsPowered=" + mIsPowered
901 + " mPowerState=" + mPowerState
902 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
903 + " ms");
904 pw.println(" mPartialCount=" + mPartialCount);
905 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
906 pw.println(" mUserState=" + dumpPowerState(mUserState));
907 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
908 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
909 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
910 + " " + ((mNextTimeout-now)/1000) + "s from now");
911 pw.println(" mDimScreen=" + mDimScreen
912 + " mStayOnConditions=" + mStayOnConditions);
913 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
914 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700915 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
916 + ',' + mBroadcastQueue[2] + "}");
917 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
918 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
920 pw.println(" mKeyboardVisible=" + mKeyboardVisible
921 + " mUserActivityAllowed=" + mUserActivityAllowed);
922 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
923 + " mScreenOffDelay=" + mScreenOffDelay);
924 pw.println(" mPreventScreenOn=" + mPreventScreenOn
925 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
926 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500927 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
929 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
930 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
931 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500932 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500933 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
934 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700935 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
Mike Lockwood20f87d72009-11-05 16:08:51 -0500936 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
937 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700938 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
939 pw.println(" mLightSensorValue=" + mLightSensorValue);
940 pw.println(" mLightSensorPendingValue=" + mLightSensorPendingValue);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400941 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700942 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 mScreenBrightness.dump(pw, " mScreenBrightness: ");
944 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
945 mButtonBrightness.dump(pw, " mButtonBrightness: ");
946
947 int N = mLocks.size();
948 pw.println();
949 pw.println("mLocks.size=" + N + ":");
950 for (int i=0; i<N; i++) {
951 WakeLock wl = mLocks.get(i);
952 String type = lockType(wl.flags & LOCK_MASK);
953 String acquireCausesWakeup = "";
954 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
955 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
956 }
957 String activated = "";
958 if (wl.activated) {
959 activated = " activated";
960 }
961 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
962 + activated + " (minState=" + wl.minState + ")");
963 }
964
965 pw.println();
966 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
967 for (PokeLock p: mPokeLocks.values()) {
968 pw.println(" poke lock '" + p.tag + "':"
969 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
970 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700971 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
972 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
974 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
975 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
976 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
977 }
978
979 pw.println();
980 }
981
982 private void setTimeoutLocked(long now, int nextState)
983 {
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500984 if (mBootCompleted) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 mHandler.removeCallbacks(mTimeoutTask);
986 mTimeoutTask.nextState = nextState;
987 long when = now;
988 switch (nextState)
989 {
990 case SCREEN_BRIGHT:
991 when += mKeylightDelay;
992 break;
993 case SCREEN_DIM:
994 if (mDimDelay >= 0) {
995 when += mDimDelay;
996 break;
997 } else {
998 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
999 }
1000 case SCREEN_OFF:
1001 synchronized (mLocks) {
1002 when += mScreenOffDelay;
1003 }
1004 break;
1005 }
1006 if (mSpew) {
1007 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
1008 + " when=" + when);
1009 }
1010 mHandler.postAtTime(mTimeoutTask, when);
1011 mNextTimeout = when; // for debugging
1012 }
1013 }
1014
1015 private void cancelTimerLocked()
1016 {
1017 mHandler.removeCallbacks(mTimeoutTask);
1018 mTimeoutTask.nextState = -1;
1019 }
1020
1021 private class TimeoutTask implements Runnable
1022 {
1023 int nextState; // access should be synchronized on mLocks
1024 public void run()
1025 {
1026 synchronized (mLocks) {
1027 if (mSpew) {
1028 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
1029 }
1030
1031 if (nextState == -1) {
1032 return;
1033 }
1034
1035 mUserState = this.nextState;
1036 setPowerState(this.nextState | mWakeLockState);
1037
1038 long now = SystemClock.uptimeMillis();
1039
1040 switch (this.nextState)
1041 {
1042 case SCREEN_BRIGHT:
1043 if (mDimDelay >= 0) {
1044 setTimeoutLocked(now, SCREEN_DIM);
1045 break;
1046 }
1047 case SCREEN_DIM:
1048 setTimeoutLocked(now, SCREEN_OFF);
1049 break;
1050 }
1051 }
1052 }
1053 }
1054
1055 private void sendNotificationLocked(boolean on, int why)
1056 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001057 if (!on) {
1058 mStillNeedSleepNotification = false;
1059 }
1060
Joe Onorato128e7292009-03-24 18:41:31 -07001061 // Add to the queue.
1062 int index = 0;
1063 while (mBroadcastQueue[index] != -1) {
1064 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 }
Joe Onorato128e7292009-03-24 18:41:31 -07001066 mBroadcastQueue[index] = on ? 1 : 0;
1067 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068
Joe Onorato128e7292009-03-24 18:41:31 -07001069 // If we added it position 2, then there is a pair that can be stripped.
1070 // If we added it position 1 and we're turning the screen off, we can strip
1071 // the pair and do nothing, because the screen is already off, and therefore
1072 // keyguard has already been enabled.
1073 // However, if we added it at position 1 and we're turning it on, then position
1074 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1075 // on, so have to run the queue then.
1076 if (index == 2) {
1077 // Also, while we're collapsing them, if it's going to be an "off," and one
1078 // is off because of user, then use that, regardless of whether it's the first
1079 // or second one.
1080 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
1081 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
1082 }
1083 mBroadcastQueue[0] = on ? 1 : 0;
1084 mBroadcastQueue[1] = -1;
1085 mBroadcastQueue[2] = -1;
1086 index = 0;
1087 }
1088 if (index == 1 && !on) {
1089 mBroadcastQueue[0] = -1;
1090 mBroadcastQueue[1] = -1;
1091 index = -1;
1092 // The wake lock was being held, but we're not actually going to do any
1093 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1095 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001096 }
1097
1098 // Now send the message.
1099 if (index >= 0) {
1100 // Acquire the broadcast wake lock before changing the power
1101 // state. It will be release after the broadcast is sent.
1102 // We always increment the ref count for each notification in the queue
1103 // and always decrement when that notification is handled.
1104 mBroadcastWakeLock.acquire();
1105 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1106 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 }
1108 }
1109
1110 private Runnable mNotificationTask = new Runnable()
1111 {
1112 public void run()
1113 {
Joe Onorato128e7292009-03-24 18:41:31 -07001114 while (true) {
1115 int value;
1116 int why;
1117 WindowManagerPolicy policy;
1118 synchronized (mLocks) {
1119 value = mBroadcastQueue[0];
1120 why = mBroadcastWhy[0];
1121 for (int i=0; i<2; i++) {
1122 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1123 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1124 }
1125 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 }
Joe Onorato128e7292009-03-24 18:41:31 -07001127 if (value == 1) {
1128 mScreenOnStart = SystemClock.uptimeMillis();
1129
1130 policy.screenTurnedOn();
1131 try {
1132 ActivityManagerNative.getDefault().wakingUp();
1133 } catch (RemoteException e) {
1134 // ignore it
1135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136
Joe Onorato128e7292009-03-24 18:41:31 -07001137 if (mSpew) {
1138 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1139 }
1140 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1141 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1142 mScreenOnBroadcastDone, mHandler, 0, null, null);
1143 } else {
1144 synchronized (mLocks) {
1145 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1146 mBroadcastWakeLock.mCount);
1147 mBroadcastWakeLock.release();
1148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 }
1150 }
Joe Onorato128e7292009-03-24 18:41:31 -07001151 else if (value == 0) {
1152 mScreenOffStart = SystemClock.uptimeMillis();
1153
1154 policy.screenTurnedOff(why);
1155 try {
1156 ActivityManagerNative.getDefault().goingToSleep();
1157 } catch (RemoteException e) {
1158 // ignore it.
1159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160
Joe Onorato128e7292009-03-24 18:41:31 -07001161 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1162 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1163 mScreenOffBroadcastDone, mHandler, 0, null, null);
1164 } else {
1165 synchronized (mLocks) {
1166 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1167 mBroadcastWakeLock.mCount);
1168 mBroadcastWakeLock.release();
1169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 }
1171 }
Joe Onorato128e7292009-03-24 18:41:31 -07001172 else {
1173 // If we're in this case, then this handler is running for a previous
1174 // paired transaction. mBroadcastWakeLock will already have been released.
1175 break;
1176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 }
1178 }
1179 };
1180
1181 long mScreenOnStart;
1182 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1183 public void onReceive(Context context, Intent intent) {
1184 synchronized (mLocks) {
1185 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1186 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1187 mBroadcastWakeLock.release();
1188 }
1189 }
1190 };
1191
1192 long mScreenOffStart;
1193 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1194 public void onReceive(Context context, Intent intent) {
1195 synchronized (mLocks) {
1196 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1197 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1198 mBroadcastWakeLock.release();
1199 }
1200 }
1201 };
1202
1203 void logPointerUpEvent() {
1204 if (LOG_TOUCH_DOWNS) {
1205 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1206 mLastTouchDown = 0;
1207 }
1208 }
1209
1210 void logPointerDownEvent() {
1211 if (LOG_TOUCH_DOWNS) {
1212 // If we are not already timing a down/up sequence
1213 if (mLastTouchDown == 0) {
1214 mLastTouchDown = SystemClock.elapsedRealtime();
1215 mTouchCycles++;
1216 }
1217 }
1218 }
1219
1220 /**
1221 * Prevents the screen from turning on even if it *should* turn on due
1222 * to a subsequent full wake lock being acquired.
1223 * <p>
1224 * This is a temporary hack that allows an activity to "cover up" any
1225 * display glitches that happen during the activity's startup
1226 * sequence. (Specifically, this API was added to work around a
1227 * cosmetic bug in the "incoming call" sequence, where the lock screen
1228 * would flicker briefly before the incoming call UI became visible.)
1229 * TODO: There ought to be a more elegant way of doing this,
1230 * probably by having the PowerManager and ActivityManager
1231 * work together to let apps specify that the screen on/off
1232 * state should be synchronized with the Activity lifecycle.
1233 * <p>
1234 * Note that calling preventScreenOn(true) will NOT turn the screen
1235 * off if it's currently on. (This API only affects *future*
1236 * acquisitions of full wake locks.)
1237 * But calling preventScreenOn(false) WILL turn the screen on if
1238 * it's currently off because of a prior preventScreenOn(true) call.
1239 * <p>
1240 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1241 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1242 * call doesn't occur within 5 seconds, we'll turn the screen back on
1243 * ourselves (and log a warning about it); this prevents a buggy app
1244 * from disabling the screen forever.)
1245 * <p>
1246 * TODO: this feature should really be controlled by a new type of poke
1247 * lock (rather than an IPowerManager call).
1248 */
1249 public void preventScreenOn(boolean prevent) {
1250 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1251
1252 synchronized (mLocks) {
1253 if (prevent) {
1254 // First of all, grab a partial wake lock to
1255 // make sure the CPU stays on during the entire
1256 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1257 mPreventScreenOnPartialLock.acquire();
1258
1259 // Post a forceReenableScreen() call (for 5 seconds in the
1260 // future) to make sure the matching preventScreenOn(false) call
1261 // has happened by then.
1262 mHandler.removeCallbacks(mForceReenableScreenTask);
1263 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1264
1265 // Finally, set the flag that prevents the screen from turning on.
1266 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001267 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 mPreventScreenOn = true;
1269 } else {
1270 // (Re)enable the screen.
1271 mPreventScreenOn = false;
1272
1273 // We're "undoing" a the prior preventScreenOn(true) call, so we
1274 // no longer need the 5-second safeguard.
1275 mHandler.removeCallbacks(mForceReenableScreenTask);
1276
1277 // Forcibly turn on the screen if it's supposed to be on. (This
1278 // handles the case where the screen is currently off because of
1279 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001280 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 if (mSpew) {
1282 Log.d(TAG,
1283 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1284 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001285 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001287 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 }
1289 }
1290
1291 // Release the partial wake lock that we held during the
1292 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1293 mPreventScreenOnPartialLock.release();
1294 }
1295 }
1296 }
1297
1298 public void setScreenBrightnessOverride(int brightness) {
1299 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1300
1301 synchronized (mLocks) {
1302 if (mScreenBrightnessOverride != brightness) {
1303 mScreenBrightnessOverride = brightness;
1304 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1305 }
1306 }
1307 }
1308
1309 /**
1310 * Sanity-check that gets called 5 seconds after any call to
1311 * preventScreenOn(true). This ensures that the original call
1312 * is followed promptly by a call to preventScreenOn(false).
1313 */
1314 private void forceReenableScreen() {
1315 // We shouldn't get here at all if mPreventScreenOn is false, since
1316 // we should have already removed any existing
1317 // mForceReenableScreenTask messages...
1318 if (!mPreventScreenOn) {
1319 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1320 return;
1321 }
1322
1323 // Uh oh. It's been 5 seconds since a call to
1324 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1325 // This means the app that called preventScreenOn(true) is either
1326 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1327 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1328 // crashed before doing so.)
1329
1330 // Log a warning, and forcibly turn the screen back on.
1331 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1332 + "Forcing the screen back on...");
1333 preventScreenOn(false);
1334 }
1335
1336 private Runnable mForceReenableScreenTask = new Runnable() {
1337 public void run() {
1338 forceReenableScreen();
1339 }
1340 };
1341
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001342 private int setScreenStateLocked(boolean on) {
1343 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001344 if (err == 0) {
1345 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1346 if (mUseSoftwareAutoBrightness) {
1347 enableLightSensor(on);
1348 if (!on) {
1349 // make sure button and key backlights are off too
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001350 int brightnessMode = (mUseSoftwareAutoBrightness
1351 ? HardwareService.BRIGHTNESS_MODE_SENSOR
1352 : HardwareService.BRIGHTNESS_MODE_USER);
1353 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, 0,
1354 brightnessMode);
1355 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, 0,
1356 brightnessMode);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001357 // clear current value so we will update based on the new conditions
1358 // when the sensor is reenabled.
1359 mLightSensorValue = -1;
1360 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001361 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001362 }
1363 return err;
1364 }
1365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 private void setPowerState(int state)
1367 {
1368 setPowerState(state, false, false);
1369 }
1370
1371 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1372 {
1373 synchronized (mLocks) {
1374 int err;
1375
1376 if (mSpew) {
1377 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1378 + " newState=0x" + Integer.toHexString(newState)
1379 + " noChangeLights=" + noChangeLights);
1380 }
1381
1382 if (noChangeLights) {
1383 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1384 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001385 if (mProximitySensorActive) {
1386 // don't turn on the screen when the proximity sensor lock is held
1387 newState = (newState & ~SCREEN_BRIGHT);
1388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389
1390 if (batteryIsLow()) {
1391 newState |= BATTERY_LOW_BIT;
1392 } else {
1393 newState &= ~BATTERY_LOW_BIT;
1394 }
1395 if (newState == mPowerState) {
1396 return;
1397 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001398
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001399 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 newState |= ALL_BRIGHT;
1401 }
1402
1403 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1404 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1405
Mike Lockwood51b84492009-11-16 21:51:18 -05001406 if (mSpew) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1408 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1409 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1410 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1411 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1412 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1413 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1414 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1415 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1416 + " newScreenOn=" + newScreenOn);
1417 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1418 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1419 }
1420
1421 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001422 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1424 }
1425
1426 if (oldScreenOn != newScreenOn) {
1427 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001428 // When the user presses the power button, we need to always send out the
1429 // notification that it's going to sleep so the keyguard goes on. But
1430 // we can't do that until the screen fades out, so we don't show the keyguard
1431 // too early.
1432 if (mStillNeedSleepNotification) {
1433 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1434 }
1435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 // Turn on the screen UNLESS there was a prior
1437 // preventScreenOn(true) request. (Note that the lifetime
1438 // of a single preventScreenOn() request is limited to 5
1439 // seconds to prevent a buggy app from disabling the
1440 // screen forever; see forceReenableScreen().)
1441 boolean reallyTurnScreenOn = true;
1442 if (mSpew) {
1443 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1444 + mPreventScreenOn);
1445 }
1446
1447 if (mPreventScreenOn) {
1448 if (mSpew) {
1449 Log.d(TAG, "- PREVENTING screen from really turning on!");
1450 }
1451 reallyTurnScreenOn = false;
1452 }
1453 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001454 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 long identity = Binder.clearCallingIdentity();
1456 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001457 mBatteryStats.noteScreenBrightness(
1458 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 mBatteryStats.noteScreenOn();
1460 } catch (RemoteException e) {
1461 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1462 } finally {
1463 Binder.restoreCallingIdentity(identity);
1464 }
1465 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001466 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 // But continue as if we really did turn the screen on...
1468 err = 0;
1469 }
1470
1471 mScreenOnStartTime = SystemClock.elapsedRealtime();
1472 mLastTouchDown = 0;
1473 mTotalTouchDownTime = 0;
1474 mTouchCycles = 0;
1475 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1476 mTotalTouchDownTime, mTouchCycles);
1477 if (err == 0) {
1478 mPowerState |= SCREEN_ON_BIT;
1479 sendNotificationLocked(true, -1);
1480 }
1481 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001482 // cancel light sensor task
1483 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 mScreenOffTime = SystemClock.elapsedRealtime();
1485 long identity = Binder.clearCallingIdentity();
1486 try {
1487 mBatteryStats.noteScreenOff();
1488 } catch (RemoteException e) {
1489 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1490 } finally {
1491 Binder.restoreCallingIdentity(identity);
1492 }
1493 mPowerState &= ~SCREEN_ON_BIT;
1494 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001495 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 } else {
1497 mOffBecauseOfUser = becauseOfUser;
1498 err = 0;
1499 mLastTouchDown = 0;
1500 }
1501 }
1502 }
1503 }
1504 }
1505
Joe Onorato128e7292009-03-24 18:41:31 -07001506 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 // I don't think we need to check the current state here because all of these
1508 // Power.setScreenState and sendNotificationLocked can both handle being
1509 // called multiple times in the same state. -joeo
1510 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1511 mTotalTouchDownTime, mTouchCycles);
1512 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001513 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 if (mScreenOnStartTime != 0) {
1515 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1516 mScreenOnStartTime = 0;
1517 }
1518 if (err == 0) {
1519 int why = becauseOfUser
1520 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1521 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1522 sendNotificationLocked(false, why);
1523 }
1524 return err;
1525 }
1526
1527 private boolean batteryIsLow() {
1528 return (!mIsPowered &&
1529 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1530 }
1531
The Android Open Source Project10592532009-03-18 17:39:46 -07001532 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001533 final int oldState = mPowerState;
1534 final int realDifference = (newState ^ oldState);
1535 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001537 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539
1540 int offMask = 0;
1541 int dimMask = 0;
1542 int onMask = 0;
1543
1544 int preferredBrightness = getPreferredBrightness();
1545 boolean startAnimation = false;
1546
1547 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1548 if (ANIMATE_KEYBOARD_LIGHTS) {
1549 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1550 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001551 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1552 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 } else {
1554 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001555 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1556 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 }
1558 startAnimation = true;
1559 } else {
1560 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001561 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001563 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
1565 }
1566 }
1567
1568 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1569 if (ANIMATE_BUTTON_LIGHTS) {
1570 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1571 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001572 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1573 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 } else {
1575 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001576 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1577 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 }
1579 startAnimation = true;
1580 } else {
1581 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001582 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001584 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 }
1586 }
1587 }
1588
1589 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1590 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001591 int nominalCurrentValue = -1;
1592 // If there was an actual difference in the light state, then
1593 // figure out the "ideal" current value based on the previous
1594 // state. Otherwise, this is a change due to the brightness
1595 // override, so we want to animate from whatever the current
1596 // value is.
1597 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1598 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1599 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1600 nominalCurrentValue = preferredBrightness;
1601 break;
1602 case SCREEN_ON_BIT:
1603 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1604 break;
1605 case 0:
1606 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1607 break;
1608 case SCREEN_BRIGHT_BIT:
1609 default:
1610 // not possible
1611 nominalCurrentValue = (int)mScreenBrightness.curValue;
1612 break;
1613 }
Joe Onorato128e7292009-03-24 18:41:31 -07001614 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001615 int brightness = preferredBrightness;
1616 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1618 // dim or turn off backlight, depending on if the screen is on
1619 // the scale is because the brightness ramp isn't linear and this biases
1620 // it so the later parts take longer.
1621 final float scale = 1.5f;
1622 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1623 if (ratio > 1.0f) ratio = 1.0f;
1624 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1626 // was bright
1627 steps = ANIM_STEPS;
1628 } else {
1629 // was dim
1630 steps = (int)(ANIM_STEPS*ratio*scale);
1631 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001632 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 if ((oldState & SCREEN_ON_BIT) != 0) {
1635 // was bright
1636 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1637 } else {
1638 // was dim
1639 steps = (int)(ANIM_STEPS*ratio);
1640 }
1641 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1642 // If the "stay on while plugged in" option is
1643 // turned on, then the screen will often not
1644 // automatically turn off while plugged in. To
1645 // still have a sense of when it is inactive, we
1646 // will then count going dim as turning off.
1647 mScreenOffTime = SystemClock.elapsedRealtime();
1648 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001649 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001652 long identity = Binder.clearCallingIdentity();
1653 try {
1654 mBatteryStats.noteScreenBrightness(brightness);
1655 } catch (RemoteException e) {
1656 // Nothing interesting to do.
1657 } finally {
1658 Binder.restoreCallingIdentity(identity);
1659 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001660 if (mScreenBrightness.setTargetLocked(brightness,
1661 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1662 startAnimation = true;
1663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 } else {
1665 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1666 // dim or turn off backlight, depending on if the screen is on
1667 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001668 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001670 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 }
1672 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001673 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 }
1675 }
1676 }
1677
1678 if (startAnimation) {
1679 if (mSpew) {
1680 Log.i(TAG, "Scheduling light animator!");
1681 }
1682 mHandler.removeCallbacks(mLightAnimator);
1683 mHandler.post(mLightAnimator);
1684 }
1685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 if (offMask != 0) {
1687 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001688 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 }
1690 if (dimMask != 0) {
1691 int brightness = Power.BRIGHTNESS_DIM;
1692 if ((newState & BATTERY_LOW_BIT) != 0 &&
1693 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1694 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1695 }
1696 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001697 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 }
1699 if (onMask != 0) {
1700 int brightness = getPreferredBrightness();
1701 if ((newState & BATTERY_LOW_BIT) != 0 &&
1702 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1703 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1704 }
1705 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001706 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709
The Android Open Source Project10592532009-03-18 17:39:46 -07001710 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001711 int brightnessMode = (mAutoBrightessEnabled
1712 ? HardwareService.BRIGHTNESS_MODE_SENSOR
1713 : HardwareService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001714 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001715 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value,
1716 brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001717 }
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001718 brightnessMode = (mUseSoftwareAutoBrightness
1719 ? HardwareService.BRIGHTNESS_MODE_SENSOR
1720 : HardwareService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001721 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001722 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value,
1723 brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001724 }
1725 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001726 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value,
1727 brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 }
1730
1731 class BrightnessState {
1732 final int mask;
1733
1734 boolean initialized;
1735 int targetValue;
1736 float curValue;
1737 float delta;
1738 boolean animating;
1739
1740 BrightnessState(int m) {
1741 mask = m;
1742 }
1743
1744 public void dump(PrintWriter pw, String prefix) {
1745 pw.println(prefix + "animating=" + animating
1746 + " targetValue=" + targetValue
1747 + " curValue=" + curValue
1748 + " delta=" + delta);
1749 }
1750
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001751 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001752 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 if (!initialized) {
1754 initialized = true;
1755 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001756 } else if (targetValue == target) {
1757 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 }
1759 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001760 delta = (targetValue -
1761 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1762 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001764 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001766 + " target=" + targetValue + " delta=" + delta
1767 + " nominalCurrentValue=" + nominalCurrentValue
1768 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 }
1770 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001771 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 }
1773
1774 boolean stepLocked() {
1775 if (!animating) return false;
1776 if (false && mSpew) {
1777 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1778 + " target=" + targetValue + " delta=" + delta);
1779 }
1780 curValue += delta;
1781 int curIntValue = (int)curValue;
1782 boolean more = true;
1783 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001784 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 more = false;
1786 } else if (delta > 0) {
1787 if (curIntValue >= targetValue) {
1788 curValue = curIntValue = targetValue;
1789 more = false;
1790 }
1791 } else {
1792 if (curIntValue <= targetValue) {
1793 curValue = curIntValue = targetValue;
1794 more = false;
1795 }
1796 }
1797 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001798 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 animating = more;
1800 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001801 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001802 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
1804 }
1805 return more;
1806 }
1807 }
1808
1809 private class LightAnimator implements Runnable {
1810 public void run() {
1811 synchronized (mLocks) {
1812 long now = SystemClock.uptimeMillis();
1813 boolean more = mScreenBrightness.stepLocked();
1814 if (mKeyboardBrightness.stepLocked()) {
1815 more = true;
1816 }
1817 if (mButtonBrightness.stepLocked()) {
1818 more = true;
1819 }
1820 if (more) {
1821 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1822 }
1823 }
1824 }
1825 }
1826
1827 private int getPreferredBrightness() {
1828 try {
1829 if (mScreenBrightnessOverride >= 0) {
1830 return mScreenBrightnessOverride;
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001831 } else if (mLightSensorBrightness >= 0 && mUseSoftwareAutoBrightness
1832 && mAutoBrightessEnabled) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001833 return mLightSensorBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 }
1835 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1836 SCREEN_BRIGHTNESS);
1837 // Don't let applications turn the screen all the way off
1838 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1839 } catch (SettingNotFoundException snfe) {
1840 return Power.BRIGHTNESS_ON;
1841 }
1842 }
1843
Charles Mendis322591c2009-10-29 11:06:59 -07001844 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 synchronized (mLocks) {
1846 return (mPowerState & SCREEN_ON_BIT) != 0;
1847 }
1848 }
1849
Charles Mendis322591c2009-10-29 11:06:59 -07001850 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 synchronized (mLocks) {
1852 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1853 }
1854 }
1855
Mike Lockwood497087e32009-11-08 18:33:03 -05001856 private boolean isScreenTurningOffLocked() {
1857 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1858 }
1859
Mike Lockwood200b30b2009-09-20 00:23:59 -04001860 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05001861 if (isScreenTurningOffLocked()) {
1862 // cancel animation so userActivity will succeed
1863 mScreenBrightness.animating = false;
1864 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04001865 boolean savedActivityAllowed = mUserActivityAllowed;
1866 mUserActivityAllowed = true;
1867 userActivity(SystemClock.uptimeMillis(), false);
1868 mUserActivityAllowed = savedActivityAllowed;
1869 }
1870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1872 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1873 userActivity(time, noChangeLights, OTHER_EVENT, force);
1874 }
1875
1876 public void userActivity(long time, boolean noChangeLights) {
1877 userActivity(time, noChangeLights, OTHER_EVENT, false);
1878 }
1879
1880 public void userActivity(long time, boolean noChangeLights, int eventType) {
1881 userActivity(time, noChangeLights, eventType, false);
1882 }
1883
1884 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1885 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1886
1887 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001888 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001890 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 }
1892 return;
1893 }
1894
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001895 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1896 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1897 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1898 if (false) {
1899 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1900 }
1901 return;
1902 }
1903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 if (false) {
1905 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1906 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1907 } else {
1908 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1909 }
1910 }
1911
1912 synchronized (mLocks) {
1913 if (mSpew) {
1914 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1915 + " mUserActivityAllowed=" + mUserActivityAllowed
1916 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001917 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1918 + " mProximitySensorActive=" + mProximitySensorActive
1919 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 }
Mike Lockwood05067122009-10-27 23:07:25 -04001921 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05001922 if (isScreenTurningOffLocked()) {
Mike Lockwood05067122009-10-27 23:07:25 -04001923 Log.d(TAG, "ignoring user activity while turning off screen");
1924 return;
1925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 if (mLastEventTime <= time || force) {
1927 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001928 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001929 // Only turn on button backlights if a button was pressed
1930 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05001931 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1933 } else {
1934 // don't clear button/keyboard backlights when the screen is touched.
1935 mUserState |= SCREEN_BRIGHT;
1936 }
1937
Dianne Hackborn617f8772009-03-31 15:04:46 -07001938 int uid = Binder.getCallingUid();
1939 long ident = Binder.clearCallingIdentity();
1940 try {
1941 mBatteryStats.noteUserActivity(uid, eventType);
1942 } catch (RemoteException e) {
1943 // Ignore
1944 } finally {
1945 Binder.restoreCallingIdentity(ident);
1946 }
1947
Michael Chane96440f2009-05-06 10:27:36 -07001948 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1950 setTimeoutLocked(time, SCREEN_BRIGHT);
1951 }
1952 }
1953 }
1954 }
1955
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001956 private int getAutoBrightnessValue(int sensorValue, int[] values) {
1957 try {
1958 int i;
1959 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
1960 if (sensorValue < mAutoBrightnessLevels[i]) {
1961 break;
1962 }
1963 }
1964 return values[i];
1965 } catch (Exception e) {
1966 // guard against null pointer or index out of bounds errors
1967 Log.e(TAG, "getAutoBrightnessValue", e);
1968 return 255;
1969 }
1970 }
1971
Mike Lockwood20f87d72009-11-05 16:08:51 -05001972 private Runnable mProximityTask = new Runnable() {
1973 public void run() {
1974 synchronized (mLocks) {
1975 if (mProximityPendingValue != -1) {
1976 proximityChangedLocked(mProximityPendingValue == 1);
1977 mProximityPendingValue = -1;
1978 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05001979 if (mProximityPartialLock.isHeld()) {
1980 mProximityPartialLock.release();
1981 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05001982 }
1983 }
1984 };
1985
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001986 private Runnable mAutoBrightnessTask = new Runnable() {
1987 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04001988 synchronized (mLocks) {
1989 int value = (int)mLightSensorPendingValue;
1990 if (value >= 0) {
1991 mLightSensorPendingValue = -1;
1992 lightSensorChangedLocked(value);
1993 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001994 }
1995 }
1996 };
1997
1998 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001999 if (mDebugLightSensor) {
2000 Log.d(TAG, "lightSensorChangedLocked " + value);
2001 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002002
2003 if (mLightSensorValue != value) {
2004 mLightSensorValue = value;
2005 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
2006 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
2007 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002008 int keyboardValue;
2009 if (mKeyboardVisible) {
2010 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2011 } else {
2012 keyboardValue = 0;
2013 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002014 mLightSensorBrightness = lcdValue;
2015
2016 if (mDebugLightSensor) {
2017 Log.d(TAG, "lcdValue " + lcdValue);
2018 Log.d(TAG, "buttonValue " + buttonValue);
2019 Log.d(TAG, "keyboardValue " + keyboardValue);
2020 }
2021
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002022 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002023 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002024 if (ANIMATE_SCREEN_LIGHTS) {
2025 if (mScreenBrightness.setTargetLocked(lcdValue,
2026 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2027 (int)mScreenBrightness.curValue)) {
2028 startAnimation = true;
2029 }
2030 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002031 int brightnessMode = (mAutoBrightessEnabled
2032 ? HardwareService.BRIGHTNESS_MODE_SENSOR
2033 : HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002034 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002035 lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002036 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002037 }
2038 if (ANIMATE_BUTTON_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002039 if (mButtonBrightness.setTargetLocked(buttonValue,
2040 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2041 (int)mButtonBrightness.curValue)) {
2042 startAnimation = true;
2043 }
2044 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002045 int brightnessMode = (mUseSoftwareAutoBrightness
2046 ? HardwareService.BRIGHTNESS_MODE_SENSOR
2047 : HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002048 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002049 buttonValue, brightnessMode);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002050 }
2051 if (ANIMATE_KEYBOARD_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002052 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2053 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2054 (int)mKeyboardBrightness.curValue)) {
2055 startAnimation = true;
2056 }
2057 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002058 int brightnessMode = (mUseSoftwareAutoBrightness
2059 ? HardwareService.BRIGHTNESS_MODE_SENSOR
2060 : HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002061 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002062 keyboardValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002063 }
2064 if (startAnimation) {
2065 if (mDebugLightSensor) {
2066 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
2067 }
2068 mHandler.removeCallbacks(mLightAnimator);
2069 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002070 }
2071 }
2072 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002073 }
2074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 /**
2076 * The user requested that we go to sleep (probably with the power button).
2077 * This overrides all wake locks that are held.
2078 */
2079 public void goToSleep(long time)
2080 {
2081 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2082 synchronized (mLocks) {
2083 goToSleepLocked(time);
2084 }
2085 }
2086
2087 /**
2088 * Returns the time the screen has been on since boot, in millis.
2089 * @return screen on time
2090 */
2091 public long getScreenOnTime() {
2092 synchronized (mLocks) {
2093 if (mScreenOnStartTime == 0) {
2094 return mScreenOnTime;
2095 } else {
2096 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
2097 }
2098 }
2099 }
2100
2101 private void goToSleepLocked(long time) {
2102
2103 if (mLastEventTime <= time) {
2104 mLastEventTime = time;
2105 // cancel all of the wake locks
2106 mWakeLockState = SCREEN_OFF;
2107 int N = mLocks.size();
2108 int numCleared = 0;
2109 for (int i=0; i<N; i++) {
2110 WakeLock wl = mLocks.get(i);
2111 if (isScreenLock(wl.flags)) {
2112 mLocks.get(i).activated = false;
2113 numCleared++;
2114 }
2115 }
2116 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002117 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 mUserState = SCREEN_OFF;
2119 setPowerState(SCREEN_OFF, false, true);
2120 cancelTimerLocked();
2121 }
2122 }
2123
2124 public long timeSinceScreenOn() {
2125 synchronized (mLocks) {
2126 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2127 return 0;
2128 }
2129 return SystemClock.elapsedRealtime() - mScreenOffTime;
2130 }
2131 }
2132
2133 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002134 synchronized (mLocks) {
2135 if (mSpew) {
2136 Log.d(TAG, "setKeyboardVisibility: " + visible);
2137 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002138 if (mKeyboardVisible != visible) {
2139 mKeyboardVisible = visible;
2140 // don't signal user activity if the screen is off; other code
2141 // will take care of turning on due to a true change to the lid
2142 // switch and synchronized with the lock screen.
2143 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002144 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002145 // force recompute of backlight values
2146 if (mLightSensorValue >= 0) {
2147 int value = (int)mLightSensorValue;
2148 mLightSensorValue = -1;
2149 lightSensorChangedLocked(value);
2150 }
2151 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002152 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2153 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002154 }
2155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 }
2157
2158 /**
2159 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002160 * When disabling user activity we also reset user power state so the keyguard can reset its
2161 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 */
2163 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002164 if (mSpew) {
2165 Log.d(TAG, "enableUserActivity " + enabled);
2166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 synchronized (mLocks) {
2168 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002169 if (!enabled) {
2170 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2171 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 }
2174 }
2175
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002176 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002177 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002178 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002179 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002180 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002181 // force recompute of backlight values
2182 if (mLightSensorValue >= 0) {
2183 int value = (int)mLightSensorValue;
2184 mLightSensorValue = -1;
2185 lightSensorChangedLocked(value);
2186 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002187 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002188 }
2189 }
2190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 /** Sets the screen off timeouts:
2192 * mKeylightDelay
2193 * mDimDelay
2194 * mScreenOffDelay
2195 * */
2196 private void setScreenOffTimeoutsLocked() {
2197 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
2198 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
2199 mDimDelay = -1;
2200 mScreenOffDelay = 0;
2201 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2202 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2203 mDimDelay = -1;
2204 mScreenOffDelay = 0;
2205 } else {
2206 int totalDelay = mTotalDelaySetting;
2207 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2208 if (totalDelay < 0) {
2209 mScreenOffDelay = Integer.MAX_VALUE;
2210 } else if (mKeylightDelay < totalDelay) {
2211 // subtract the time that the keylight delay. This will give us the
2212 // remainder of the time that we need to sleep to get the accurate
2213 // screen off timeout.
2214 mScreenOffDelay = totalDelay - mKeylightDelay;
2215 } else {
2216 mScreenOffDelay = 0;
2217 }
2218 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2219 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2220 mScreenOffDelay = LONG_DIM_TIME;
2221 } else {
2222 mDimDelay = -1;
2223 }
2224 }
2225 if (mSpew) {
2226 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2227 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2228 + " mDimScreen=" + mDimScreen);
2229 }
2230 }
2231
2232 /**
2233 * Refreshes cached Gservices settings. Called once on startup, and
2234 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
2235 * GservicesChangedReceiver).
2236 */
2237 private void updateGservicesValues() {
2238 mShortKeylightDelay = Settings.Gservices.getInt(
2239 mContext.getContentResolver(),
2240 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
2241 SHORT_KEYLIGHT_DELAY_DEFAULT);
2242 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
2243 }
2244
2245 /**
2246 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
2247 * which tells us we need to refresh our cached Gservices settings.
2248 */
2249 private class GservicesChangedReceiver extends BroadcastReceiver {
2250 @Override
2251 public void onReceive(Context context, Intent intent) {
2252 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
2253 updateGservicesValues();
2254 }
2255 }
2256
2257 private class LockList extends ArrayList<WakeLock>
2258 {
2259 void addLock(WakeLock wl)
2260 {
2261 int index = getIndex(wl.binder);
2262 if (index < 0) {
2263 this.add(wl);
2264 }
2265 }
2266
2267 WakeLock removeLock(IBinder binder)
2268 {
2269 int index = getIndex(binder);
2270 if (index >= 0) {
2271 return this.remove(index);
2272 } else {
2273 return null;
2274 }
2275 }
2276
2277 int getIndex(IBinder binder)
2278 {
2279 int N = this.size();
2280 for (int i=0; i<N; i++) {
2281 if (this.get(i).binder == binder) {
2282 return i;
2283 }
2284 }
2285 return -1;
2286 }
2287
2288 int gatherState()
2289 {
2290 int result = 0;
2291 int N = this.size();
2292 for (int i=0; i<N; i++) {
2293 WakeLock wl = this.get(i);
2294 if (wl.activated) {
2295 if (isScreenLock(wl.flags)) {
2296 result |= wl.minState;
2297 }
2298 }
2299 }
2300 return result;
2301 }
Michael Chane96440f2009-05-06 10:27:36 -07002302
2303 int reactivateScreenLocksLocked()
2304 {
2305 int result = 0;
2306 int N = this.size();
2307 for (int i=0; i<N; i++) {
2308 WakeLock wl = this.get(i);
2309 if (isScreenLock(wl.flags)) {
2310 wl.activated = true;
2311 result |= wl.minState;
2312 }
2313 }
2314 return result;
2315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002316 }
2317
2318 void setPolicy(WindowManagerPolicy p) {
2319 synchronized (mLocks) {
2320 mPolicy = p;
2321 mLocks.notifyAll();
2322 }
2323 }
2324
2325 WindowManagerPolicy getPolicyLocked() {
2326 while (mPolicy == null || !mDoneBooting) {
2327 try {
2328 mLocks.wait();
2329 } catch (InterruptedException e) {
2330 // Ignore
2331 }
2332 }
2333 return mPolicy;
2334 }
2335
2336 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002337 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2338 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2339 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002340 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002341 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002342 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002343 }
2344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 synchronized (mLocks) {
2346 Log.d(TAG, "system ready!");
2347 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002348 long identity = Binder.clearCallingIdentity();
2349 try {
2350 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2351 mBatteryStats.noteScreenOn();
2352 } catch (RemoteException e) {
2353 // Nothing interesting to do.
2354 } finally {
2355 Binder.restoreCallingIdentity(identity);
2356 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002357 }
2358 }
2359
2360 void bootCompleted() {
2361 Log.d(TAG, "bootCompleted");
2362 synchronized (mLocks) {
2363 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2365 updateWakeLockLocked();
2366 mLocks.notifyAll();
2367 }
2368 }
2369
2370 public void monitor() {
2371 synchronized (mLocks) { }
2372 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002373
2374 public int getSupportedWakeLockFlags() {
2375 int result = PowerManager.PARTIAL_WAKE_LOCK
2376 | PowerManager.FULL_WAKE_LOCK
2377 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2378
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002379 if (mProximitySensor != null) {
2380 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2381 }
2382
2383 return result;
2384 }
2385
Mike Lockwood237a2992009-09-15 14:42:16 -04002386 public void setBacklightBrightness(int brightness) {
2387 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2388 // Don't let applications turn the screen all the way off
2389 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002390 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness,
2391 HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwooddf024922009-10-29 21:29:15 -04002392 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002393 (mKeyboardVisible ? brightness : 0), HardwareService.BRIGHTNESS_MODE_USER);
2394 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness,
2395 HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwood237a2992009-09-15 14:42:16 -04002396 long identity = Binder.clearCallingIdentity();
2397 try {
2398 mBatteryStats.noteScreenBrightness(brightness);
2399 } catch (RemoteException e) {
2400 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2401 } finally {
2402 Binder.restoreCallingIdentity(identity);
2403 }
2404
2405 // update our animation state
2406 if (ANIMATE_SCREEN_LIGHTS) {
2407 mScreenBrightness.curValue = brightness;
2408 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002409 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002410 }
2411 if (ANIMATE_KEYBOARD_LIGHTS) {
2412 mKeyboardBrightness.curValue = brightness;
2413 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002414 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002415 }
2416 if (ANIMATE_BUTTON_LIGHTS) {
2417 mButtonBrightness.curValue = brightness;
2418 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002419 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002420 }
2421 }
2422
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002423 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002424 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002425 Log.d(TAG, "enableProximityLockLocked");
2426 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002427 if (!mProximitySensorEnabled) {
2428 // clear calling identity so sensor manager battery stats are accurate
2429 long identity = Binder.clearCallingIdentity();
2430 try {
2431 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2432 SensorManager.SENSOR_DELAY_NORMAL);
2433 mProximitySensorEnabled = true;
2434 } finally {
2435 Binder.restoreCallingIdentity(identity);
2436 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002437 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002438 }
2439
2440 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002441 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002442 Log.d(TAG, "disableProximityLockLocked");
2443 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002444 if (mProximitySensorEnabled) {
2445 // clear calling identity so sensor manager battery stats are accurate
2446 long identity = Binder.clearCallingIdentity();
2447 try {
2448 mSensorManager.unregisterListener(mProximityListener);
2449 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002450 if (mProximityPartialLock.isHeld()) {
2451 mProximityPartialLock.release();
2452 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002453 mProximitySensorEnabled = false;
2454 } finally {
2455 Binder.restoreCallingIdentity(identity);
2456 }
2457 if (mProximitySensorActive) {
2458 mProximitySensorActive = false;
2459 forceUserActivityLocked();
2460 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002461 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002462 }
2463
Mike Lockwood20f87d72009-11-05 16:08:51 -05002464 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002465 if (mDebugProximitySensor) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002466 Log.d(TAG, "proximityChangedLocked, active: " + active);
2467 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002468 if (!mProximitySensorEnabled) {
2469 Log.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002470 return;
2471 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002472 if (active) {
2473 goToSleepLocked(SystemClock.uptimeMillis());
2474 mProximitySensorActive = true;
2475 } else {
2476 // proximity sensor negative events trigger as user activity.
2477 // temporarily set mUserActivityAllowed to true so this will work
2478 // even when the keyguard is on.
2479 mProximitySensorActive = false;
2480 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002481
2482 if (mProximityWakeLockCount == 0) {
2483 // disable sensor if we have no listeners left after proximity negative
2484 disableProximityLockLocked();
2485 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002486 }
2487 }
2488
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002489 private void enableLightSensor(boolean enable) {
2490 if (mDebugLightSensor) {
2491 Log.d(TAG, "enableLightSensor " + enable);
2492 }
2493 if (mSensorManager != null && mLightSensorEnabled != enable) {
2494 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002495 // clear calling identity so sensor manager battery stats are accurate
2496 long identity = Binder.clearCallingIdentity();
2497 try {
2498 if (enable) {
2499 mSensorManager.registerListener(mLightListener, mLightSensor,
2500 SensorManager.SENSOR_DELAY_NORMAL);
2501 } else {
2502 mSensorManager.unregisterListener(mLightListener);
2503 mHandler.removeCallbacks(mAutoBrightnessTask);
2504 }
2505 } finally {
2506 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002507 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002508 }
2509 }
2510
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002511 SensorEventListener mProximityListener = new SensorEventListener() {
2512 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002513 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002514 synchronized (mLocks) {
2515 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002516 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2517 mLastProximityEventTime = milliseconds;
2518 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002519 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002520
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002521 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002522 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2523 distance < mProximitySensor.getMaximumRange());
2524
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002525 if (mDebugProximitySensor) {
2526 Log.d(TAG, "mProximityListener.onSensorChanged active: " + active);
2527 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002528 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2529 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2530 mProximityPendingValue = (active ? 1 : 0);
2531 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002532 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002533 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002534 // process the value immediately
2535 mProximityPendingValue = -1;
2536 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002537 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002538
2539 // update mProximityPartialLock state
2540 boolean held = mProximityPartialLock.isHeld();
2541 if (!held && proximityTaskQueued) {
2542 // hold wakelock until mProximityTask runs
2543 mProximityPartialLock.acquire();
2544 } else if (held && !proximityTaskQueued) {
2545 mProximityPartialLock.release();
2546 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002547 }
2548 }
2549
2550 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2551 // ignore
2552 }
2553 };
2554
2555 SensorEventListener mLightListener = new SensorEventListener() {
2556 public void onSensorChanged(SensorEvent event) {
2557 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002558 // ignore light sensor while screen is turning off
2559 if (isScreenTurningOffLocked()) {
2560 return;
2561 }
2562
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002563 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002564 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002565 if (mDebugLightSensor) {
2566 Log.d(TAG, "onSensorChanged: light value: " + value);
2567 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002568 mHandler.removeCallbacks(mAutoBrightnessTask);
2569 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002570 if (mLightSensorValue == -1 ||
2571 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2572 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002573 lightSensorChangedLocked(value);
2574 } else {
2575 // delay processing to debounce the sensor
2576 mLightSensorPendingValue = value;
2577 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2578 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002579 } else {
2580 mLightSensorPendingValue = -1;
2581 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002582 }
2583 }
2584
2585 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2586 // ignore
2587 }
2588 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589}