blob: 35f508b8f297bb271d8d63d837ba1b4690e80827 [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;
31import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070032import android.hardware.Sensor;
33import android.hardware.SensorEvent;
34import android.hardware.SensorEventListener;
35import android.hardware.SensorManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.os.BatteryStats;
37import android.os.Binder;
38import android.os.Handler;
39import android.os.HandlerThread;
40import android.os.IBinder;
41import android.os.IPowerManager;
42import android.os.LocalPowerManager;
43import android.os.Power;
44import android.os.PowerManager;
45import android.os.Process;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.provider.Settings.SettingNotFoundException;
49import android.provider.Settings;
50import android.util.EventLog;
51import android.util.Log;
52import android.view.WindowManagerPolicy;
53import static android.provider.Settings.System.DIM_SCREEN;
54import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050055import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
57import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
58
59import java.io.FileDescriptor;
60import java.io.PrintWriter;
61import java.util.ArrayList;
62import java.util.HashMap;
63import java.util.Observable;
64import java.util.Observer;
65
Mike Lockwoodbc706a02009-07-27 13:50:57 -070066class PowerManagerService extends IPowerManager.Stub
Mike Lockwooda625b382009-09-12 17:36:03 -070067 implements LocalPowerManager, Watchdog.Monitor, SensorEventListener {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
69 private static final String TAG = "PowerManagerService";
70 static final String PARTIAL_NAME = "PowerManagerService";
71
72 private static final boolean LOG_PARTIAL_WL = false;
73
74 // Indicates whether touch-down cycles should be logged as part of the
75 // LOG_POWER_SCREEN_STATE log events
76 private static final boolean LOG_TOUCH_DOWNS = true;
77
78 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
79 | PowerManager.SCREEN_DIM_WAKE_LOCK
80 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070081 | PowerManager.FULL_WAKE_LOCK
82 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
84 // time since last state: time since last event:
85 // The short keylight delay comes from Gservices; this is the default.
86 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
87 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
88 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
89 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
90
Mike Lockwoodd20ea362009-09-15 00:13:38 -040091 // trigger proximity if distance is less than 5 cm
92 private static final float PROXIMITY_THRESHOLD = 5.0f;
93
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 // Cached Gservices settings; see updateGservicesValues()
95 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
96
97 // flags for setPowerState
98 private static final int SCREEN_ON_BIT = 0x00000001;
99 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
100 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
101 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
102 private static final int BATTERY_LOW_BIT = 0x00000010;
103
104 // values for setPowerState
105
106 // SCREEN_OFF == everything off
107 private static final int SCREEN_OFF = 0x00000000;
108
109 // SCREEN_DIM == screen on, screen backlight dim
110 private static final int SCREEN_DIM = SCREEN_ON_BIT;
111
112 // SCREEN_BRIGHT == screen on, screen backlight bright
113 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
114
115 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
116 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
117
118 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
119 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
120
121 // used for noChangeLights in setPowerState()
122 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
123
124 static final boolean ANIMATE_SCREEN_LIGHTS = true;
125 static final boolean ANIMATE_BUTTON_LIGHTS = false;
126 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
127
128 static final int ANIM_STEPS = 60/4;
129
130 // These magic numbers are the initial state of the LEDs at boot. Ideally
131 // we should read them from the driver, but our current hardware returns 0
132 // for the initial value. Oops!
133 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
134 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
135 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
136
137 static final int LOG_POWER_SLEEP_REQUESTED = 2724;
138 static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
139 static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
140 static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
141 static final int LOG_POWER_SCREEN_STATE = 2728;
142 static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
143
144 private final int MY_UID;
145
146 private boolean mDoneBooting = false;
147 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700148 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
149 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 private int mPartialCount = 0;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700151 private int mProximityCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 private int mPowerState;
153 private boolean mOffBecauseOfUser;
154 private int mUserState;
155 private boolean mKeyboardVisible = false;
156 private boolean mUserActivityAllowed = true;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700157 private boolean mProximitySensorActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private int mTotalDelaySetting;
159 private int mKeylightDelay;
160 private int mDimDelay;
161 private int mScreenOffDelay;
162 private int mWakeLockState;
163 private long mLastEventTime = 0;
164 private long mScreenOffTime;
165 private volatile WindowManagerPolicy mPolicy;
166 private final LockList mLocks = new LockList();
167 private Intent mScreenOffIntent;
168 private Intent mScreenOnIntent;
The Android Open Source Project10592532009-03-18 17:39:46 -0700169 private HardwareService mHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 private Context mContext;
171 private UnsynchronizedWakeLock mBroadcastWakeLock;
172 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
173 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
174 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
175 private HandlerThread mHandlerThread;
176 private Handler mHandler;
177 private TimeoutTask mTimeoutTask = new TimeoutTask();
178 private LightAnimator mLightAnimator = new LightAnimator();
179 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700180 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700182 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700184 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700185 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 private boolean mIsPowered = false;
187 private IActivityManager mActivityService;
188 private IBatteryStats mBatteryStats;
189 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700190 private SensorManager mSensorManager;
191 private Sensor mProximitySensor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 private boolean mDimScreen = true;
193 private long mNextTimeout;
194 private volatile int mPokey = 0;
195 private volatile boolean mPokeAwakeOnSet = false;
196 private volatile boolean mInitComplete = false;
197 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
198 private long mScreenOnTime;
199 private long mScreenOnStartTime;
200 private boolean mPreventScreenOn;
201 private int mScreenBrightnessOverride = -1;
202
203 // Used when logging number and duration of touch-down cycles
204 private long mTotalTouchDownTime;
205 private long mLastTouchDown;
206 private int mTouchCycles;
207
208 // could be either static or controllable at runtime
209 private static final boolean mSpew = false;
210
211 /*
212 static PrintStream mLog;
213 static {
214 try {
215 mLog = new PrintStream("/data/power.log");
216 }
217 catch (FileNotFoundException e) {
218 android.util.Log.e(TAG, "Life is hard", e);
219 }
220 }
221 static class Log {
222 static void d(String tag, String s) {
223 mLog.println(s);
224 android.util.Log.d(tag, s);
225 }
226 static void i(String tag, String s) {
227 mLog.println(s);
228 android.util.Log.i(tag, s);
229 }
230 static void w(String tag, String s) {
231 mLog.println(s);
232 android.util.Log.w(tag, s);
233 }
234 static void e(String tag, String s) {
235 mLog.println(s);
236 android.util.Log.e(tag, s);
237 }
238 }
239 */
240
241 /**
242 * This class works around a deadlock between the lock in PowerManager.WakeLock
243 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
244 * mToken object so it can be accessed from any thread, but it calls into here
245 * with its lock held. This class is essentially a reimplementation of
246 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
247 * only call it with our own locks held.
248 */
249 private class UnsynchronizedWakeLock {
250 int mFlags;
251 String mTag;
252 IBinder mToken;
253 int mCount = 0;
254 boolean mRefCounted;
255
256 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
257 mFlags = flags;
258 mTag = tag;
259 mToken = new Binder();
260 mRefCounted = refCounted;
261 }
262
263 public void acquire() {
264 if (!mRefCounted || mCount++ == 0) {
265 long ident = Binder.clearCallingIdentity();
266 try {
267 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
268 MY_UID, mTag);
269 } finally {
270 Binder.restoreCallingIdentity(ident);
271 }
272 }
273 }
274
275 public void release() {
276 if (!mRefCounted || --mCount == 0) {
277 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
278 }
279 if (mCount < 0) {
280 throw new RuntimeException("WakeLock under-locked " + mTag);
281 }
282 }
283
284 public String toString() {
285 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
286 + " mCount=" + mCount + ")";
287 }
288 }
289
290 private final class BatteryReceiver extends BroadcastReceiver {
291 @Override
292 public void onReceive(Context context, Intent intent) {
293 synchronized (mLocks) {
294 boolean wasPowered = mIsPowered;
295 mIsPowered = mBatteryService.isPowered();
296
297 if (mIsPowered != wasPowered) {
298 // update mStayOnWhilePluggedIn wake lock
299 updateWakeLockLocked();
300
301 // treat plugging and unplugging the devices as a user activity.
302 // users find it disconcerting when they unplug the device
303 // and it shuts off right away.
304 // temporarily set mUserActivityAllowed to true so this will work
305 // even when the keyguard is on.
306 synchronized (mLocks) {
307 boolean savedActivityAllowed = mUserActivityAllowed;
308 mUserActivityAllowed = true;
309 userActivity(SystemClock.uptimeMillis(), false);
310 mUserActivityAllowed = savedActivityAllowed;
311 }
312 }
313 }
314 }
315 }
316
317 /**
318 * Set the setting that determines whether the device stays on when plugged in.
319 * The argument is a bit string, with each bit specifying a power source that,
320 * when the device is connected to that source, causes the device to stay on.
321 * See {@link android.os.BatteryManager} for the list of power sources that
322 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
323 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
324 * @param val an {@code int} containing the bits that specify which power sources
325 * should cause the device to stay on.
326 */
327 public void setStayOnSetting(int val) {
328 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
329 Settings.System.putInt(mContext.getContentResolver(),
330 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
331 }
332
333 private class SettingsObserver implements Observer {
334 private int getInt(String name) {
335 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
336 }
337
338 public void update(Observable o, Object arg) {
339 synchronized (mLocks) {
340 // STAY_ON_WHILE_PLUGGED_IN
341 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
342 updateWakeLockLocked();
343
344 // SCREEN_OFF_TIMEOUT
345 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
346
347 // DIM_SCREEN
348 //mDimScreen = getInt(DIM_SCREEN) != 0;
349
350 // recalculate everything
351 setScreenOffTimeoutsLocked();
352 }
353 }
354 }
355
356 PowerManagerService()
357 {
358 // Hack to get our uid... should have a func for this.
359 long token = Binder.clearCallingIdentity();
360 MY_UID = Binder.getCallingUid();
361 Binder.restoreCallingIdentity(token);
362
363 // XXX remove this when the kernel doesn't timeout wake locks
364 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
365
366 // assume nothing is on yet
367 mUserState = mPowerState = 0;
368
369 // Add ourself to the Watchdog monitors.
370 Watchdog.getInstance().addMonitor(this);
371 mScreenOnStartTime = SystemClock.elapsedRealtime();
372 }
373
374 private ContentQueryMap mSettings;
375
The Android Open Source Project10592532009-03-18 17:39:46 -0700376 void init(Context context, HardwareService hardware, IActivityManager activity,
377 BatteryService battery) {
378 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 mContext = context;
380 mActivityService = activity;
381 mBatteryStats = BatteryStatsService.getService();
382 mBatteryService = battery;
383
384 mHandlerThread = new HandlerThread("PowerManagerService") {
385 @Override
386 protected void onLooperPrepared() {
387 super.onLooperPrepared();
388 initInThread();
389 }
390 };
391 mHandlerThread.start();
392
393 synchronized (mHandlerThread) {
394 while (!mInitComplete) {
395 try {
396 mHandlerThread.wait();
397 } catch (InterruptedException e) {
398 // Ignore
399 }
400 }
401 }
402 }
403
404 void initInThread() {
405 mHandler = new Handler();
406
407 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700408 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
410 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
411 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
412 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
413 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
414 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
415
416 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
417 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
418 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
419 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
420
421 ContentResolver resolver = mContext.getContentResolver();
422 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
423 "(" + Settings.System.NAME + "=?) or ("
424 + Settings.System.NAME + "=?) or ("
425 + Settings.System.NAME + "=?)",
426 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN},
427 null);
428 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
429 SettingsObserver settingsObserver = new SettingsObserver();
430 mSettings.addObserver(settingsObserver);
431
432 // pretend that the settings changed so we will get their initial state
433 settingsObserver.update(mSettings, null);
434
435 // register for the battery changed notifications
436 IntentFilter filter = new IntentFilter();
437 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
438 mContext.registerReceiver(new BatteryReceiver(), filter);
439
440 // Listen for Gservices changes
441 IntentFilter gservicesChangedFilter =
442 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
443 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
444 // And explicitly do the initial update of our cached settings
445 updateGservicesValues();
446
447 // turn everything on
448 setPowerState(ALL_BRIGHT);
Dan Murphy951764b2009-08-27 14:59:03 -0500449
450 // set auto brightness mode to user setting
451 boolean brightnessMode = Settings.System.getInt(resolver, SCREEN_BRIGHTNESS_MODE, 1) != 0;
452 mHardware.setAutoBrightness_UNCHECKED(brightnessMode);
453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 synchronized (mHandlerThread) {
455 mInitComplete = true;
456 mHandlerThread.notifyAll();
457 }
458 }
459
460 private class WakeLock implements IBinder.DeathRecipient
461 {
462 WakeLock(int f, IBinder b, String t, int u) {
463 super();
464 flags = f;
465 binder = b;
466 tag = t;
467 uid = u == MY_UID ? Process.SYSTEM_UID : u;
468 if (u != MY_UID || (
469 !"KEEP_SCREEN_ON_FLAG".equals(tag)
470 && !"KeyInputQueue".equals(tag))) {
471 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
472 ? BatteryStats.WAKE_TYPE_PARTIAL
473 : BatteryStats.WAKE_TYPE_FULL;
474 } else {
475 monitorType = -1;
476 }
477 try {
478 b.linkToDeath(this, 0);
479 } catch (RemoteException e) {
480 binderDied();
481 }
482 }
483 public void binderDied() {
484 synchronized (mLocks) {
485 releaseWakeLockLocked(this.binder, true);
486 }
487 }
488 final int flags;
489 final IBinder binder;
490 final String tag;
491 final int uid;
492 final int monitorType;
493 boolean activated = true;
494 int minState;
495 }
496
497 private void updateWakeLockLocked() {
498 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
499 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
500 mStayOnWhilePluggedInScreenDimLock.acquire();
501 mStayOnWhilePluggedInPartialLock.acquire();
502 } else {
503 mStayOnWhilePluggedInScreenDimLock.release();
504 mStayOnWhilePluggedInPartialLock.release();
505 }
506 }
507
508 private boolean isScreenLock(int flags)
509 {
510 int n = flags & LOCK_MASK;
511 return n == PowerManager.FULL_WAKE_LOCK
512 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
513 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
514 }
515
516 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700518 if (uid != Process.myUid()) {
519 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 long ident = Binder.clearCallingIdentity();
522 try {
523 synchronized (mLocks) {
524 acquireWakeLockLocked(flags, lock, uid, tag);
525 }
526 } finally {
527 Binder.restoreCallingIdentity(ident);
528 }
529 }
530
531 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
532 int acquireUid = -1;
533 String acquireName = null;
534 int acquireType = -1;
535
536 if (mSpew) {
537 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
538 }
539
540 int index = mLocks.getIndex(lock);
541 WakeLock wl;
542 boolean newlock;
543 if (index < 0) {
544 wl = new WakeLock(flags, lock, tag, uid);
545 switch (wl.flags & LOCK_MASK)
546 {
547 case PowerManager.FULL_WAKE_LOCK:
548 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
549 break;
550 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
551 wl.minState = SCREEN_BRIGHT;
552 break;
553 case PowerManager.SCREEN_DIM_WAKE_LOCK:
554 wl.minState = SCREEN_DIM;
555 break;
556 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700557 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 break;
559 default:
560 // just log and bail. we're in the server, so don't
561 // throw an exception.
562 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
563 + " flags=" + flags);
564 return;
565 }
566 mLocks.addLock(wl);
567 newlock = true;
568 } else {
569 wl = mLocks.get(index);
570 newlock = false;
571 }
572 if (isScreenLock(flags)) {
573 // if this causes a wakeup, we reactivate all of the locks and
574 // set it to whatever they want. otherwise, we modulate that
575 // by the current state so we never turn it more on than
576 // it already is.
577 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700578 int oldWakeLockState = mWakeLockState;
579 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 if (mSpew) {
581 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700582 + " mWakeLockState=0x"
583 + Integer.toHexString(mWakeLockState)
584 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 } else {
587 if (mSpew) {
588 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
589 + " mLocks.gatherState()=0x"
590 + Integer.toHexString(mLocks.gatherState())
591 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
592 }
593 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
594 }
595 setPowerState(mWakeLockState | mUserState);
596 }
597 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
598 if (newlock) {
599 mPartialCount++;
600 if (mPartialCount == 1) {
601 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
602 }
603 }
604 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700605 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
606 mProximityCount++;
607 if (mProximityCount == 1) {
608 enableProximityLockLocked();
609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 }
611 if (newlock) {
612 acquireUid = wl.uid;
613 acquireName = wl.tag;
614 acquireType = wl.monitorType;
615 }
616
617 if (acquireType >= 0) {
618 try {
619 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
620 } catch (RemoteException e) {
621 // Ignore
622 }
623 }
624 }
625
626 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700627 int uid = Binder.getCallingUid();
628 if (uid != Process.myUid()) {
629 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631
632 synchronized (mLocks) {
633 releaseWakeLockLocked(lock, false);
634 }
635 }
636
637 private void releaseWakeLockLocked(IBinder lock, boolean death) {
638 int releaseUid;
639 String releaseName;
640 int releaseType;
641
642 WakeLock wl = mLocks.removeLock(lock);
643 if (wl == null) {
644 return;
645 }
646
647 if (mSpew) {
648 Log.d(TAG, "releaseWakeLock flags=0x"
649 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
650 }
651
652 if (isScreenLock(wl.flags)) {
653 mWakeLockState = mLocks.gatherState();
654 // goes in the middle to reduce flicker
655 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
656 userActivity(SystemClock.uptimeMillis(), false);
657 }
658 setPowerState(mWakeLockState | mUserState);
659 }
660 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
661 mPartialCount--;
662 if (mPartialCount == 0) {
663 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
664 Power.releaseWakeLock(PARTIAL_NAME);
665 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700666 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
667 mProximityCount--;
668 if (mProximityCount == 0) {
669 disableProximityLockLocked();
670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 }
672 // Unlink the lock from the binder.
673 wl.binder.unlinkToDeath(wl, 0);
674 releaseUid = wl.uid;
675 releaseName = wl.tag;
676 releaseType = wl.monitorType;
677
678 if (releaseType >= 0) {
679 long origId = Binder.clearCallingIdentity();
680 try {
681 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
682 } catch (RemoteException e) {
683 // Ignore
684 } finally {
685 Binder.restoreCallingIdentity(origId);
686 }
687 }
688 }
689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 private class PokeLock implements IBinder.DeathRecipient
691 {
692 PokeLock(int p, IBinder b, String t) {
693 super();
694 this.pokey = p;
695 this.binder = b;
696 this.tag = t;
697 try {
698 b.linkToDeath(this, 0);
699 } catch (RemoteException e) {
700 binderDied();
701 }
702 }
703 public void binderDied() {
704 setPokeLock(0, this.binder, this.tag);
705 }
706 int pokey;
707 IBinder binder;
708 String tag;
709 boolean awakeOnSet;
710 }
711
712 public void setPokeLock(int pokey, IBinder token, String tag) {
713 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
714 if (token == null) {
715 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
716 return;
717 }
718
719 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
720 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
721 + " and POKE_LOCK_MEDIUM_TIMEOUT");
722 }
723
724 synchronized (mLocks) {
725 if (pokey != 0) {
726 PokeLock p = mPokeLocks.get(token);
727 int oldPokey = 0;
728 if (p != null) {
729 oldPokey = p.pokey;
730 p.pokey = pokey;
731 } else {
732 p = new PokeLock(pokey, token, tag);
733 mPokeLocks.put(token, p);
734 }
735 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
736 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
737 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
738 p.awakeOnSet = true;
739 }
740 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700741 PokeLock rLock = mPokeLocks.remove(token);
742 if (rLock != null) {
743 token.unlinkToDeath(rLock, 0);
744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 }
746
747 int oldPokey = mPokey;
748 int cumulative = 0;
749 boolean oldAwakeOnSet = mPokeAwakeOnSet;
750 boolean awakeOnSet = false;
751 for (PokeLock p: mPokeLocks.values()) {
752 cumulative |= p.pokey;
753 if (p.awakeOnSet) {
754 awakeOnSet = true;
755 }
756 }
757 mPokey = cumulative;
758 mPokeAwakeOnSet = awakeOnSet;
759
760 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
761 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
762
763 if (oldCumulativeTimeout != newCumulativeTimeout) {
764 setScreenOffTimeoutsLocked();
765 // reset the countdown timer, but use the existing nextState so it doesn't
766 // change anything
767 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
768 }
769 }
770 }
771
772 private static String lockType(int type)
773 {
774 switch (type)
775 {
776 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700777 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700779 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700781 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700783 return "PARTIAL_WAKE_LOCK ";
784 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
785 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 default:
David Brown251faa62009-08-02 22:04:36 -0700787 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 }
789 }
790
791 private static String dumpPowerState(int state) {
792 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
793 ? "KEYBOARD_BRIGHT_BIT " : "")
794 + (((state & SCREEN_BRIGHT_BIT) != 0)
795 ? "SCREEN_BRIGHT_BIT " : "")
796 + (((state & SCREEN_ON_BIT) != 0)
797 ? "SCREEN_ON_BIT " : "")
798 + (((state & BATTERY_LOW_BIT) != 0)
799 ? "BATTERY_LOW_BIT " : "");
800 }
801
802 @Override
803 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
804 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
805 != PackageManager.PERMISSION_GRANTED) {
806 pw.println("Permission Denial: can't dump PowerManager from from pid="
807 + Binder.getCallingPid()
808 + ", uid=" + Binder.getCallingUid());
809 return;
810 }
811
812 long now = SystemClock.uptimeMillis();
813
814 pw.println("Power Manager State:");
815 pw.println(" mIsPowered=" + mIsPowered
816 + " mPowerState=" + mPowerState
817 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
818 + " ms");
819 pw.println(" mPartialCount=" + mPartialCount);
820 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
821 pw.println(" mUserState=" + dumpPowerState(mUserState));
822 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
823 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
824 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
825 + " " + ((mNextTimeout-now)/1000) + "s from now");
826 pw.println(" mDimScreen=" + mDimScreen
827 + " mStayOnConditions=" + mStayOnConditions);
828 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
829 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700830 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
831 + ',' + mBroadcastQueue[2] + "}");
832 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
833 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
835 pw.println(" mKeyboardVisible=" + mKeyboardVisible
836 + " mUserActivityAllowed=" + mUserActivityAllowed);
837 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
838 + " mScreenOffDelay=" + mScreenOffDelay);
839 pw.println(" mPreventScreenOn=" + mPreventScreenOn
840 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
841 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
842 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
843 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
844 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
845 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
846 mScreenBrightness.dump(pw, " mScreenBrightness: ");
847 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
848 mButtonBrightness.dump(pw, " mButtonBrightness: ");
849
850 int N = mLocks.size();
851 pw.println();
852 pw.println("mLocks.size=" + N + ":");
853 for (int i=0; i<N; i++) {
854 WakeLock wl = mLocks.get(i);
855 String type = lockType(wl.flags & LOCK_MASK);
856 String acquireCausesWakeup = "";
857 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
858 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
859 }
860 String activated = "";
861 if (wl.activated) {
862 activated = " activated";
863 }
864 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
865 + activated + " (minState=" + wl.minState + ")");
866 }
867
868 pw.println();
869 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
870 for (PokeLock p: mPokeLocks.values()) {
871 pw.println(" poke lock '" + p.tag + "':"
872 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
873 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700874 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
875 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
877 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
878 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
879 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
880 }
881
882 pw.println();
883 }
884
885 private void setTimeoutLocked(long now, int nextState)
886 {
887 if (mDoneBooting) {
888 mHandler.removeCallbacks(mTimeoutTask);
889 mTimeoutTask.nextState = nextState;
890 long when = now;
891 switch (nextState)
892 {
893 case SCREEN_BRIGHT:
894 when += mKeylightDelay;
895 break;
896 case SCREEN_DIM:
897 if (mDimDelay >= 0) {
898 when += mDimDelay;
899 break;
900 } else {
901 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
902 }
903 case SCREEN_OFF:
904 synchronized (mLocks) {
905 when += mScreenOffDelay;
906 }
907 break;
908 }
909 if (mSpew) {
910 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
911 + " when=" + when);
912 }
913 mHandler.postAtTime(mTimeoutTask, when);
914 mNextTimeout = when; // for debugging
915 }
916 }
917
918 private void cancelTimerLocked()
919 {
920 mHandler.removeCallbacks(mTimeoutTask);
921 mTimeoutTask.nextState = -1;
922 }
923
924 private class TimeoutTask implements Runnable
925 {
926 int nextState; // access should be synchronized on mLocks
927 public void run()
928 {
929 synchronized (mLocks) {
930 if (mSpew) {
931 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
932 }
933
934 if (nextState == -1) {
935 return;
936 }
937
938 mUserState = this.nextState;
939 setPowerState(this.nextState | mWakeLockState);
940
941 long now = SystemClock.uptimeMillis();
942
943 switch (this.nextState)
944 {
945 case SCREEN_BRIGHT:
946 if (mDimDelay >= 0) {
947 setTimeoutLocked(now, SCREEN_DIM);
948 break;
949 }
950 case SCREEN_DIM:
951 setTimeoutLocked(now, SCREEN_OFF);
952 break;
953 }
954 }
955 }
956 }
957
958 private void sendNotificationLocked(boolean on, int why)
959 {
Mike Lockwoodddfe8792009-08-27 13:27:08 -0700960 if (mProximitySensorActive) {
961 why = WindowManagerPolicy.OFF_BECAUSE_OF_PROXIMITY_SENSOR;
962 }
Joe Onorato64c62ba2009-03-24 20:13:57 -0700963 if (!on) {
964 mStillNeedSleepNotification = false;
965 }
966
Joe Onorato128e7292009-03-24 18:41:31 -0700967 // Add to the queue.
968 int index = 0;
969 while (mBroadcastQueue[index] != -1) {
970 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 }
Joe Onorato128e7292009-03-24 18:41:31 -0700972 mBroadcastQueue[index] = on ? 1 : 0;
973 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974
Joe Onorato128e7292009-03-24 18:41:31 -0700975 // If we added it position 2, then there is a pair that can be stripped.
976 // If we added it position 1 and we're turning the screen off, we can strip
977 // the pair and do nothing, because the screen is already off, and therefore
978 // keyguard has already been enabled.
979 // However, if we added it at position 1 and we're turning it on, then position
980 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
981 // on, so have to run the queue then.
982 if (index == 2) {
983 // Also, while we're collapsing them, if it's going to be an "off," and one
984 // is off because of user, then use that, regardless of whether it's the first
985 // or second one.
986 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
987 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
988 }
989 mBroadcastQueue[0] = on ? 1 : 0;
990 mBroadcastQueue[1] = -1;
991 mBroadcastQueue[2] = -1;
992 index = 0;
993 }
994 if (index == 1 && !on) {
995 mBroadcastQueue[0] = -1;
996 mBroadcastQueue[1] = -1;
997 index = -1;
998 // The wake lock was being held, but we're not actually going to do any
999 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1001 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001002 }
1003
1004 // Now send the message.
1005 if (index >= 0) {
1006 // Acquire the broadcast wake lock before changing the power
1007 // state. It will be release after the broadcast is sent.
1008 // We always increment the ref count for each notification in the queue
1009 // and always decrement when that notification is handled.
1010 mBroadcastWakeLock.acquire();
1011 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1012 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 }
1014 }
1015
1016 private Runnable mNotificationTask = new Runnable()
1017 {
1018 public void run()
1019 {
Joe Onorato128e7292009-03-24 18:41:31 -07001020 while (true) {
1021 int value;
1022 int why;
1023 WindowManagerPolicy policy;
1024 synchronized (mLocks) {
1025 value = mBroadcastQueue[0];
1026 why = mBroadcastWhy[0];
1027 for (int i=0; i<2; i++) {
1028 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1029 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1030 }
1031 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 }
Joe Onorato128e7292009-03-24 18:41:31 -07001033 if (value == 1) {
1034 mScreenOnStart = SystemClock.uptimeMillis();
1035
1036 policy.screenTurnedOn();
1037 try {
1038 ActivityManagerNative.getDefault().wakingUp();
1039 } catch (RemoteException e) {
1040 // ignore it
1041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042
Joe Onorato128e7292009-03-24 18:41:31 -07001043 if (mSpew) {
1044 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1045 }
1046 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1047 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1048 mScreenOnBroadcastDone, mHandler, 0, null, null);
1049 } else {
1050 synchronized (mLocks) {
1051 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1052 mBroadcastWakeLock.mCount);
1053 mBroadcastWakeLock.release();
1054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
1056 }
Joe Onorato128e7292009-03-24 18:41:31 -07001057 else if (value == 0) {
1058 mScreenOffStart = SystemClock.uptimeMillis();
1059
1060 policy.screenTurnedOff(why);
1061 try {
1062 ActivityManagerNative.getDefault().goingToSleep();
1063 } catch (RemoteException e) {
1064 // ignore it.
1065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066
Joe Onorato128e7292009-03-24 18:41:31 -07001067 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1068 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1069 mScreenOffBroadcastDone, mHandler, 0, null, null);
1070 } else {
1071 synchronized (mLocks) {
1072 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1073 mBroadcastWakeLock.mCount);
1074 mBroadcastWakeLock.release();
1075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 }
1077 }
Joe Onorato128e7292009-03-24 18:41:31 -07001078 else {
1079 // If we're in this case, then this handler is running for a previous
1080 // paired transaction. mBroadcastWakeLock will already have been released.
1081 break;
1082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 }
1084 }
1085 };
1086
1087 long mScreenOnStart;
1088 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1089 public void onReceive(Context context, Intent intent) {
1090 synchronized (mLocks) {
1091 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1092 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1093 mBroadcastWakeLock.release();
1094 }
1095 }
1096 };
1097
1098 long mScreenOffStart;
1099 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1100 public void onReceive(Context context, Intent intent) {
1101 synchronized (mLocks) {
1102 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1103 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1104 mBroadcastWakeLock.release();
1105 }
1106 }
1107 };
1108
1109 void logPointerUpEvent() {
1110 if (LOG_TOUCH_DOWNS) {
1111 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1112 mLastTouchDown = 0;
1113 }
1114 }
1115
1116 void logPointerDownEvent() {
1117 if (LOG_TOUCH_DOWNS) {
1118 // If we are not already timing a down/up sequence
1119 if (mLastTouchDown == 0) {
1120 mLastTouchDown = SystemClock.elapsedRealtime();
1121 mTouchCycles++;
1122 }
1123 }
1124 }
1125
1126 /**
1127 * Prevents the screen from turning on even if it *should* turn on due
1128 * to a subsequent full wake lock being acquired.
1129 * <p>
1130 * This is a temporary hack that allows an activity to "cover up" any
1131 * display glitches that happen during the activity's startup
1132 * sequence. (Specifically, this API was added to work around a
1133 * cosmetic bug in the "incoming call" sequence, where the lock screen
1134 * would flicker briefly before the incoming call UI became visible.)
1135 * TODO: There ought to be a more elegant way of doing this,
1136 * probably by having the PowerManager and ActivityManager
1137 * work together to let apps specify that the screen on/off
1138 * state should be synchronized with the Activity lifecycle.
1139 * <p>
1140 * Note that calling preventScreenOn(true) will NOT turn the screen
1141 * off if it's currently on. (This API only affects *future*
1142 * acquisitions of full wake locks.)
1143 * But calling preventScreenOn(false) WILL turn the screen on if
1144 * it's currently off because of a prior preventScreenOn(true) call.
1145 * <p>
1146 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1147 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1148 * call doesn't occur within 5 seconds, we'll turn the screen back on
1149 * ourselves (and log a warning about it); this prevents a buggy app
1150 * from disabling the screen forever.)
1151 * <p>
1152 * TODO: this feature should really be controlled by a new type of poke
1153 * lock (rather than an IPowerManager call).
1154 */
1155 public void preventScreenOn(boolean prevent) {
1156 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1157
1158 synchronized (mLocks) {
1159 if (prevent) {
1160 // First of all, grab a partial wake lock to
1161 // make sure the CPU stays on during the entire
1162 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1163 mPreventScreenOnPartialLock.acquire();
1164
1165 // Post a forceReenableScreen() call (for 5 seconds in the
1166 // future) to make sure the matching preventScreenOn(false) call
1167 // has happened by then.
1168 mHandler.removeCallbacks(mForceReenableScreenTask);
1169 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1170
1171 // Finally, set the flag that prevents the screen from turning on.
1172 // (Below, in setPowerState(), we'll check mPreventScreenOn and
1173 // we *won't* call Power.setScreenState(true) if it's set.)
1174 mPreventScreenOn = true;
1175 } else {
1176 // (Re)enable the screen.
1177 mPreventScreenOn = false;
1178
1179 // We're "undoing" a the prior preventScreenOn(true) call, so we
1180 // no longer need the 5-second safeguard.
1181 mHandler.removeCallbacks(mForceReenableScreenTask);
1182
1183 // Forcibly turn on the screen if it's supposed to be on. (This
1184 // handles the case where the screen is currently off because of
1185 // a prior preventScreenOn(true) call.)
1186 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1187 if (mSpew) {
1188 Log.d(TAG,
1189 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1190 }
1191 int err = Power.setScreenState(true);
1192 if (err != 0) {
1193 Log.w(TAG, "preventScreenOn: error from Power.setScreenState(): " + err);
1194 }
1195 }
1196
1197 // Release the partial wake lock that we held during the
1198 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1199 mPreventScreenOnPartialLock.release();
1200 }
1201 }
1202 }
1203
1204 public void setScreenBrightnessOverride(int brightness) {
1205 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1206
1207 synchronized (mLocks) {
1208 if (mScreenBrightnessOverride != brightness) {
1209 mScreenBrightnessOverride = brightness;
1210 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1211 }
1212 }
1213 }
1214
1215 /**
1216 * Sanity-check that gets called 5 seconds after any call to
1217 * preventScreenOn(true). This ensures that the original call
1218 * is followed promptly by a call to preventScreenOn(false).
1219 */
1220 private void forceReenableScreen() {
1221 // We shouldn't get here at all if mPreventScreenOn is false, since
1222 // we should have already removed any existing
1223 // mForceReenableScreenTask messages...
1224 if (!mPreventScreenOn) {
1225 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1226 return;
1227 }
1228
1229 // Uh oh. It's been 5 seconds since a call to
1230 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1231 // This means the app that called preventScreenOn(true) is either
1232 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1233 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1234 // crashed before doing so.)
1235
1236 // Log a warning, and forcibly turn the screen back on.
1237 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1238 + "Forcing the screen back on...");
1239 preventScreenOn(false);
1240 }
1241
1242 private Runnable mForceReenableScreenTask = new Runnable() {
1243 public void run() {
1244 forceReenableScreen();
1245 }
1246 };
1247
1248 private void setPowerState(int state)
1249 {
1250 setPowerState(state, false, false);
1251 }
1252
1253 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1254 {
1255 synchronized (mLocks) {
1256 int err;
1257
1258 if (mSpew) {
1259 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1260 + " newState=0x" + Integer.toHexString(newState)
1261 + " noChangeLights=" + noChangeLights);
1262 }
1263
1264 if (noChangeLights) {
1265 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1266 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001267 if (mProximitySensorActive) {
1268 // don't turn on the screen when the proximity sensor lock is held
1269 newState = (newState & ~SCREEN_BRIGHT);
1270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271
1272 if (batteryIsLow()) {
1273 newState |= BATTERY_LOW_BIT;
1274 } else {
1275 newState &= ~BATTERY_LOW_BIT;
1276 }
1277 if (newState == mPowerState) {
1278 return;
1279 }
1280
1281 if (!mDoneBooting) {
1282 newState |= ALL_BRIGHT;
1283 }
1284
1285 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1286 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1287
1288 if (mSpew) {
1289 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1290 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1291 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1292 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1293 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1294 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1295 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1296 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1297 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1298 + " newScreenOn=" + newScreenOn);
1299 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1300 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1301 }
1302
1303 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001304 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1306 }
1307
1308 if (oldScreenOn != newScreenOn) {
1309 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001310 // When the user presses the power button, we need to always send out the
1311 // notification that it's going to sleep so the keyguard goes on. But
1312 // we can't do that until the screen fades out, so we don't show the keyguard
1313 // too early.
1314 if (mStillNeedSleepNotification) {
1315 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1316 }
1317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 // Turn on the screen UNLESS there was a prior
1319 // preventScreenOn(true) request. (Note that the lifetime
1320 // of a single preventScreenOn() request is limited to 5
1321 // seconds to prevent a buggy app from disabling the
1322 // screen forever; see forceReenableScreen().)
1323 boolean reallyTurnScreenOn = true;
1324 if (mSpew) {
1325 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1326 + mPreventScreenOn);
1327 }
1328
1329 if (mPreventScreenOn) {
1330 if (mSpew) {
1331 Log.d(TAG, "- PREVENTING screen from really turning on!");
1332 }
1333 reallyTurnScreenOn = false;
1334 }
1335 if (reallyTurnScreenOn) {
1336 err = Power.setScreenState(true);
1337 long identity = Binder.clearCallingIdentity();
1338 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001339 mBatteryStats.noteScreenBrightness(
1340 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 mBatteryStats.noteScreenOn();
1342 } catch (RemoteException e) {
1343 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1344 } finally {
1345 Binder.restoreCallingIdentity(identity);
1346 }
1347 } else {
1348 Power.setScreenState(false);
1349 // But continue as if we really did turn the screen on...
1350 err = 0;
1351 }
1352
1353 mScreenOnStartTime = SystemClock.elapsedRealtime();
1354 mLastTouchDown = 0;
1355 mTotalTouchDownTime = 0;
1356 mTouchCycles = 0;
1357 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1358 mTotalTouchDownTime, mTouchCycles);
1359 if (err == 0) {
1360 mPowerState |= SCREEN_ON_BIT;
1361 sendNotificationLocked(true, -1);
1362 }
1363 } else {
1364 mScreenOffTime = SystemClock.elapsedRealtime();
1365 long identity = Binder.clearCallingIdentity();
1366 try {
1367 mBatteryStats.noteScreenOff();
1368 } catch (RemoteException e) {
1369 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1370 } finally {
1371 Binder.restoreCallingIdentity(identity);
1372 }
1373 mPowerState &= ~SCREEN_ON_BIT;
1374 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001375 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 } else {
1377 mOffBecauseOfUser = becauseOfUser;
1378 err = 0;
1379 mLastTouchDown = 0;
1380 }
1381 }
1382 }
1383 }
1384 }
1385
Joe Onorato128e7292009-03-24 18:41:31 -07001386 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 // I don't think we need to check the current state here because all of these
1388 // Power.setScreenState and sendNotificationLocked can both handle being
1389 // called multiple times in the same state. -joeo
1390 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1391 mTotalTouchDownTime, mTouchCycles);
1392 mLastTouchDown = 0;
1393 int err = Power.setScreenState(false);
1394 if (mScreenOnStartTime != 0) {
1395 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1396 mScreenOnStartTime = 0;
1397 }
1398 if (err == 0) {
1399 int why = becauseOfUser
1400 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1401 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1402 sendNotificationLocked(false, why);
1403 }
1404 return err;
1405 }
1406
1407 private boolean batteryIsLow() {
1408 return (!mIsPowered &&
1409 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1410 }
1411
The Android Open Source Project10592532009-03-18 17:39:46 -07001412 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001413 final int oldState = mPowerState;
1414 final int realDifference = (newState ^ oldState);
1415 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001417 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
1419
1420 int offMask = 0;
1421 int dimMask = 0;
1422 int onMask = 0;
1423
1424 int preferredBrightness = getPreferredBrightness();
1425 boolean startAnimation = false;
1426
1427 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1428 if (ANIMATE_KEYBOARD_LIGHTS) {
1429 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1430 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001431 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1432 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 } else {
1434 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001435 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1436 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 }
1438 startAnimation = true;
1439 } else {
1440 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001441 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001443 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 }
1445 }
1446 }
1447
1448 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1449 if (ANIMATE_BUTTON_LIGHTS) {
1450 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1451 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001452 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1453 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 } else {
1455 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001456 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1457 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 }
1459 startAnimation = true;
1460 } else {
1461 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001462 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001464 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 }
1466 }
1467 }
1468
1469 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1470 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001471 int nominalCurrentValue = -1;
1472 // If there was an actual difference in the light state, then
1473 // figure out the "ideal" current value based on the previous
1474 // state. Otherwise, this is a change due to the brightness
1475 // override, so we want to animate from whatever the current
1476 // value is.
1477 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1478 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1479 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1480 nominalCurrentValue = preferredBrightness;
1481 break;
1482 case SCREEN_ON_BIT:
1483 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1484 break;
1485 case 0:
1486 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1487 break;
1488 case SCREEN_BRIGHT_BIT:
1489 default:
1490 // not possible
1491 nominalCurrentValue = (int)mScreenBrightness.curValue;
1492 break;
1493 }
Joe Onorato128e7292009-03-24 18:41:31 -07001494 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001495 int brightness = preferredBrightness;
1496 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1498 // dim or turn off backlight, depending on if the screen is on
1499 // the scale is because the brightness ramp isn't linear and this biases
1500 // it so the later parts take longer.
1501 final float scale = 1.5f;
1502 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1503 if (ratio > 1.0f) ratio = 1.0f;
1504 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1506 // was bright
1507 steps = ANIM_STEPS;
1508 } else {
1509 // was dim
1510 steps = (int)(ANIM_STEPS*ratio*scale);
1511 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001512 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 if ((oldState & SCREEN_ON_BIT) != 0) {
1515 // was bright
1516 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1517 } else {
1518 // was dim
1519 steps = (int)(ANIM_STEPS*ratio);
1520 }
1521 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1522 // If the "stay on while plugged in" option is
1523 // turned on, then the screen will often not
1524 // automatically turn off while plugged in. To
1525 // still have a sense of when it is inactive, we
1526 // will then count going dim as turning off.
1527 mScreenOffTime = SystemClock.elapsedRealtime();
1528 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001529 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001532 long identity = Binder.clearCallingIdentity();
1533 try {
1534 mBatteryStats.noteScreenBrightness(brightness);
1535 } catch (RemoteException e) {
1536 // Nothing interesting to do.
1537 } finally {
1538 Binder.restoreCallingIdentity(identity);
1539 }
1540 mScreenBrightness.setTargetLocked(brightness,
1541 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 startAnimation = true;
1543 } else {
1544 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1545 // dim or turn off backlight, depending on if the screen is on
1546 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001547 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001549 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
1551 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001552 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 }
1554 }
1555 }
1556
1557 if (startAnimation) {
1558 if (mSpew) {
1559 Log.i(TAG, "Scheduling light animator!");
1560 }
1561 mHandler.removeCallbacks(mLightAnimator);
1562 mHandler.post(mLightAnimator);
1563 }
1564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 if (offMask != 0) {
1566 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001567 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 }
1569 if (dimMask != 0) {
1570 int brightness = Power.BRIGHTNESS_DIM;
1571 if ((newState & BATTERY_LOW_BIT) != 0 &&
1572 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1573 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1574 }
1575 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001576 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
1578 if (onMask != 0) {
1579 int brightness = getPreferredBrightness();
1580 if ((newState & BATTERY_LOW_BIT) != 0 &&
1581 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1582 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1583 }
1584 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001585 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588
The Android Open Source Project10592532009-03-18 17:39:46 -07001589 private void setLightBrightness(int mask, int value) {
1590 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1591 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1592 }
1593 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1594 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1595 }
1596 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1597 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
1600
1601 class BrightnessState {
1602 final int mask;
1603
1604 boolean initialized;
1605 int targetValue;
1606 float curValue;
1607 float delta;
1608 boolean animating;
1609
1610 BrightnessState(int m) {
1611 mask = m;
1612 }
1613
1614 public void dump(PrintWriter pw, String prefix) {
1615 pw.println(prefix + "animating=" + animating
1616 + " targetValue=" + targetValue
1617 + " curValue=" + curValue
1618 + " delta=" + delta);
1619 }
1620
Joe Onorato128e7292009-03-24 18:41:31 -07001621 void setTargetLocked(int target, int stepsToTarget, int initialValue,
1622 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 if (!initialized) {
1624 initialized = true;
1625 curValue = (float)initialValue;
1626 }
1627 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001628 delta = (targetValue -
1629 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1630 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001632 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001634 + " target=" + targetValue + " delta=" + delta
1635 + " nominalCurrentValue=" + nominalCurrentValue
1636 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
1638 animating = true;
1639 }
1640
1641 boolean stepLocked() {
1642 if (!animating) return false;
1643 if (false && mSpew) {
1644 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1645 + " target=" + targetValue + " delta=" + delta);
1646 }
1647 curValue += delta;
1648 int curIntValue = (int)curValue;
1649 boolean more = true;
1650 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001651 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 more = false;
1653 } else if (delta > 0) {
1654 if (curIntValue >= targetValue) {
1655 curValue = curIntValue = targetValue;
1656 more = false;
1657 }
1658 } else {
1659 if (curIntValue <= targetValue) {
1660 curValue = curIntValue = targetValue;
1661 more = false;
1662 }
1663 }
1664 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001665 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 animating = more;
1667 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001668 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001669 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 }
1671 }
1672 return more;
1673 }
1674 }
1675
1676 private class LightAnimator implements Runnable {
1677 public void run() {
1678 synchronized (mLocks) {
1679 long now = SystemClock.uptimeMillis();
1680 boolean more = mScreenBrightness.stepLocked();
1681 if (mKeyboardBrightness.stepLocked()) {
1682 more = true;
1683 }
1684 if (mButtonBrightness.stepLocked()) {
1685 more = true;
1686 }
1687 if (more) {
1688 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1689 }
1690 }
1691 }
1692 }
1693
1694 private int getPreferredBrightness() {
1695 try {
1696 if (mScreenBrightnessOverride >= 0) {
1697 return mScreenBrightnessOverride;
1698 }
1699 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1700 SCREEN_BRIGHTNESS);
1701 // Don't let applications turn the screen all the way off
1702 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1703 } catch (SettingNotFoundException snfe) {
1704 return Power.BRIGHTNESS_ON;
1705 }
1706 }
1707
1708 boolean screenIsOn() {
1709 synchronized (mLocks) {
1710 return (mPowerState & SCREEN_ON_BIT) != 0;
1711 }
1712 }
1713
1714 boolean screenIsBright() {
1715 synchronized (mLocks) {
1716 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1717 }
1718 }
1719
1720 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1721 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1722 userActivity(time, noChangeLights, OTHER_EVENT, force);
1723 }
1724
1725 public void userActivity(long time, boolean noChangeLights) {
1726 userActivity(time, noChangeLights, OTHER_EVENT, false);
1727 }
1728
1729 public void userActivity(long time, boolean noChangeLights, int eventType) {
1730 userActivity(time, noChangeLights, eventType, false);
1731 }
1732
1733 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1734 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1735
1736 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001737 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001739 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 }
1741 return;
1742 }
1743
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001744 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1745 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1746 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1747 if (false) {
1748 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1749 }
1750 return;
1751 }
1752
1753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 if (false) {
1755 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1756 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1757 } else {
1758 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1759 }
1760 }
1761
1762 synchronized (mLocks) {
1763 if (mSpew) {
1764 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1765 + " mUserActivityAllowed=" + mUserActivityAllowed
1766 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001767 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1768 + " mProximitySensorActive=" + mProximitySensorActive
1769 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 }
1771 if (mLastEventTime <= time || force) {
1772 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001773 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 // Only turn on button backlights if a button was pressed.
1775 if (eventType == BUTTON_EVENT) {
1776 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1777 } else {
1778 // don't clear button/keyboard backlights when the screen is touched.
1779 mUserState |= SCREEN_BRIGHT;
1780 }
1781
Dianne Hackborn617f8772009-03-31 15:04:46 -07001782 int uid = Binder.getCallingUid();
1783 long ident = Binder.clearCallingIdentity();
1784 try {
1785 mBatteryStats.noteUserActivity(uid, eventType);
1786 } catch (RemoteException e) {
1787 // Ignore
1788 } finally {
1789 Binder.restoreCallingIdentity(ident);
1790 }
1791
Michael Chane96440f2009-05-06 10:27:36 -07001792 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1794 setTimeoutLocked(time, SCREEN_BRIGHT);
1795 }
1796 }
1797 }
1798 }
1799
1800 /**
1801 * The user requested that we go to sleep (probably with the power button).
1802 * This overrides all wake locks that are held.
1803 */
1804 public void goToSleep(long time)
1805 {
1806 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1807 synchronized (mLocks) {
1808 goToSleepLocked(time);
1809 }
1810 }
1811
1812 /**
1813 * Returns the time the screen has been on since boot, in millis.
1814 * @return screen on time
1815 */
1816 public long getScreenOnTime() {
1817 synchronized (mLocks) {
1818 if (mScreenOnStartTime == 0) {
1819 return mScreenOnTime;
1820 } else {
1821 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1822 }
1823 }
1824 }
1825
1826 private void goToSleepLocked(long time) {
1827
1828 if (mLastEventTime <= time) {
1829 mLastEventTime = time;
1830 // cancel all of the wake locks
1831 mWakeLockState = SCREEN_OFF;
1832 int N = mLocks.size();
1833 int numCleared = 0;
1834 for (int i=0; i<N; i++) {
1835 WakeLock wl = mLocks.get(i);
1836 if (isScreenLock(wl.flags)) {
1837 mLocks.get(i).activated = false;
1838 numCleared++;
1839 }
1840 }
1841 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07001842 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 mUserState = SCREEN_OFF;
1844 setPowerState(SCREEN_OFF, false, true);
1845 cancelTimerLocked();
1846 }
1847 }
1848
1849 public long timeSinceScreenOn() {
1850 synchronized (mLocks) {
1851 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1852 return 0;
1853 }
1854 return SystemClock.elapsedRealtime() - mScreenOffTime;
1855 }
1856 }
1857
1858 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07001859 synchronized (mLocks) {
1860 if (mSpew) {
1861 Log.d(TAG, "setKeyboardVisibility: " + visible);
1862 }
1863 mKeyboardVisible = visible;
1864 // don't signal user activity when closing keyboard if the screen is off.
1865 // otherwise, we want to make sure the backlights are adjusted.
1866 if (visible || (mPowerState & SCREEN_ON_BIT) != 0) {
1867 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
1868 }
1869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 }
1871
1872 /**
1873 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
1874 */
1875 public void enableUserActivity(boolean enabled) {
1876 synchronized (mLocks) {
1877 mUserActivityAllowed = enabled;
1878 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
1879 }
1880 }
1881
1882 /** Sets the screen off timeouts:
1883 * mKeylightDelay
1884 * mDimDelay
1885 * mScreenOffDelay
1886 * */
1887 private void setScreenOffTimeoutsLocked() {
1888 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
1889 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
1890 mDimDelay = -1;
1891 mScreenOffDelay = 0;
1892 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
1893 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
1894 mDimDelay = -1;
1895 mScreenOffDelay = 0;
1896 } else {
1897 int totalDelay = mTotalDelaySetting;
1898 mKeylightDelay = LONG_KEYLIGHT_DELAY;
1899 if (totalDelay < 0) {
1900 mScreenOffDelay = Integer.MAX_VALUE;
1901 } else if (mKeylightDelay < totalDelay) {
1902 // subtract the time that the keylight delay. This will give us the
1903 // remainder of the time that we need to sleep to get the accurate
1904 // screen off timeout.
1905 mScreenOffDelay = totalDelay - mKeylightDelay;
1906 } else {
1907 mScreenOffDelay = 0;
1908 }
1909 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
1910 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
1911 mScreenOffDelay = LONG_DIM_TIME;
1912 } else {
1913 mDimDelay = -1;
1914 }
1915 }
1916 if (mSpew) {
1917 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
1918 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
1919 + " mDimScreen=" + mDimScreen);
1920 }
1921 }
1922
1923 /**
1924 * Refreshes cached Gservices settings. Called once on startup, and
1925 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
1926 * GservicesChangedReceiver).
1927 */
1928 private void updateGservicesValues() {
1929 mShortKeylightDelay = Settings.Gservices.getInt(
1930 mContext.getContentResolver(),
1931 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
1932 SHORT_KEYLIGHT_DELAY_DEFAULT);
1933 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
1934 }
1935
1936 /**
1937 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
1938 * which tells us we need to refresh our cached Gservices settings.
1939 */
1940 private class GservicesChangedReceiver extends BroadcastReceiver {
1941 @Override
1942 public void onReceive(Context context, Intent intent) {
1943 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
1944 updateGservicesValues();
1945 }
1946 }
1947
1948 private class LockList extends ArrayList<WakeLock>
1949 {
1950 void addLock(WakeLock wl)
1951 {
1952 int index = getIndex(wl.binder);
1953 if (index < 0) {
1954 this.add(wl);
1955 }
1956 }
1957
1958 WakeLock removeLock(IBinder binder)
1959 {
1960 int index = getIndex(binder);
1961 if (index >= 0) {
1962 return this.remove(index);
1963 } else {
1964 return null;
1965 }
1966 }
1967
1968 int getIndex(IBinder binder)
1969 {
1970 int N = this.size();
1971 for (int i=0; i<N; i++) {
1972 if (this.get(i).binder == binder) {
1973 return i;
1974 }
1975 }
1976 return -1;
1977 }
1978
1979 int gatherState()
1980 {
1981 int result = 0;
1982 int N = this.size();
1983 for (int i=0; i<N; i++) {
1984 WakeLock wl = this.get(i);
1985 if (wl.activated) {
1986 if (isScreenLock(wl.flags)) {
1987 result |= wl.minState;
1988 }
1989 }
1990 }
1991 return result;
1992 }
Michael Chane96440f2009-05-06 10:27:36 -07001993
1994 int reactivateScreenLocksLocked()
1995 {
1996 int result = 0;
1997 int N = this.size();
1998 for (int i=0; i<N; i++) {
1999 WakeLock wl = this.get(i);
2000 if (isScreenLock(wl.flags)) {
2001 wl.activated = true;
2002 result |= wl.minState;
2003 }
2004 }
2005 return result;
2006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 }
2008
2009 void setPolicy(WindowManagerPolicy p) {
2010 synchronized (mLocks) {
2011 mPolicy = p;
2012 mLocks.notifyAll();
2013 }
2014 }
2015
2016 WindowManagerPolicy getPolicyLocked() {
2017 while (mPolicy == null || !mDoneBooting) {
2018 try {
2019 mLocks.wait();
2020 } catch (InterruptedException e) {
2021 // Ignore
2022 }
2023 }
2024 return mPolicy;
2025 }
2026
2027 void systemReady() {
2028 synchronized (mLocks) {
2029 Log.d(TAG, "system ready!");
2030 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002031 long identity = Binder.clearCallingIdentity();
2032 try {
2033 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2034 mBatteryStats.noteScreenOn();
2035 } catch (RemoteException e) {
2036 // Nothing interesting to do.
2037 } finally {
2038 Binder.restoreCallingIdentity(identity);
2039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2041 updateWakeLockLocked();
2042 mLocks.notifyAll();
2043 }
2044 }
2045
2046 public void monitor() {
2047 synchronized (mLocks) { }
2048 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002049
2050 public int getSupportedWakeLockFlags() {
2051 int result = PowerManager.PARTIAL_WAKE_LOCK
2052 | PowerManager.FULL_WAKE_LOCK
2053 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2054
2055 // call getSensorManager() to make sure mProximitySensor is initialized
2056 getSensorManager();
2057 if (mProximitySensor != null) {
2058 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2059 }
2060
2061 return result;
2062 }
2063
Mike Lockwood237a2992009-09-15 14:42:16 -04002064 public void setBacklightBrightness(int brightness) {
2065 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2066 // Don't let applications turn the screen all the way off
2067 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2068 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness);
2069 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, brightness);
2070 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness);
2071 long identity = Binder.clearCallingIdentity();
2072 try {
2073 mBatteryStats.noteScreenBrightness(brightness);
2074 } catch (RemoteException e) {
2075 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2076 } finally {
2077 Binder.restoreCallingIdentity(identity);
2078 }
2079
2080 // update our animation state
2081 if (ANIMATE_SCREEN_LIGHTS) {
2082 mScreenBrightness.curValue = brightness;
2083 mScreenBrightness.animating = false;
2084 }
2085 if (ANIMATE_KEYBOARD_LIGHTS) {
2086 mKeyboardBrightness.curValue = brightness;
2087 mKeyboardBrightness.animating = false;
2088 }
2089 if (ANIMATE_BUTTON_LIGHTS) {
2090 mButtonBrightness.curValue = brightness;
2091 mButtonBrightness.animating = false;
2092 }
2093 }
2094
2095 public void setAutoBrightness(boolean on) {
2096 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2097 mHardware.setAutoBrightness_UNCHECKED(on);
2098 }
2099
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002100 private SensorManager getSensorManager() {
2101 if (mSensorManager == null) {
2102 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2103 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2104 }
2105 return mSensorManager;
2106 }
2107
2108 private void enableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002109 if (mSpew) {
2110 Log.d(TAG, "enableProximityLockLocked");
2111 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002112 mSensorManager.registerListener(this, mProximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
2113 }
2114
2115 private void disableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002116 if (mSpew) {
2117 Log.d(TAG, "disableProximityLockLocked");
2118 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002119 mSensorManager.unregisterListener(this);
Mike Lockwood36fc3022009-08-25 16:49:06 -07002120 mProximitySensorActive = false;
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002121 }
2122
2123 public void onSensorChanged(SensorEvent event) {
2124 long milliseconds = event.timestamp / 1000000;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002125 synchronized (mLocks) {
Mike Lockwoodd20ea362009-09-15 00:13:38 -04002126 float distance = event.values[0];
2127 if (distance >= 0.0 && distance < PROXIMITY_THRESHOLD) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002128 if (mSpew) {
Mike Lockwoodd20ea362009-09-15 00:13:38 -04002129 Log.d(TAG, "onSensorChanged: proximity active, distance: " + distance);
Mike Lockwood36fc3022009-08-25 16:49:06 -07002130 }
2131 goToSleepLocked(milliseconds);
2132 mProximitySensorActive = true;
2133 } else {
Mike Lockwoodd20ea362009-09-15 00:13:38 -04002134 // proximity sensor negative events trigger as user activity.
Mike Lockwood36fc3022009-08-25 16:49:06 -07002135 // temporarily set mUserActivityAllowed to true so this will work
2136 // even when the keyguard is on.
2137 if (mSpew) {
Mike Lockwoodd20ea362009-09-15 00:13:38 -04002138 Log.d(TAG, "onSensorChanged: proximity inactive, distance: " + distance);
Mike Lockwood36fc3022009-08-25 16:49:06 -07002139 }
2140 mProximitySensorActive = false;
Mike Lockwood06952d92009-08-13 16:05:38 -04002141 boolean savedActivityAllowed = mUserActivityAllowed;
2142 mUserActivityAllowed = true;
2143 userActivity(milliseconds, false);
2144 mUserActivityAllowed = savedActivityAllowed;
2145 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002146 }
2147 }
2148
2149 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2150 // ignore
2151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152}