blob: e1425d444c345ce2bc18f731d16b180a015c55dc [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;
157 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700158 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
159 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private int mPartialCount = 0;
161 private int mPowerState;
162 private boolean mOffBecauseOfUser;
163 private int mUserState;
164 private boolean mKeyboardVisible = false;
165 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500166 private int mProximityWakeLockCount = 0;
167 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700168 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500169 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
170 private long mLastProximityEventTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 private int mTotalDelaySetting;
172 private int mKeylightDelay;
173 private int mDimDelay;
174 private int mScreenOffDelay;
175 private int mWakeLockState;
176 private long mLastEventTime = 0;
177 private long mScreenOffTime;
178 private volatile WindowManagerPolicy mPolicy;
179 private final LockList mLocks = new LockList();
180 private Intent mScreenOffIntent;
181 private Intent mScreenOnIntent;
The Android Open Source Project10592532009-03-18 17:39:46 -0700182 private HardwareService mHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 private Context mContext;
184 private UnsynchronizedWakeLock mBroadcastWakeLock;
185 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
186 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
187 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
188 private HandlerThread mHandlerThread;
189 private Handler mHandler;
190 private TimeoutTask mTimeoutTask = new TimeoutTask();
191 private LightAnimator mLightAnimator = new LightAnimator();
192 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700193 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700195 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700197 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700198 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 private boolean mIsPowered = false;
200 private IActivityManager mActivityService;
201 private IBatteryStats mBatteryStats;
202 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700203 private SensorManager mSensorManager;
204 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400205 private Sensor mLightSensor;
206 private boolean mLightSensorEnabled;
207 private float mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700208 private float mLightSensorPendingValue = -1;
209 private int mLightSensorBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 private boolean mDimScreen = true;
211 private long mNextTimeout;
212 private volatile int mPokey = 0;
213 private volatile boolean mPokeAwakeOnSet = false;
214 private volatile boolean mInitComplete = false;
215 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500216 // mScreenOnTime and mScreenOnStartTime are used for computing total time screen
217 // has been on since boot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 private long mScreenOnTime;
219 private long mScreenOnStartTime;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500220 // mLastScreenOnTime is the time the screen was last turned on
221 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 private boolean mPreventScreenOn;
223 private int mScreenBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400224 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700225 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700226 private int[] mAutoBrightnessLevels;
227 private int[] mLcdBacklightValues;
228 private int[] mButtonBacklightValues;
229 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500230 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
232 // Used when logging number and duration of touch-down cycles
233 private long mTotalTouchDownTime;
234 private long mLastTouchDown;
235 private int mTouchCycles;
236
237 // could be either static or controllable at runtime
238 private static final boolean mSpew = false;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500239 private static final boolean mDebugProximitySensor = (true || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400240 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 /*
243 static PrintStream mLog;
244 static {
245 try {
246 mLog = new PrintStream("/data/power.log");
247 }
248 catch (FileNotFoundException e) {
249 android.util.Log.e(TAG, "Life is hard", e);
250 }
251 }
252 static class Log {
253 static void d(String tag, String s) {
254 mLog.println(s);
255 android.util.Log.d(tag, s);
256 }
257 static void i(String tag, String s) {
258 mLog.println(s);
259 android.util.Log.i(tag, s);
260 }
261 static void w(String tag, String s) {
262 mLog.println(s);
263 android.util.Log.w(tag, s);
264 }
265 static void e(String tag, String s) {
266 mLog.println(s);
267 android.util.Log.e(tag, s);
268 }
269 }
270 */
271
272 /**
273 * This class works around a deadlock between the lock in PowerManager.WakeLock
274 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
275 * mToken object so it can be accessed from any thread, but it calls into here
276 * with its lock held. This class is essentially a reimplementation of
277 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
278 * only call it with our own locks held.
279 */
280 private class UnsynchronizedWakeLock {
281 int mFlags;
282 String mTag;
283 IBinder mToken;
284 int mCount = 0;
285 boolean mRefCounted;
286
287 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
288 mFlags = flags;
289 mTag = tag;
290 mToken = new Binder();
291 mRefCounted = refCounted;
292 }
293
294 public void acquire() {
295 if (!mRefCounted || mCount++ == 0) {
296 long ident = Binder.clearCallingIdentity();
297 try {
298 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
299 MY_UID, mTag);
300 } finally {
301 Binder.restoreCallingIdentity(ident);
302 }
303 }
304 }
305
306 public void release() {
307 if (!mRefCounted || --mCount == 0) {
308 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
309 }
310 if (mCount < 0) {
311 throw new RuntimeException("WakeLock under-locked " + mTag);
312 }
313 }
314
315 public String toString() {
316 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
317 + " mCount=" + mCount + ")";
318 }
319 }
320
321 private final class BatteryReceiver extends BroadcastReceiver {
322 @Override
323 public void onReceive(Context context, Intent intent) {
324 synchronized (mLocks) {
325 boolean wasPowered = mIsPowered;
326 mIsPowered = mBatteryService.isPowered();
327
328 if (mIsPowered != wasPowered) {
329 // update mStayOnWhilePluggedIn wake lock
330 updateWakeLockLocked();
331
332 // treat plugging and unplugging the devices as a user activity.
333 // users find it disconcerting when they unplug the device
334 // and it shuts off right away.
335 // temporarily set mUserActivityAllowed to true so this will work
336 // even when the keyguard is on.
337 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400338 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 }
340 }
341 }
342 }
343 }
344
345 /**
346 * Set the setting that determines whether the device stays on when plugged in.
347 * The argument is a bit string, with each bit specifying a power source that,
348 * when the device is connected to that source, causes the device to stay on.
349 * See {@link android.os.BatteryManager} for the list of power sources that
350 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
351 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
352 * @param val an {@code int} containing the bits that specify which power sources
353 * should cause the device to stay on.
354 */
355 public void setStayOnSetting(int val) {
356 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
357 Settings.System.putInt(mContext.getContentResolver(),
358 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
359 }
360
361 private class SettingsObserver implements Observer {
362 private int getInt(String name) {
363 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
364 }
365
366 public void update(Observable o, Object arg) {
367 synchronized (mLocks) {
368 // STAY_ON_WHILE_PLUGGED_IN
369 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
370 updateWakeLockLocked();
371
372 // SCREEN_OFF_TIMEOUT
373 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
374
375 // DIM_SCREEN
376 //mDimScreen = getInt(DIM_SCREEN) != 0;
377
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700378 // SCREEN_BRIGHTNESS_MODE
379 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 // recalculate everything
382 setScreenOffTimeoutsLocked();
383 }
384 }
385 }
386
387 PowerManagerService()
388 {
389 // Hack to get our uid... should have a func for this.
390 long token = Binder.clearCallingIdentity();
391 MY_UID = Binder.getCallingUid();
392 Binder.restoreCallingIdentity(token);
393
394 // XXX remove this when the kernel doesn't timeout wake locks
395 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
396
397 // assume nothing is on yet
398 mUserState = mPowerState = 0;
399
400 // Add ourself to the Watchdog monitors.
401 Watchdog.getInstance().addMonitor(this);
402 mScreenOnStartTime = SystemClock.elapsedRealtime();
403 }
404
405 private ContentQueryMap mSettings;
406
The Android Open Source Project10592532009-03-18 17:39:46 -0700407 void init(Context context, HardwareService hardware, IActivityManager activity,
408 BatteryService battery) {
409 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 mContext = context;
411 mActivityService = activity;
412 mBatteryStats = BatteryStatsService.getService();
413 mBatteryService = battery;
414
415 mHandlerThread = new HandlerThread("PowerManagerService") {
416 @Override
417 protected void onLooperPrepared() {
418 super.onLooperPrepared();
419 initInThread();
420 }
421 };
422 mHandlerThread.start();
423
424 synchronized (mHandlerThread) {
425 while (!mInitComplete) {
426 try {
427 mHandlerThread.wait();
428 } catch (InterruptedException e) {
429 // Ignore
430 }
431 }
432 }
433 }
434
435 void initInThread() {
436 mHandler = new Handler();
437
438 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700439 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
441 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
442 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
443 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
444 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
445 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
446
447 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
448 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
449 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
450 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
451
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700452 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400453
454 // read settings for auto-brightness
455 mUseSoftwareAutoBrightness = resources.getBoolean(
456 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400457 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700458 mAutoBrightnessLevels = resources.getIntArray(
459 com.android.internal.R.array.config_autoBrightnessLevels);
460 mLcdBacklightValues = resources.getIntArray(
461 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
462 mButtonBacklightValues = resources.getIntArray(
463 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
464 mKeyboardBacklightValues = resources.getIntArray(
465 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500466 mLightSensorWarmupTime = resources.getInteger(
467 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700468 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700469
470 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
472 "(" + Settings.System.NAME + "=?) or ("
473 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700474 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700476 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
477 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 null);
479 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
480 SettingsObserver settingsObserver = new SettingsObserver();
481 mSettings.addObserver(settingsObserver);
482
483 // pretend that the settings changed so we will get their initial state
484 settingsObserver.update(mSettings, null);
485
486 // register for the battery changed notifications
487 IntentFilter filter = new IntentFilter();
488 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
489 mContext.registerReceiver(new BatteryReceiver(), filter);
490
491 // Listen for Gservices changes
492 IntentFilter gservicesChangedFilter =
493 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
494 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
495 // And explicitly do the initial update of our cached settings
496 updateGservicesValues();
497
Mike Lockwood4984e732009-11-01 08:16:33 -0500498 if (mUseSoftwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400499 // turn the screen on
500 setPowerState(SCREEN_BRIGHT);
501 } else {
502 // turn everything on
503 setPowerState(ALL_BRIGHT);
504 }
Dan Murphy951764b2009-08-27 14:59:03 -0500505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 synchronized (mHandlerThread) {
507 mInitComplete = true;
508 mHandlerThread.notifyAll();
509 }
510 }
511
512 private class WakeLock implements IBinder.DeathRecipient
513 {
514 WakeLock(int f, IBinder b, String t, int u) {
515 super();
516 flags = f;
517 binder = b;
518 tag = t;
519 uid = u == MY_UID ? Process.SYSTEM_UID : u;
520 if (u != MY_UID || (
521 !"KEEP_SCREEN_ON_FLAG".equals(tag)
522 && !"KeyInputQueue".equals(tag))) {
523 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
524 ? BatteryStats.WAKE_TYPE_PARTIAL
525 : BatteryStats.WAKE_TYPE_FULL;
526 } else {
527 monitorType = -1;
528 }
529 try {
530 b.linkToDeath(this, 0);
531 } catch (RemoteException e) {
532 binderDied();
533 }
534 }
535 public void binderDied() {
536 synchronized (mLocks) {
537 releaseWakeLockLocked(this.binder, true);
538 }
539 }
540 final int flags;
541 final IBinder binder;
542 final String tag;
543 final int uid;
544 final int monitorType;
545 boolean activated = true;
546 int minState;
547 }
548
549 private void updateWakeLockLocked() {
550 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
551 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
552 mStayOnWhilePluggedInScreenDimLock.acquire();
553 mStayOnWhilePluggedInPartialLock.acquire();
554 } else {
555 mStayOnWhilePluggedInScreenDimLock.release();
556 mStayOnWhilePluggedInPartialLock.release();
557 }
558 }
559
560 private boolean isScreenLock(int flags)
561 {
562 int n = flags & LOCK_MASK;
563 return n == PowerManager.FULL_WAKE_LOCK
564 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
565 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
566 }
567
568 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700570 if (uid != Process.myUid()) {
571 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 long ident = Binder.clearCallingIdentity();
574 try {
575 synchronized (mLocks) {
576 acquireWakeLockLocked(flags, lock, uid, tag);
577 }
578 } finally {
579 Binder.restoreCallingIdentity(ident);
580 }
581 }
582
583 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
584 int acquireUid = -1;
585 String acquireName = null;
586 int acquireType = -1;
587
588 if (mSpew) {
589 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
590 }
591
592 int index = mLocks.getIndex(lock);
593 WakeLock wl;
594 boolean newlock;
595 if (index < 0) {
596 wl = new WakeLock(flags, lock, tag, uid);
597 switch (wl.flags & LOCK_MASK)
598 {
599 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500600 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400601 wl.minState = SCREEN_BRIGHT;
602 } else {
603 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 break;
606 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
607 wl.minState = SCREEN_BRIGHT;
608 break;
609 case PowerManager.SCREEN_DIM_WAKE_LOCK:
610 wl.minState = SCREEN_DIM;
611 break;
612 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700613 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 break;
615 default:
616 // just log and bail. we're in the server, so don't
617 // throw an exception.
618 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
619 + " flags=" + flags);
620 return;
621 }
622 mLocks.addLock(wl);
623 newlock = true;
624 } else {
625 wl = mLocks.get(index);
626 newlock = false;
627 }
628 if (isScreenLock(flags)) {
629 // if this causes a wakeup, we reactivate all of the locks and
630 // set it to whatever they want. otherwise, we modulate that
631 // by the current state so we never turn it more on than
632 // it already is.
633 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700634 int oldWakeLockState = mWakeLockState;
635 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 if (mSpew) {
637 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700638 + " mWakeLockState=0x"
639 + Integer.toHexString(mWakeLockState)
640 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 } else {
643 if (mSpew) {
644 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
645 + " mLocks.gatherState()=0x"
646 + Integer.toHexString(mLocks.gatherState())
647 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
648 }
649 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
650 }
651 setPowerState(mWakeLockState | mUserState);
652 }
653 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
654 if (newlock) {
655 mPartialCount++;
656 if (mPartialCount == 1) {
657 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
658 }
659 }
660 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700661 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500662 mProximityWakeLockCount++;
663 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700664 enableProximityLockLocked();
665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 }
667 if (newlock) {
668 acquireUid = wl.uid;
669 acquireName = wl.tag;
670 acquireType = wl.monitorType;
671 }
672
673 if (acquireType >= 0) {
674 try {
675 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
676 } catch (RemoteException e) {
677 // Ignore
678 }
679 }
680 }
681
682 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700683 int uid = Binder.getCallingUid();
684 if (uid != Process.myUid()) {
685 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687
688 synchronized (mLocks) {
689 releaseWakeLockLocked(lock, false);
690 }
691 }
692
693 private void releaseWakeLockLocked(IBinder lock, boolean death) {
694 int releaseUid;
695 String releaseName;
696 int releaseType;
697
698 WakeLock wl = mLocks.removeLock(lock);
699 if (wl == null) {
700 return;
701 }
702
703 if (mSpew) {
704 Log.d(TAG, "releaseWakeLock flags=0x"
705 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
706 }
707
708 if (isScreenLock(wl.flags)) {
709 mWakeLockState = mLocks.gatherState();
710 // goes in the middle to reduce flicker
711 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
712 userActivity(SystemClock.uptimeMillis(), false);
713 }
714 setPowerState(mWakeLockState | mUserState);
715 }
716 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
717 mPartialCount--;
718 if (mPartialCount == 0) {
719 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
720 Power.releaseWakeLock(PARTIAL_NAME);
721 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700722 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500723 mProximityWakeLockCount--;
724 if (mProximityWakeLockCount == 0) {
725 if (mProximitySensorActive) {
726 // wait for proximity sensor to go negative before disabling sensor
727 if (mDebugProximitySensor) {
728 Log.d(TAG, "waiting for proximity sensor to go negative");
729 }
730 } else {
731 disableProximityLockLocked();
732 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 }
735 // Unlink the lock from the binder.
736 wl.binder.unlinkToDeath(wl, 0);
737 releaseUid = wl.uid;
738 releaseName = wl.tag;
739 releaseType = wl.monitorType;
740
741 if (releaseType >= 0) {
742 long origId = Binder.clearCallingIdentity();
743 try {
744 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
745 } catch (RemoteException e) {
746 // Ignore
747 } finally {
748 Binder.restoreCallingIdentity(origId);
749 }
750 }
751 }
752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 private class PokeLock implements IBinder.DeathRecipient
754 {
755 PokeLock(int p, IBinder b, String t) {
756 super();
757 this.pokey = p;
758 this.binder = b;
759 this.tag = t;
760 try {
761 b.linkToDeath(this, 0);
762 } catch (RemoteException e) {
763 binderDied();
764 }
765 }
766 public void binderDied() {
767 setPokeLock(0, this.binder, this.tag);
768 }
769 int pokey;
770 IBinder binder;
771 String tag;
772 boolean awakeOnSet;
773 }
774
775 public void setPokeLock(int pokey, IBinder token, String tag) {
776 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
777 if (token == null) {
778 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
779 return;
780 }
781
782 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
783 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
784 + " and POKE_LOCK_MEDIUM_TIMEOUT");
785 }
786
787 synchronized (mLocks) {
788 if (pokey != 0) {
789 PokeLock p = mPokeLocks.get(token);
790 int oldPokey = 0;
791 if (p != null) {
792 oldPokey = p.pokey;
793 p.pokey = pokey;
794 } else {
795 p = new PokeLock(pokey, token, tag);
796 mPokeLocks.put(token, p);
797 }
798 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
799 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
800 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
801 p.awakeOnSet = true;
802 }
803 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700804 PokeLock rLock = mPokeLocks.remove(token);
805 if (rLock != null) {
806 token.unlinkToDeath(rLock, 0);
807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 }
809
810 int oldPokey = mPokey;
811 int cumulative = 0;
812 boolean oldAwakeOnSet = mPokeAwakeOnSet;
813 boolean awakeOnSet = false;
814 for (PokeLock p: mPokeLocks.values()) {
815 cumulative |= p.pokey;
816 if (p.awakeOnSet) {
817 awakeOnSet = true;
818 }
819 }
820 mPokey = cumulative;
821 mPokeAwakeOnSet = awakeOnSet;
822
823 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
824 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
825
826 if (oldCumulativeTimeout != newCumulativeTimeout) {
827 setScreenOffTimeoutsLocked();
828 // reset the countdown timer, but use the existing nextState so it doesn't
829 // change anything
830 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
831 }
832 }
833 }
834
835 private static String lockType(int type)
836 {
837 switch (type)
838 {
839 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700840 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700842 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700844 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700846 return "PARTIAL_WAKE_LOCK ";
847 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
848 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 default:
David Brown251faa62009-08-02 22:04:36 -0700850 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 }
852 }
853
854 private static String dumpPowerState(int state) {
855 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
856 ? "KEYBOARD_BRIGHT_BIT " : "")
857 + (((state & SCREEN_BRIGHT_BIT) != 0)
858 ? "SCREEN_BRIGHT_BIT " : "")
859 + (((state & SCREEN_ON_BIT) != 0)
860 ? "SCREEN_ON_BIT " : "")
861 + (((state & BATTERY_LOW_BIT) != 0)
862 ? "BATTERY_LOW_BIT " : "");
863 }
864
865 @Override
866 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
867 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
868 != PackageManager.PERMISSION_GRANTED) {
869 pw.println("Permission Denial: can't dump PowerManager from from pid="
870 + Binder.getCallingPid()
871 + ", uid=" + Binder.getCallingUid());
872 return;
873 }
874
875 long now = SystemClock.uptimeMillis();
876
877 pw.println("Power Manager State:");
878 pw.println(" mIsPowered=" + mIsPowered
879 + " mPowerState=" + mPowerState
880 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
881 + " ms");
882 pw.println(" mPartialCount=" + mPartialCount);
883 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
884 pw.println(" mUserState=" + dumpPowerState(mUserState));
885 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
886 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
887 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
888 + " " + ((mNextTimeout-now)/1000) + "s from now");
889 pw.println(" mDimScreen=" + mDimScreen
890 + " mStayOnConditions=" + mStayOnConditions);
891 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
892 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700893 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
894 + ',' + mBroadcastQueue[2] + "}");
895 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
896 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
898 pw.println(" mKeyboardVisible=" + mKeyboardVisible
899 + " mUserActivityAllowed=" + mUserActivityAllowed);
900 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
901 + " mScreenOffDelay=" + mScreenOffDelay);
902 pw.println(" mPreventScreenOn=" + mPreventScreenOn
903 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
904 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500905 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
907 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
908 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
909 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500910 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
911 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700912 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
Mike Lockwood20f87d72009-11-05 16:08:51 -0500913 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
914 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700915 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
916 pw.println(" mLightSensorValue=" + mLightSensorValue);
917 pw.println(" mLightSensorPendingValue=" + mLightSensorPendingValue);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400918 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700919 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 mScreenBrightness.dump(pw, " mScreenBrightness: ");
921 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
922 mButtonBrightness.dump(pw, " mButtonBrightness: ");
923
924 int N = mLocks.size();
925 pw.println();
926 pw.println("mLocks.size=" + N + ":");
927 for (int i=0; i<N; i++) {
928 WakeLock wl = mLocks.get(i);
929 String type = lockType(wl.flags & LOCK_MASK);
930 String acquireCausesWakeup = "";
931 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
932 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
933 }
934 String activated = "";
935 if (wl.activated) {
936 activated = " activated";
937 }
938 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
939 + activated + " (minState=" + wl.minState + ")");
940 }
941
942 pw.println();
943 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
944 for (PokeLock p: mPokeLocks.values()) {
945 pw.println(" poke lock '" + p.tag + "':"
946 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
947 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700948 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
949 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
951 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
952 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
953 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
954 }
955
956 pw.println();
957 }
958
959 private void setTimeoutLocked(long now, int nextState)
960 {
961 if (mDoneBooting) {
962 mHandler.removeCallbacks(mTimeoutTask);
963 mTimeoutTask.nextState = nextState;
964 long when = now;
965 switch (nextState)
966 {
967 case SCREEN_BRIGHT:
968 when += mKeylightDelay;
969 break;
970 case SCREEN_DIM:
971 if (mDimDelay >= 0) {
972 when += mDimDelay;
973 break;
974 } else {
975 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
976 }
977 case SCREEN_OFF:
978 synchronized (mLocks) {
979 when += mScreenOffDelay;
980 }
981 break;
982 }
983 if (mSpew) {
984 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
985 + " when=" + when);
986 }
987 mHandler.postAtTime(mTimeoutTask, when);
988 mNextTimeout = when; // for debugging
989 }
990 }
991
992 private void cancelTimerLocked()
993 {
994 mHandler.removeCallbacks(mTimeoutTask);
995 mTimeoutTask.nextState = -1;
996 }
997
998 private class TimeoutTask implements Runnable
999 {
1000 int nextState; // access should be synchronized on mLocks
1001 public void run()
1002 {
1003 synchronized (mLocks) {
1004 if (mSpew) {
1005 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
1006 }
1007
1008 if (nextState == -1) {
1009 return;
1010 }
1011
1012 mUserState = this.nextState;
1013 setPowerState(this.nextState | mWakeLockState);
1014
1015 long now = SystemClock.uptimeMillis();
1016
1017 switch (this.nextState)
1018 {
1019 case SCREEN_BRIGHT:
1020 if (mDimDelay >= 0) {
1021 setTimeoutLocked(now, SCREEN_DIM);
1022 break;
1023 }
1024 case SCREEN_DIM:
1025 setTimeoutLocked(now, SCREEN_OFF);
1026 break;
1027 }
1028 }
1029 }
1030 }
1031
1032 private void sendNotificationLocked(boolean on, int why)
1033 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001034 if (!on) {
1035 mStillNeedSleepNotification = false;
1036 }
1037
Joe Onorato128e7292009-03-24 18:41:31 -07001038 // Add to the queue.
1039 int index = 0;
1040 while (mBroadcastQueue[index] != -1) {
1041 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
Joe Onorato128e7292009-03-24 18:41:31 -07001043 mBroadcastQueue[index] = on ? 1 : 0;
1044 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045
Joe Onorato128e7292009-03-24 18:41:31 -07001046 // If we added it position 2, then there is a pair that can be stripped.
1047 // If we added it position 1 and we're turning the screen off, we can strip
1048 // the pair and do nothing, because the screen is already off, and therefore
1049 // keyguard has already been enabled.
1050 // However, if we added it at position 1 and we're turning it on, then position
1051 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1052 // on, so have to run the queue then.
1053 if (index == 2) {
1054 // Also, while we're collapsing them, if it's going to be an "off," and one
1055 // is off because of user, then use that, regardless of whether it's the first
1056 // or second one.
1057 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
1058 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
1059 }
1060 mBroadcastQueue[0] = on ? 1 : 0;
1061 mBroadcastQueue[1] = -1;
1062 mBroadcastQueue[2] = -1;
1063 index = 0;
1064 }
1065 if (index == 1 && !on) {
1066 mBroadcastQueue[0] = -1;
1067 mBroadcastQueue[1] = -1;
1068 index = -1;
1069 // The wake lock was being held, but we're not actually going to do any
1070 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1072 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001073 }
1074
1075 // Now send the message.
1076 if (index >= 0) {
1077 // Acquire the broadcast wake lock before changing the power
1078 // state. It will be release after the broadcast is sent.
1079 // We always increment the ref count for each notification in the queue
1080 // and always decrement when that notification is handled.
1081 mBroadcastWakeLock.acquire();
1082 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1083 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 }
1085 }
1086
1087 private Runnable mNotificationTask = new Runnable()
1088 {
1089 public void run()
1090 {
Joe Onorato128e7292009-03-24 18:41:31 -07001091 while (true) {
1092 int value;
1093 int why;
1094 WindowManagerPolicy policy;
1095 synchronized (mLocks) {
1096 value = mBroadcastQueue[0];
1097 why = mBroadcastWhy[0];
1098 for (int i=0; i<2; i++) {
1099 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1100 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1101 }
1102 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 }
Joe Onorato128e7292009-03-24 18:41:31 -07001104 if (value == 1) {
1105 mScreenOnStart = SystemClock.uptimeMillis();
1106
1107 policy.screenTurnedOn();
1108 try {
1109 ActivityManagerNative.getDefault().wakingUp();
1110 } catch (RemoteException e) {
1111 // ignore it
1112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113
Joe Onorato128e7292009-03-24 18:41:31 -07001114 if (mSpew) {
1115 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1116 }
1117 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1118 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1119 mScreenOnBroadcastDone, mHandler, 0, null, null);
1120 } else {
1121 synchronized (mLocks) {
1122 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1123 mBroadcastWakeLock.mCount);
1124 mBroadcastWakeLock.release();
1125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 }
1127 }
Joe Onorato128e7292009-03-24 18:41:31 -07001128 else if (value == 0) {
1129 mScreenOffStart = SystemClock.uptimeMillis();
1130
1131 policy.screenTurnedOff(why);
1132 try {
1133 ActivityManagerNative.getDefault().goingToSleep();
1134 } catch (RemoteException e) {
1135 // ignore it.
1136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137
Joe Onorato128e7292009-03-24 18:41:31 -07001138 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1139 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1140 mScreenOffBroadcastDone, mHandler, 0, null, null);
1141 } else {
1142 synchronized (mLocks) {
1143 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1144 mBroadcastWakeLock.mCount);
1145 mBroadcastWakeLock.release();
1146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 }
1148 }
Joe Onorato128e7292009-03-24 18:41:31 -07001149 else {
1150 // If we're in this case, then this handler is running for a previous
1151 // paired transaction. mBroadcastWakeLock will already have been released.
1152 break;
1153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 }
1155 }
1156 };
1157
1158 long mScreenOnStart;
1159 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1160 public void onReceive(Context context, Intent intent) {
1161 synchronized (mLocks) {
1162 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1163 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1164 mBroadcastWakeLock.release();
1165 }
1166 }
1167 };
1168
1169 long mScreenOffStart;
1170 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1171 public void onReceive(Context context, Intent intent) {
1172 synchronized (mLocks) {
1173 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1174 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1175 mBroadcastWakeLock.release();
1176 }
1177 }
1178 };
1179
1180 void logPointerUpEvent() {
1181 if (LOG_TOUCH_DOWNS) {
1182 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1183 mLastTouchDown = 0;
1184 }
1185 }
1186
1187 void logPointerDownEvent() {
1188 if (LOG_TOUCH_DOWNS) {
1189 // If we are not already timing a down/up sequence
1190 if (mLastTouchDown == 0) {
1191 mLastTouchDown = SystemClock.elapsedRealtime();
1192 mTouchCycles++;
1193 }
1194 }
1195 }
1196
1197 /**
1198 * Prevents the screen from turning on even if it *should* turn on due
1199 * to a subsequent full wake lock being acquired.
1200 * <p>
1201 * This is a temporary hack that allows an activity to "cover up" any
1202 * display glitches that happen during the activity's startup
1203 * sequence. (Specifically, this API was added to work around a
1204 * cosmetic bug in the "incoming call" sequence, where the lock screen
1205 * would flicker briefly before the incoming call UI became visible.)
1206 * TODO: There ought to be a more elegant way of doing this,
1207 * probably by having the PowerManager and ActivityManager
1208 * work together to let apps specify that the screen on/off
1209 * state should be synchronized with the Activity lifecycle.
1210 * <p>
1211 * Note that calling preventScreenOn(true) will NOT turn the screen
1212 * off if it's currently on. (This API only affects *future*
1213 * acquisitions of full wake locks.)
1214 * But calling preventScreenOn(false) WILL turn the screen on if
1215 * it's currently off because of a prior preventScreenOn(true) call.
1216 * <p>
1217 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1218 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1219 * call doesn't occur within 5 seconds, we'll turn the screen back on
1220 * ourselves (and log a warning about it); this prevents a buggy app
1221 * from disabling the screen forever.)
1222 * <p>
1223 * TODO: this feature should really be controlled by a new type of poke
1224 * lock (rather than an IPowerManager call).
1225 */
1226 public void preventScreenOn(boolean prevent) {
1227 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1228
1229 synchronized (mLocks) {
1230 if (prevent) {
1231 // First of all, grab a partial wake lock to
1232 // make sure the CPU stays on during the entire
1233 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1234 mPreventScreenOnPartialLock.acquire();
1235
1236 // Post a forceReenableScreen() call (for 5 seconds in the
1237 // future) to make sure the matching preventScreenOn(false) call
1238 // has happened by then.
1239 mHandler.removeCallbacks(mForceReenableScreenTask);
1240 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1241
1242 // Finally, set the flag that prevents the screen from turning on.
1243 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001244 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 mPreventScreenOn = true;
1246 } else {
1247 // (Re)enable the screen.
1248 mPreventScreenOn = false;
1249
1250 // We're "undoing" a the prior preventScreenOn(true) call, so we
1251 // no longer need the 5-second safeguard.
1252 mHandler.removeCallbacks(mForceReenableScreenTask);
1253
1254 // Forcibly turn on the screen if it's supposed to be on. (This
1255 // handles the case where the screen is currently off because of
1256 // a prior preventScreenOn(true) call.)
1257 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1258 if (mSpew) {
1259 Log.d(TAG,
1260 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1261 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001262 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001264 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 }
1266 }
1267
1268 // Release the partial wake lock that we held during the
1269 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1270 mPreventScreenOnPartialLock.release();
1271 }
1272 }
1273 }
1274
1275 public void setScreenBrightnessOverride(int brightness) {
1276 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1277
1278 synchronized (mLocks) {
1279 if (mScreenBrightnessOverride != brightness) {
1280 mScreenBrightnessOverride = brightness;
1281 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1282 }
1283 }
1284 }
1285
1286 /**
1287 * Sanity-check that gets called 5 seconds after any call to
1288 * preventScreenOn(true). This ensures that the original call
1289 * is followed promptly by a call to preventScreenOn(false).
1290 */
1291 private void forceReenableScreen() {
1292 // We shouldn't get here at all if mPreventScreenOn is false, since
1293 // we should have already removed any existing
1294 // mForceReenableScreenTask messages...
1295 if (!mPreventScreenOn) {
1296 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1297 return;
1298 }
1299
1300 // Uh oh. It's been 5 seconds since a call to
1301 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1302 // This means the app that called preventScreenOn(true) is either
1303 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1304 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1305 // crashed before doing so.)
1306
1307 // Log a warning, and forcibly turn the screen back on.
1308 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1309 + "Forcing the screen back on...");
1310 preventScreenOn(false);
1311 }
1312
1313 private Runnable mForceReenableScreenTask = new Runnable() {
1314 public void run() {
1315 forceReenableScreen();
1316 }
1317 };
1318
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001319 private int setScreenStateLocked(boolean on) {
1320 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001321 if (err == 0) {
1322 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1323 if (mUseSoftwareAutoBrightness) {
1324 enableLightSensor(on);
1325 if (!on) {
1326 // make sure button and key backlights are off too
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001327 int brightnessMode = (mUseSoftwareAutoBrightness
1328 ? HardwareService.BRIGHTNESS_MODE_SENSOR
1329 : HardwareService.BRIGHTNESS_MODE_USER);
1330 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, 0,
1331 brightnessMode);
1332 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, 0,
1333 brightnessMode);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001334 // clear current value so we will update based on the new conditions
1335 // when the sensor is reenabled.
1336 mLightSensorValue = -1;
1337 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001338 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001339 }
1340 return err;
1341 }
1342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 private void setPowerState(int state)
1344 {
1345 setPowerState(state, false, false);
1346 }
1347
1348 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1349 {
1350 synchronized (mLocks) {
1351 int err;
1352
1353 if (mSpew) {
1354 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1355 + " newState=0x" + Integer.toHexString(newState)
1356 + " noChangeLights=" + noChangeLights);
1357 }
1358
1359 if (noChangeLights) {
1360 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1361 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001362 if (mProximitySensorActive) {
1363 // don't turn on the screen when the proximity sensor lock is held
1364 newState = (newState & ~SCREEN_BRIGHT);
1365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366
1367 if (batteryIsLow()) {
1368 newState |= BATTERY_LOW_BIT;
1369 } else {
1370 newState &= ~BATTERY_LOW_BIT;
1371 }
1372 if (newState == mPowerState) {
1373 return;
1374 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001375
Mike Lockwood4984e732009-11-01 08:16:33 -05001376 if (!mDoneBooting && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 newState |= ALL_BRIGHT;
1378 }
1379
1380 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1381 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1382
Mike Lockwood24ace332009-11-09 19:53:08 -05001383 if (mPowerState != newState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1385 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1386 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1387 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1388 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1389 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1390 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1391 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1392 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1393 + " newScreenOn=" + newScreenOn);
1394 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1395 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1396 }
1397
1398 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001399 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1401 }
1402
1403 if (oldScreenOn != newScreenOn) {
1404 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001405 // When the user presses the power button, we need to always send out the
1406 // notification that it's going to sleep so the keyguard goes on. But
1407 // we can't do that until the screen fades out, so we don't show the keyguard
1408 // too early.
1409 if (mStillNeedSleepNotification) {
1410 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1411 }
1412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 // Turn on the screen UNLESS there was a prior
1414 // preventScreenOn(true) request. (Note that the lifetime
1415 // of a single preventScreenOn() request is limited to 5
1416 // seconds to prevent a buggy app from disabling the
1417 // screen forever; see forceReenableScreen().)
1418 boolean reallyTurnScreenOn = true;
1419 if (mSpew) {
1420 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1421 + mPreventScreenOn);
1422 }
1423
1424 if (mPreventScreenOn) {
1425 if (mSpew) {
1426 Log.d(TAG, "- PREVENTING screen from really turning on!");
1427 }
1428 reallyTurnScreenOn = false;
1429 }
1430 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001431 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 long identity = Binder.clearCallingIdentity();
1433 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001434 mBatteryStats.noteScreenBrightness(
1435 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 mBatteryStats.noteScreenOn();
1437 } catch (RemoteException e) {
1438 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1439 } finally {
1440 Binder.restoreCallingIdentity(identity);
1441 }
1442 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001443 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 // But continue as if we really did turn the screen on...
1445 err = 0;
1446 }
1447
1448 mScreenOnStartTime = SystemClock.elapsedRealtime();
1449 mLastTouchDown = 0;
1450 mTotalTouchDownTime = 0;
1451 mTouchCycles = 0;
1452 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1453 mTotalTouchDownTime, mTouchCycles);
1454 if (err == 0) {
1455 mPowerState |= SCREEN_ON_BIT;
1456 sendNotificationLocked(true, -1);
1457 }
1458 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001459 // cancel light sensor task
1460 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 mScreenOffTime = SystemClock.elapsedRealtime();
1462 long identity = Binder.clearCallingIdentity();
1463 try {
1464 mBatteryStats.noteScreenOff();
1465 } catch (RemoteException e) {
1466 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1467 } finally {
1468 Binder.restoreCallingIdentity(identity);
1469 }
1470 mPowerState &= ~SCREEN_ON_BIT;
1471 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001472 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 } else {
1474 mOffBecauseOfUser = becauseOfUser;
1475 err = 0;
1476 mLastTouchDown = 0;
1477 }
1478 }
1479 }
1480 }
1481 }
1482
Joe Onorato128e7292009-03-24 18:41:31 -07001483 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 // I don't think we need to check the current state here because all of these
1485 // Power.setScreenState and sendNotificationLocked can both handle being
1486 // called multiple times in the same state. -joeo
1487 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1488 mTotalTouchDownTime, mTouchCycles);
1489 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001490 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 if (mScreenOnStartTime != 0) {
1492 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1493 mScreenOnStartTime = 0;
1494 }
1495 if (err == 0) {
1496 int why = becauseOfUser
1497 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1498 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1499 sendNotificationLocked(false, why);
1500 }
1501 return err;
1502 }
1503
1504 private boolean batteryIsLow() {
1505 return (!mIsPowered &&
1506 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1507 }
1508
The Android Open Source Project10592532009-03-18 17:39:46 -07001509 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001510 final int oldState = mPowerState;
1511 final int realDifference = (newState ^ oldState);
1512 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001514 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516
1517 int offMask = 0;
1518 int dimMask = 0;
1519 int onMask = 0;
1520
1521 int preferredBrightness = getPreferredBrightness();
1522 boolean startAnimation = false;
1523
1524 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1525 if (ANIMATE_KEYBOARD_LIGHTS) {
1526 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1527 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001528 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1529 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 } else {
1531 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001532 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1533 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 }
1535 startAnimation = true;
1536 } else {
1537 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001538 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001540 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
1542 }
1543 }
1544
1545 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1546 if (ANIMATE_BUTTON_LIGHTS) {
1547 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1548 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001549 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1550 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 } else {
1552 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001553 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1554 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 }
1556 startAnimation = true;
1557 } else {
1558 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001559 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001561 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 }
1563 }
1564 }
1565
1566 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1567 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001568 int nominalCurrentValue = -1;
1569 // If there was an actual difference in the light state, then
1570 // figure out the "ideal" current value based on the previous
1571 // state. Otherwise, this is a change due to the brightness
1572 // override, so we want to animate from whatever the current
1573 // value is.
1574 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1575 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1576 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1577 nominalCurrentValue = preferredBrightness;
1578 break;
1579 case SCREEN_ON_BIT:
1580 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1581 break;
1582 case 0:
1583 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1584 break;
1585 case SCREEN_BRIGHT_BIT:
1586 default:
1587 // not possible
1588 nominalCurrentValue = (int)mScreenBrightness.curValue;
1589 break;
1590 }
Joe Onorato128e7292009-03-24 18:41:31 -07001591 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001592 int brightness = preferredBrightness;
1593 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1595 // dim or turn off backlight, depending on if the screen is on
1596 // the scale is because the brightness ramp isn't linear and this biases
1597 // it so the later parts take longer.
1598 final float scale = 1.5f;
1599 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1600 if (ratio > 1.0f) ratio = 1.0f;
1601 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1603 // was bright
1604 steps = ANIM_STEPS;
1605 } else {
1606 // was dim
1607 steps = (int)(ANIM_STEPS*ratio*scale);
1608 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001609 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 if ((oldState & SCREEN_ON_BIT) != 0) {
1612 // was bright
1613 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1614 } else {
1615 // was dim
1616 steps = (int)(ANIM_STEPS*ratio);
1617 }
1618 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1619 // If the "stay on while plugged in" option is
1620 // turned on, then the screen will often not
1621 // automatically turn off while plugged in. To
1622 // still have a sense of when it is inactive, we
1623 // will then count going dim as turning off.
1624 mScreenOffTime = SystemClock.elapsedRealtime();
1625 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001626 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001629 long identity = Binder.clearCallingIdentity();
1630 try {
1631 mBatteryStats.noteScreenBrightness(brightness);
1632 } catch (RemoteException e) {
1633 // Nothing interesting to do.
1634 } finally {
1635 Binder.restoreCallingIdentity(identity);
1636 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001637 if (mScreenBrightness.setTargetLocked(brightness,
1638 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1639 startAnimation = true;
1640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 } else {
1642 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1643 // dim or turn off backlight, depending on if the screen is on
1644 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001645 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001647 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001650 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 }
1652 }
1653 }
1654
1655 if (startAnimation) {
1656 if (mSpew) {
1657 Log.i(TAG, "Scheduling light animator!");
1658 }
1659 mHandler.removeCallbacks(mLightAnimator);
1660 mHandler.post(mLightAnimator);
1661 }
1662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 if (offMask != 0) {
1664 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001665 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 }
1667 if (dimMask != 0) {
1668 int brightness = Power.BRIGHTNESS_DIM;
1669 if ((newState & BATTERY_LOW_BIT) != 0 &&
1670 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1671 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1672 }
1673 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001674 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 }
1676 if (onMask != 0) {
1677 int brightness = getPreferredBrightness();
1678 if ((newState & BATTERY_LOW_BIT) != 0 &&
1679 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1680 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1681 }
1682 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001683 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686
The Android Open Source Project10592532009-03-18 17:39:46 -07001687 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001688 int brightnessMode = (mAutoBrightessEnabled
1689 ? HardwareService.BRIGHTNESS_MODE_SENSOR
1690 : HardwareService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001691 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001692 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value,
1693 brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001694 }
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001695 brightnessMode = (mUseSoftwareAutoBrightness
1696 ? HardwareService.BRIGHTNESS_MODE_SENSOR
1697 : HardwareService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001698 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001699 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value,
1700 brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001701 }
1702 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001703 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value,
1704 brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 }
1707
1708 class BrightnessState {
1709 final int mask;
1710
1711 boolean initialized;
1712 int targetValue;
1713 float curValue;
1714 float delta;
1715 boolean animating;
1716
1717 BrightnessState(int m) {
1718 mask = m;
1719 }
1720
1721 public void dump(PrintWriter pw, String prefix) {
1722 pw.println(prefix + "animating=" + animating
1723 + " targetValue=" + targetValue
1724 + " curValue=" + curValue
1725 + " delta=" + delta);
1726 }
1727
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001728 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001729 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 if (!initialized) {
1731 initialized = true;
1732 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001733 } else if (targetValue == target) {
1734 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 }
1736 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001737 delta = (targetValue -
1738 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1739 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001741 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001743 + " target=" + targetValue + " delta=" + delta
1744 + " nominalCurrentValue=" + nominalCurrentValue
1745 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 }
1747 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001748 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 }
1750
1751 boolean stepLocked() {
1752 if (!animating) return false;
1753 if (false && mSpew) {
1754 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1755 + " target=" + targetValue + " delta=" + delta);
1756 }
1757 curValue += delta;
1758 int curIntValue = (int)curValue;
1759 boolean more = true;
1760 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001761 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 more = false;
1763 } else if (delta > 0) {
1764 if (curIntValue >= targetValue) {
1765 curValue = curIntValue = targetValue;
1766 more = false;
1767 }
1768 } else {
1769 if (curIntValue <= targetValue) {
1770 curValue = curIntValue = targetValue;
1771 more = false;
1772 }
1773 }
1774 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001775 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 animating = more;
1777 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001778 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001779 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 }
1781 }
1782 return more;
1783 }
1784 }
1785
1786 private class LightAnimator implements Runnable {
1787 public void run() {
1788 synchronized (mLocks) {
1789 long now = SystemClock.uptimeMillis();
1790 boolean more = mScreenBrightness.stepLocked();
1791 if (mKeyboardBrightness.stepLocked()) {
1792 more = true;
1793 }
1794 if (mButtonBrightness.stepLocked()) {
1795 more = true;
1796 }
1797 if (more) {
1798 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1799 }
1800 }
1801 }
1802 }
1803
1804 private int getPreferredBrightness() {
1805 try {
1806 if (mScreenBrightnessOverride >= 0) {
1807 return mScreenBrightnessOverride;
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001808 } else if (mLightSensorBrightness >= 0 && mUseSoftwareAutoBrightness
1809 && mAutoBrightessEnabled) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001810 return mLightSensorBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 }
1812 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1813 SCREEN_BRIGHTNESS);
1814 // Don't let applications turn the screen all the way off
1815 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1816 } catch (SettingNotFoundException snfe) {
1817 return Power.BRIGHTNESS_ON;
1818 }
1819 }
1820
Charles Mendis322591c2009-10-29 11:06:59 -07001821 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 synchronized (mLocks) {
1823 return (mPowerState & SCREEN_ON_BIT) != 0;
1824 }
1825 }
1826
Charles Mendis322591c2009-10-29 11:06:59 -07001827 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 synchronized (mLocks) {
1829 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1830 }
1831 }
1832
Mike Lockwood497087e32009-11-08 18:33:03 -05001833 private boolean isScreenTurningOffLocked() {
1834 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1835 }
1836
Mike Lockwood200b30b2009-09-20 00:23:59 -04001837 private void forceUserActivityLocked() {
Mike Lockwood952211b2009-11-02 14:17:57 -05001838 // cancel animation so userActivity will succeed
1839 mScreenBrightness.animating = false;
Mike Lockwood200b30b2009-09-20 00:23:59 -04001840 boolean savedActivityAllowed = mUserActivityAllowed;
1841 mUserActivityAllowed = true;
1842 userActivity(SystemClock.uptimeMillis(), false);
1843 mUserActivityAllowed = savedActivityAllowed;
1844 }
1845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1847 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1848 userActivity(time, noChangeLights, OTHER_EVENT, force);
1849 }
1850
1851 public void userActivity(long time, boolean noChangeLights) {
1852 userActivity(time, noChangeLights, OTHER_EVENT, false);
1853 }
1854
1855 public void userActivity(long time, boolean noChangeLights, int eventType) {
1856 userActivity(time, noChangeLights, eventType, false);
1857 }
1858
1859 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1860 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1861
1862 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001863 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001865 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 }
1867 return;
1868 }
1869
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001870 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1871 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1872 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1873 if (false) {
1874 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1875 }
1876 return;
1877 }
1878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 if (false) {
1880 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1881 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1882 } else {
1883 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1884 }
1885 }
1886
1887 synchronized (mLocks) {
1888 if (mSpew) {
1889 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1890 + " mUserActivityAllowed=" + mUserActivityAllowed
1891 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001892 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1893 + " mProximitySensorActive=" + mProximitySensorActive
1894 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 }
Mike Lockwood05067122009-10-27 23:07:25 -04001896 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05001897 if (isScreenTurningOffLocked()) {
Mike Lockwood05067122009-10-27 23:07:25 -04001898 Log.d(TAG, "ignoring user activity while turning off screen");
1899 return;
1900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 if (mLastEventTime <= time || force) {
1902 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001903 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001904 // Only turn on button backlights if a button was pressed
1905 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05001906 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1908 } else {
1909 // don't clear button/keyboard backlights when the screen is touched.
1910 mUserState |= SCREEN_BRIGHT;
1911 }
1912
Dianne Hackborn617f8772009-03-31 15:04:46 -07001913 int uid = Binder.getCallingUid();
1914 long ident = Binder.clearCallingIdentity();
1915 try {
1916 mBatteryStats.noteUserActivity(uid, eventType);
1917 } catch (RemoteException e) {
1918 // Ignore
1919 } finally {
1920 Binder.restoreCallingIdentity(ident);
1921 }
1922
Michael Chane96440f2009-05-06 10:27:36 -07001923 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1925 setTimeoutLocked(time, SCREEN_BRIGHT);
1926 }
1927 }
1928 }
1929 }
1930
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001931 private int getAutoBrightnessValue(int sensorValue, int[] values) {
1932 try {
1933 int i;
1934 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
1935 if (sensorValue < mAutoBrightnessLevels[i]) {
1936 break;
1937 }
1938 }
1939 return values[i];
1940 } catch (Exception e) {
1941 // guard against null pointer or index out of bounds errors
1942 Log.e(TAG, "getAutoBrightnessValue", e);
1943 return 255;
1944 }
1945 }
1946
Mike Lockwood20f87d72009-11-05 16:08:51 -05001947 private Runnable mProximityTask = new Runnable() {
1948 public void run() {
1949 synchronized (mLocks) {
1950 if (mProximityPendingValue != -1) {
1951 proximityChangedLocked(mProximityPendingValue == 1);
1952 mProximityPendingValue = -1;
1953 }
1954 }
1955 }
1956 };
1957
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001958 private Runnable mAutoBrightnessTask = new Runnable() {
1959 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04001960 synchronized (mLocks) {
1961 int value = (int)mLightSensorPendingValue;
1962 if (value >= 0) {
1963 mLightSensorPendingValue = -1;
1964 lightSensorChangedLocked(value);
1965 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001966 }
1967 }
1968 };
1969
1970 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001971 if (mDebugLightSensor) {
1972 Log.d(TAG, "lightSensorChangedLocked " + value);
1973 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001974
1975 if (mLightSensorValue != value) {
1976 mLightSensorValue = value;
1977 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
1978 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
1979 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04001980 int keyboardValue;
1981 if (mKeyboardVisible) {
1982 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
1983 } else {
1984 keyboardValue = 0;
1985 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001986 mLightSensorBrightness = lcdValue;
1987
1988 if (mDebugLightSensor) {
1989 Log.d(TAG, "lcdValue " + lcdValue);
1990 Log.d(TAG, "buttonValue " + buttonValue);
1991 Log.d(TAG, "keyboardValue " + keyboardValue);
1992 }
1993
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001994 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05001995 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001996 if (ANIMATE_SCREEN_LIGHTS) {
1997 if (mScreenBrightness.setTargetLocked(lcdValue,
1998 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
1999 (int)mScreenBrightness.curValue)) {
2000 startAnimation = true;
2001 }
2002 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002003 int brightnessMode = (mAutoBrightessEnabled
2004 ? HardwareService.BRIGHTNESS_MODE_SENSOR
2005 : HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002006 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002007 lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002008 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002009 }
2010 if (ANIMATE_BUTTON_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002011 if (mButtonBrightness.setTargetLocked(buttonValue,
2012 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2013 (int)mButtonBrightness.curValue)) {
2014 startAnimation = true;
2015 }
2016 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002017 int brightnessMode = (mUseSoftwareAutoBrightness
2018 ? HardwareService.BRIGHTNESS_MODE_SENSOR
2019 : HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002020 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002021 buttonValue, brightnessMode);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002022 }
2023 if (ANIMATE_KEYBOARD_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002024 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2025 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2026 (int)mKeyboardBrightness.curValue)) {
2027 startAnimation = true;
2028 }
2029 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002030 int brightnessMode = (mUseSoftwareAutoBrightness
2031 ? HardwareService.BRIGHTNESS_MODE_SENSOR
2032 : HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002033 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002034 keyboardValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002035 }
2036 if (startAnimation) {
2037 if (mDebugLightSensor) {
2038 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
2039 }
2040 mHandler.removeCallbacks(mLightAnimator);
2041 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002042 }
2043 }
2044 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002045 }
2046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 /**
2048 * The user requested that we go to sleep (probably with the power button).
2049 * This overrides all wake locks that are held.
2050 */
2051 public void goToSleep(long time)
2052 {
2053 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2054 synchronized (mLocks) {
2055 goToSleepLocked(time);
2056 }
2057 }
2058
2059 /**
2060 * Returns the time the screen has been on since boot, in millis.
2061 * @return screen on time
2062 */
2063 public long getScreenOnTime() {
2064 synchronized (mLocks) {
2065 if (mScreenOnStartTime == 0) {
2066 return mScreenOnTime;
2067 } else {
2068 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
2069 }
2070 }
2071 }
2072
2073 private void goToSleepLocked(long time) {
2074
2075 if (mLastEventTime <= time) {
2076 mLastEventTime = time;
2077 // cancel all of the wake locks
2078 mWakeLockState = SCREEN_OFF;
2079 int N = mLocks.size();
2080 int numCleared = 0;
2081 for (int i=0; i<N; i++) {
2082 WakeLock wl = mLocks.get(i);
2083 if (isScreenLock(wl.flags)) {
2084 mLocks.get(i).activated = false;
2085 numCleared++;
2086 }
2087 }
2088 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002089 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 mUserState = SCREEN_OFF;
2091 setPowerState(SCREEN_OFF, false, true);
2092 cancelTimerLocked();
2093 }
2094 }
2095
2096 public long timeSinceScreenOn() {
2097 synchronized (mLocks) {
2098 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2099 return 0;
2100 }
2101 return SystemClock.elapsedRealtime() - mScreenOffTime;
2102 }
2103 }
2104
2105 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002106 synchronized (mLocks) {
2107 if (mSpew) {
2108 Log.d(TAG, "setKeyboardVisibility: " + visible);
2109 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002110 if (mKeyboardVisible != visible) {
2111 mKeyboardVisible = visible;
2112 // don't signal user activity if the screen is off; other code
2113 // will take care of turning on due to a true change to the lid
2114 // switch and synchronized with the lock screen.
2115 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002116 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002117 // force recompute of backlight values
2118 if (mLightSensorValue >= 0) {
2119 int value = (int)mLightSensorValue;
2120 mLightSensorValue = -1;
2121 lightSensorChangedLocked(value);
2122 }
2123 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002124 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2125 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002126 }
2127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 }
2129
2130 /**
2131 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002132 * When disabling user activity we also reset user power state so the keyguard can reset its
2133 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 */
2135 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002136 if (mSpew) {
2137 Log.d(TAG, "enableUserActivity " + enabled);
2138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 synchronized (mLocks) {
2140 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002141 if (!enabled) {
2142 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2143 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 }
2146 }
2147
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002148 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002149 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002150 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002151 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002152 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002153 // force recompute of backlight values
2154 if (mLightSensorValue >= 0) {
2155 int value = (int)mLightSensorValue;
2156 mLightSensorValue = -1;
2157 lightSensorChangedLocked(value);
2158 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002159 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002160 }
2161 }
2162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 /** Sets the screen off timeouts:
2164 * mKeylightDelay
2165 * mDimDelay
2166 * mScreenOffDelay
2167 * */
2168 private void setScreenOffTimeoutsLocked() {
2169 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
2170 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
2171 mDimDelay = -1;
2172 mScreenOffDelay = 0;
2173 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2174 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2175 mDimDelay = -1;
2176 mScreenOffDelay = 0;
2177 } else {
2178 int totalDelay = mTotalDelaySetting;
2179 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2180 if (totalDelay < 0) {
2181 mScreenOffDelay = Integer.MAX_VALUE;
2182 } else if (mKeylightDelay < totalDelay) {
2183 // subtract the time that the keylight delay. This will give us the
2184 // remainder of the time that we need to sleep to get the accurate
2185 // screen off timeout.
2186 mScreenOffDelay = totalDelay - mKeylightDelay;
2187 } else {
2188 mScreenOffDelay = 0;
2189 }
2190 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2191 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2192 mScreenOffDelay = LONG_DIM_TIME;
2193 } else {
2194 mDimDelay = -1;
2195 }
2196 }
2197 if (mSpew) {
2198 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2199 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2200 + " mDimScreen=" + mDimScreen);
2201 }
2202 }
2203
2204 /**
2205 * Refreshes cached Gservices settings. Called once on startup, and
2206 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
2207 * GservicesChangedReceiver).
2208 */
2209 private void updateGservicesValues() {
2210 mShortKeylightDelay = Settings.Gservices.getInt(
2211 mContext.getContentResolver(),
2212 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
2213 SHORT_KEYLIGHT_DELAY_DEFAULT);
2214 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
2215 }
2216
2217 /**
2218 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
2219 * which tells us we need to refresh our cached Gservices settings.
2220 */
2221 private class GservicesChangedReceiver extends BroadcastReceiver {
2222 @Override
2223 public void onReceive(Context context, Intent intent) {
2224 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
2225 updateGservicesValues();
2226 }
2227 }
2228
2229 private class LockList extends ArrayList<WakeLock>
2230 {
2231 void addLock(WakeLock wl)
2232 {
2233 int index = getIndex(wl.binder);
2234 if (index < 0) {
2235 this.add(wl);
2236 }
2237 }
2238
2239 WakeLock removeLock(IBinder binder)
2240 {
2241 int index = getIndex(binder);
2242 if (index >= 0) {
2243 return this.remove(index);
2244 } else {
2245 return null;
2246 }
2247 }
2248
2249 int getIndex(IBinder binder)
2250 {
2251 int N = this.size();
2252 for (int i=0; i<N; i++) {
2253 if (this.get(i).binder == binder) {
2254 return i;
2255 }
2256 }
2257 return -1;
2258 }
2259
2260 int gatherState()
2261 {
2262 int result = 0;
2263 int N = this.size();
2264 for (int i=0; i<N; i++) {
2265 WakeLock wl = this.get(i);
2266 if (wl.activated) {
2267 if (isScreenLock(wl.flags)) {
2268 result |= wl.minState;
2269 }
2270 }
2271 }
2272 return result;
2273 }
Michael Chane96440f2009-05-06 10:27:36 -07002274
2275 int reactivateScreenLocksLocked()
2276 {
2277 int result = 0;
2278 int N = this.size();
2279 for (int i=0; i<N; i++) {
2280 WakeLock wl = this.get(i);
2281 if (isScreenLock(wl.flags)) {
2282 wl.activated = true;
2283 result |= wl.minState;
2284 }
2285 }
2286 return result;
2287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 }
2289
2290 void setPolicy(WindowManagerPolicy p) {
2291 synchronized (mLocks) {
2292 mPolicy = p;
2293 mLocks.notifyAll();
2294 }
2295 }
2296
2297 WindowManagerPolicy getPolicyLocked() {
2298 while (mPolicy == null || !mDoneBooting) {
2299 try {
2300 mLocks.wait();
2301 } catch (InterruptedException e) {
2302 // Ignore
2303 }
2304 }
2305 return mPolicy;
2306 }
2307
2308 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002309 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2310 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2311 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002312 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002313 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002314 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002315 }
2316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 synchronized (mLocks) {
2318 Log.d(TAG, "system ready!");
2319 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002320 long identity = Binder.clearCallingIdentity();
2321 try {
2322 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2323 mBatteryStats.noteScreenOn();
2324 } catch (RemoteException e) {
2325 // Nothing interesting to do.
2326 } finally {
2327 Binder.restoreCallingIdentity(identity);
2328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002329 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2330 updateWakeLockLocked();
2331 mLocks.notifyAll();
2332 }
2333 }
2334
2335 public void monitor() {
2336 synchronized (mLocks) { }
2337 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002338
2339 public int getSupportedWakeLockFlags() {
2340 int result = PowerManager.PARTIAL_WAKE_LOCK
2341 | PowerManager.FULL_WAKE_LOCK
2342 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2343
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002344 if (mProximitySensor != null) {
2345 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2346 }
2347
2348 return result;
2349 }
2350
Mike Lockwood237a2992009-09-15 14:42:16 -04002351 public void setBacklightBrightness(int brightness) {
2352 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2353 // Don't let applications turn the screen all the way off
2354 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002355 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness,
2356 HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwooddf024922009-10-29 21:29:15 -04002357 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002358 (mKeyboardVisible ? brightness : 0), HardwareService.BRIGHTNESS_MODE_USER);
2359 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness,
2360 HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwood237a2992009-09-15 14:42:16 -04002361 long identity = Binder.clearCallingIdentity();
2362 try {
2363 mBatteryStats.noteScreenBrightness(brightness);
2364 } catch (RemoteException e) {
2365 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2366 } finally {
2367 Binder.restoreCallingIdentity(identity);
2368 }
2369
2370 // update our animation state
2371 if (ANIMATE_SCREEN_LIGHTS) {
2372 mScreenBrightness.curValue = brightness;
2373 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002374 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002375 }
2376 if (ANIMATE_KEYBOARD_LIGHTS) {
2377 mKeyboardBrightness.curValue = brightness;
2378 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002379 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002380 }
2381 if (ANIMATE_BUTTON_LIGHTS) {
2382 mButtonBrightness.curValue = brightness;
2383 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002384 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002385 }
2386 }
2387
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002388 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002389 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002390 Log.d(TAG, "enableProximityLockLocked");
2391 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002392 if (!mProximitySensorEnabled) {
2393 // clear calling identity so sensor manager battery stats are accurate
2394 long identity = Binder.clearCallingIdentity();
2395 try {
2396 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2397 SensorManager.SENSOR_DELAY_NORMAL);
2398 mProximitySensorEnabled = true;
2399 } finally {
2400 Binder.restoreCallingIdentity(identity);
2401 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002402 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002403 }
2404
2405 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002406 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002407 Log.d(TAG, "disableProximityLockLocked");
2408 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002409 if (mProximitySensorEnabled) {
2410 // clear calling identity so sensor manager battery stats are accurate
2411 long identity = Binder.clearCallingIdentity();
2412 try {
2413 mSensorManager.unregisterListener(mProximityListener);
2414 mHandler.removeCallbacks(mProximityTask);
2415 mProximitySensorEnabled = false;
2416 } finally {
2417 Binder.restoreCallingIdentity(identity);
2418 }
2419 if (mProximitySensorActive) {
2420 mProximitySensorActive = false;
2421 forceUserActivityLocked();
2422 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002423 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002424 }
2425
Mike Lockwood20f87d72009-11-05 16:08:51 -05002426 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002427 if (mDebugProximitySensor) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002428 Log.d(TAG, "proximityChangedLocked, active: " + active);
2429 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002430 if (!mProximitySensorEnabled) {
2431 Log.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002432 return;
2433 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002434 if (active) {
2435 goToSleepLocked(SystemClock.uptimeMillis());
2436 mProximitySensorActive = true;
2437 } else {
2438 // proximity sensor negative events trigger as user activity.
2439 // temporarily set mUserActivityAllowed to true so this will work
2440 // even when the keyguard is on.
2441 mProximitySensorActive = false;
2442 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002443
2444 if (mProximityWakeLockCount == 0) {
2445 // disable sensor if we have no listeners left after proximity negative
2446 disableProximityLockLocked();
2447 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002448 }
2449 }
2450
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002451 private void enableLightSensor(boolean enable) {
2452 if (mDebugLightSensor) {
2453 Log.d(TAG, "enableLightSensor " + enable);
2454 }
2455 if (mSensorManager != null && mLightSensorEnabled != enable) {
2456 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002457 // clear calling identity so sensor manager battery stats are accurate
2458 long identity = Binder.clearCallingIdentity();
2459 try {
2460 if (enable) {
2461 mSensorManager.registerListener(mLightListener, mLightSensor,
2462 SensorManager.SENSOR_DELAY_NORMAL);
2463 } else {
2464 mSensorManager.unregisterListener(mLightListener);
2465 mHandler.removeCallbacks(mAutoBrightnessTask);
2466 }
2467 } finally {
2468 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002469 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002470 }
2471 }
2472
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002473 SensorEventListener mProximityListener = new SensorEventListener() {
2474 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002475 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002476 synchronized (mLocks) {
2477 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002478 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2479 mLastProximityEventTime = milliseconds;
2480 mHandler.removeCallbacks(mProximityTask);
2481
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002482 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002483 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2484 distance < mProximitySensor.getMaximumRange());
2485
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002486 if (mDebugProximitySensor) {
2487 Log.d(TAG, "mProximityListener.onSensorChanged active: " + active);
2488 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002489 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2490 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2491 mProximityPendingValue = (active ? 1 : 0);
2492 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002493 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002494 // process the value immediately
2495 mProximityPendingValue = -1;
2496 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002497 }
2498 }
2499 }
2500
2501 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2502 // ignore
2503 }
2504 };
2505
2506 SensorEventListener mLightListener = new SensorEventListener() {
2507 public void onSensorChanged(SensorEvent event) {
2508 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002509 // ignore light sensor while screen is turning off
2510 if (isScreenTurningOffLocked()) {
2511 return;
2512 }
2513
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002514 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002515 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002516 if (mDebugLightSensor) {
2517 Log.d(TAG, "onSensorChanged: light value: " + value);
2518 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002519 mHandler.removeCallbacks(mAutoBrightnessTask);
2520 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002521 if (mLightSensorValue == -1 ||
2522 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2523 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002524 lightSensorChangedLocked(value);
2525 } else {
2526 // delay processing to debounce the sensor
2527 mLightSensorPendingValue = value;
2528 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2529 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002530 } else {
2531 mLightSensorPendingValue = -1;
2532 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002533 }
2534 }
2535
2536 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2537 // ignore
2538 }
2539 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540}