blob: 84250bce314d817fe04754e75616ef76864a33e7 [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 {
Joe Onorato64c62ba2009-03-24 20:13:57 -0700960 if (!on) {
961 mStillNeedSleepNotification = false;
962 }
963
Joe Onorato128e7292009-03-24 18:41:31 -0700964 // Add to the queue.
965 int index = 0;
966 while (mBroadcastQueue[index] != -1) {
967 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 }
Joe Onorato128e7292009-03-24 18:41:31 -0700969 mBroadcastQueue[index] = on ? 1 : 0;
970 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971
Joe Onorato128e7292009-03-24 18:41:31 -0700972 // If we added it position 2, then there is a pair that can be stripped.
973 // If we added it position 1 and we're turning the screen off, we can strip
974 // the pair and do nothing, because the screen is already off, and therefore
975 // keyguard has already been enabled.
976 // However, if we added it at position 1 and we're turning it on, then position
977 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
978 // on, so have to run the queue then.
979 if (index == 2) {
980 // Also, while we're collapsing them, if it's going to be an "off," and one
981 // is off because of user, then use that, regardless of whether it's the first
982 // or second one.
983 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
984 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
985 }
986 mBroadcastQueue[0] = on ? 1 : 0;
987 mBroadcastQueue[1] = -1;
988 mBroadcastQueue[2] = -1;
989 index = 0;
990 }
991 if (index == 1 && !on) {
992 mBroadcastQueue[0] = -1;
993 mBroadcastQueue[1] = -1;
994 index = -1;
995 // The wake lock was being held, but we're not actually going to do any
996 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
998 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -0700999 }
1000
1001 // Now send the message.
1002 if (index >= 0) {
1003 // Acquire the broadcast wake lock before changing the power
1004 // state. It will be release after the broadcast is sent.
1005 // We always increment the ref count for each notification in the queue
1006 // and always decrement when that notification is handled.
1007 mBroadcastWakeLock.acquire();
1008 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1009 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 }
1011 }
1012
1013 private Runnable mNotificationTask = new Runnable()
1014 {
1015 public void run()
1016 {
Joe Onorato128e7292009-03-24 18:41:31 -07001017 while (true) {
1018 int value;
1019 int why;
1020 WindowManagerPolicy policy;
1021 synchronized (mLocks) {
1022 value = mBroadcastQueue[0];
1023 why = mBroadcastWhy[0];
1024 for (int i=0; i<2; i++) {
1025 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1026 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1027 }
1028 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 }
Joe Onorato128e7292009-03-24 18:41:31 -07001030 if (value == 1) {
1031 mScreenOnStart = SystemClock.uptimeMillis();
1032
1033 policy.screenTurnedOn();
1034 try {
1035 ActivityManagerNative.getDefault().wakingUp();
1036 } catch (RemoteException e) {
1037 // ignore it
1038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039
Joe Onorato128e7292009-03-24 18:41:31 -07001040 if (mSpew) {
1041 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1042 }
1043 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1044 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1045 mScreenOnBroadcastDone, mHandler, 0, null, null);
1046 } else {
1047 synchronized (mLocks) {
1048 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1049 mBroadcastWakeLock.mCount);
1050 mBroadcastWakeLock.release();
1051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 }
1053 }
Joe Onorato128e7292009-03-24 18:41:31 -07001054 else if (value == 0) {
1055 mScreenOffStart = SystemClock.uptimeMillis();
1056
1057 policy.screenTurnedOff(why);
1058 try {
1059 ActivityManagerNative.getDefault().goingToSleep();
1060 } catch (RemoteException e) {
1061 // ignore it.
1062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063
Joe Onorato128e7292009-03-24 18:41:31 -07001064 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1065 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1066 mScreenOffBroadcastDone, mHandler, 0, null, null);
1067 } else {
1068 synchronized (mLocks) {
1069 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1070 mBroadcastWakeLock.mCount);
1071 mBroadcastWakeLock.release();
1072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
1074 }
Joe Onorato128e7292009-03-24 18:41:31 -07001075 else {
1076 // If we're in this case, then this handler is running for a previous
1077 // paired transaction. mBroadcastWakeLock will already have been released.
1078 break;
1079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 }
1081 }
1082 };
1083
1084 long mScreenOnStart;
1085 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1086 public void onReceive(Context context, Intent intent) {
1087 synchronized (mLocks) {
1088 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1089 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1090 mBroadcastWakeLock.release();
1091 }
1092 }
1093 };
1094
1095 long mScreenOffStart;
1096 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1097 public void onReceive(Context context, Intent intent) {
1098 synchronized (mLocks) {
1099 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1100 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1101 mBroadcastWakeLock.release();
1102 }
1103 }
1104 };
1105
1106 void logPointerUpEvent() {
1107 if (LOG_TOUCH_DOWNS) {
1108 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1109 mLastTouchDown = 0;
1110 }
1111 }
1112
1113 void logPointerDownEvent() {
1114 if (LOG_TOUCH_DOWNS) {
1115 // If we are not already timing a down/up sequence
1116 if (mLastTouchDown == 0) {
1117 mLastTouchDown = SystemClock.elapsedRealtime();
1118 mTouchCycles++;
1119 }
1120 }
1121 }
1122
1123 /**
1124 * Prevents the screen from turning on even if it *should* turn on due
1125 * to a subsequent full wake lock being acquired.
1126 * <p>
1127 * This is a temporary hack that allows an activity to "cover up" any
1128 * display glitches that happen during the activity's startup
1129 * sequence. (Specifically, this API was added to work around a
1130 * cosmetic bug in the "incoming call" sequence, where the lock screen
1131 * would flicker briefly before the incoming call UI became visible.)
1132 * TODO: There ought to be a more elegant way of doing this,
1133 * probably by having the PowerManager and ActivityManager
1134 * work together to let apps specify that the screen on/off
1135 * state should be synchronized with the Activity lifecycle.
1136 * <p>
1137 * Note that calling preventScreenOn(true) will NOT turn the screen
1138 * off if it's currently on. (This API only affects *future*
1139 * acquisitions of full wake locks.)
1140 * But calling preventScreenOn(false) WILL turn the screen on if
1141 * it's currently off because of a prior preventScreenOn(true) call.
1142 * <p>
1143 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1144 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1145 * call doesn't occur within 5 seconds, we'll turn the screen back on
1146 * ourselves (and log a warning about it); this prevents a buggy app
1147 * from disabling the screen forever.)
1148 * <p>
1149 * TODO: this feature should really be controlled by a new type of poke
1150 * lock (rather than an IPowerManager call).
1151 */
1152 public void preventScreenOn(boolean prevent) {
1153 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1154
1155 synchronized (mLocks) {
1156 if (prevent) {
1157 // First of all, grab a partial wake lock to
1158 // make sure the CPU stays on during the entire
1159 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1160 mPreventScreenOnPartialLock.acquire();
1161
1162 // Post a forceReenableScreen() call (for 5 seconds in the
1163 // future) to make sure the matching preventScreenOn(false) call
1164 // has happened by then.
1165 mHandler.removeCallbacks(mForceReenableScreenTask);
1166 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1167
1168 // Finally, set the flag that prevents the screen from turning on.
1169 // (Below, in setPowerState(), we'll check mPreventScreenOn and
1170 // we *won't* call Power.setScreenState(true) if it's set.)
1171 mPreventScreenOn = true;
1172 } else {
1173 // (Re)enable the screen.
1174 mPreventScreenOn = false;
1175
1176 // We're "undoing" a the prior preventScreenOn(true) call, so we
1177 // no longer need the 5-second safeguard.
1178 mHandler.removeCallbacks(mForceReenableScreenTask);
1179
1180 // Forcibly turn on the screen if it's supposed to be on. (This
1181 // handles the case where the screen is currently off because of
1182 // a prior preventScreenOn(true) call.)
1183 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1184 if (mSpew) {
1185 Log.d(TAG,
1186 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1187 }
1188 int err = Power.setScreenState(true);
1189 if (err != 0) {
1190 Log.w(TAG, "preventScreenOn: error from Power.setScreenState(): " + err);
1191 }
1192 }
1193
1194 // Release the partial wake lock that we held during the
1195 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1196 mPreventScreenOnPartialLock.release();
1197 }
1198 }
1199 }
1200
1201 public void setScreenBrightnessOverride(int brightness) {
1202 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1203
1204 synchronized (mLocks) {
1205 if (mScreenBrightnessOverride != brightness) {
1206 mScreenBrightnessOverride = brightness;
1207 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1208 }
1209 }
1210 }
1211
1212 /**
1213 * Sanity-check that gets called 5 seconds after any call to
1214 * preventScreenOn(true). This ensures that the original call
1215 * is followed promptly by a call to preventScreenOn(false).
1216 */
1217 private void forceReenableScreen() {
1218 // We shouldn't get here at all if mPreventScreenOn is false, since
1219 // we should have already removed any existing
1220 // mForceReenableScreenTask messages...
1221 if (!mPreventScreenOn) {
1222 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1223 return;
1224 }
1225
1226 // Uh oh. It's been 5 seconds since a call to
1227 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1228 // This means the app that called preventScreenOn(true) is either
1229 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1230 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1231 // crashed before doing so.)
1232
1233 // Log a warning, and forcibly turn the screen back on.
1234 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1235 + "Forcing the screen back on...");
1236 preventScreenOn(false);
1237 }
1238
1239 private Runnable mForceReenableScreenTask = new Runnable() {
1240 public void run() {
1241 forceReenableScreen();
1242 }
1243 };
1244
1245 private void setPowerState(int state)
1246 {
1247 setPowerState(state, false, false);
1248 }
1249
1250 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1251 {
1252 synchronized (mLocks) {
1253 int err;
1254
1255 if (mSpew) {
1256 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1257 + " newState=0x" + Integer.toHexString(newState)
1258 + " noChangeLights=" + noChangeLights);
1259 }
1260
1261 if (noChangeLights) {
1262 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1263 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001264 if (mProximitySensorActive) {
1265 // don't turn on the screen when the proximity sensor lock is held
1266 newState = (newState & ~SCREEN_BRIGHT);
1267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268
1269 if (batteryIsLow()) {
1270 newState |= BATTERY_LOW_BIT;
1271 } else {
1272 newState &= ~BATTERY_LOW_BIT;
1273 }
1274 if (newState == mPowerState) {
1275 return;
1276 }
1277
1278 if (!mDoneBooting) {
1279 newState |= ALL_BRIGHT;
1280 }
1281
1282 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1283 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1284
1285 if (mSpew) {
1286 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1287 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1288 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1289 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1290 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1291 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1292 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1293 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1294 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1295 + " newScreenOn=" + newScreenOn);
1296 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1297 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1298 }
1299
1300 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001301 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1303 }
1304
1305 if (oldScreenOn != newScreenOn) {
1306 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001307 // When the user presses the power button, we need to always send out the
1308 // notification that it's going to sleep so the keyguard goes on. But
1309 // we can't do that until the screen fades out, so we don't show the keyguard
1310 // too early.
1311 if (mStillNeedSleepNotification) {
1312 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1313 }
1314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 // Turn on the screen UNLESS there was a prior
1316 // preventScreenOn(true) request. (Note that the lifetime
1317 // of a single preventScreenOn() request is limited to 5
1318 // seconds to prevent a buggy app from disabling the
1319 // screen forever; see forceReenableScreen().)
1320 boolean reallyTurnScreenOn = true;
1321 if (mSpew) {
1322 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1323 + mPreventScreenOn);
1324 }
1325
1326 if (mPreventScreenOn) {
1327 if (mSpew) {
1328 Log.d(TAG, "- PREVENTING screen from really turning on!");
1329 }
1330 reallyTurnScreenOn = false;
1331 }
1332 if (reallyTurnScreenOn) {
1333 err = Power.setScreenState(true);
1334 long identity = Binder.clearCallingIdentity();
1335 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001336 mBatteryStats.noteScreenBrightness(
1337 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 mBatteryStats.noteScreenOn();
1339 } catch (RemoteException e) {
1340 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1341 } finally {
1342 Binder.restoreCallingIdentity(identity);
1343 }
1344 } else {
1345 Power.setScreenState(false);
1346 // But continue as if we really did turn the screen on...
1347 err = 0;
1348 }
1349
1350 mScreenOnStartTime = SystemClock.elapsedRealtime();
1351 mLastTouchDown = 0;
1352 mTotalTouchDownTime = 0;
1353 mTouchCycles = 0;
1354 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1355 mTotalTouchDownTime, mTouchCycles);
1356 if (err == 0) {
1357 mPowerState |= SCREEN_ON_BIT;
1358 sendNotificationLocked(true, -1);
1359 }
1360 } else {
1361 mScreenOffTime = SystemClock.elapsedRealtime();
1362 long identity = Binder.clearCallingIdentity();
1363 try {
1364 mBatteryStats.noteScreenOff();
1365 } catch (RemoteException e) {
1366 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1367 } finally {
1368 Binder.restoreCallingIdentity(identity);
1369 }
1370 mPowerState &= ~SCREEN_ON_BIT;
1371 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001372 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 } else {
1374 mOffBecauseOfUser = becauseOfUser;
1375 err = 0;
1376 mLastTouchDown = 0;
1377 }
1378 }
1379 }
1380 }
1381 }
1382
Joe Onorato128e7292009-03-24 18:41:31 -07001383 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 // I don't think we need to check the current state here because all of these
1385 // Power.setScreenState and sendNotificationLocked can both handle being
1386 // called multiple times in the same state. -joeo
1387 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1388 mTotalTouchDownTime, mTouchCycles);
1389 mLastTouchDown = 0;
1390 int err = Power.setScreenState(false);
1391 if (mScreenOnStartTime != 0) {
1392 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1393 mScreenOnStartTime = 0;
1394 }
1395 if (err == 0) {
1396 int why = becauseOfUser
1397 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1398 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1399 sendNotificationLocked(false, why);
1400 }
1401 return err;
1402 }
1403
1404 private boolean batteryIsLow() {
1405 return (!mIsPowered &&
1406 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1407 }
1408
The Android Open Source Project10592532009-03-18 17:39:46 -07001409 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001410 final int oldState = mPowerState;
1411 final int realDifference = (newState ^ oldState);
1412 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001414 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 }
1416
1417 int offMask = 0;
1418 int dimMask = 0;
1419 int onMask = 0;
1420
1421 int preferredBrightness = getPreferredBrightness();
1422 boolean startAnimation = false;
1423
1424 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1425 if (ANIMATE_KEYBOARD_LIGHTS) {
1426 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1427 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001428 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1429 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 } else {
1431 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001432 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1433 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 }
1435 startAnimation = true;
1436 } else {
1437 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001438 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001440 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 }
1442 }
1443 }
1444
1445 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1446 if (ANIMATE_BUTTON_LIGHTS) {
1447 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1448 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001449 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1450 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 } else {
1452 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001453 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1454 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 }
1456 startAnimation = true;
1457 } else {
1458 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001459 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001461 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 }
1463 }
1464 }
1465
1466 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1467 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001468 int nominalCurrentValue = -1;
1469 // If there was an actual difference in the light state, then
1470 // figure out the "ideal" current value based on the previous
1471 // state. Otherwise, this is a change due to the brightness
1472 // override, so we want to animate from whatever the current
1473 // value is.
1474 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1475 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1476 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1477 nominalCurrentValue = preferredBrightness;
1478 break;
1479 case SCREEN_ON_BIT:
1480 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1481 break;
1482 case 0:
1483 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1484 break;
1485 case SCREEN_BRIGHT_BIT:
1486 default:
1487 // not possible
1488 nominalCurrentValue = (int)mScreenBrightness.curValue;
1489 break;
1490 }
Joe Onorato128e7292009-03-24 18:41:31 -07001491 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001492 int brightness = preferredBrightness;
1493 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1495 // dim or turn off backlight, depending on if the screen is on
1496 // the scale is because the brightness ramp isn't linear and this biases
1497 // it so the later parts take longer.
1498 final float scale = 1.5f;
1499 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1500 if (ratio > 1.0f) ratio = 1.0f;
1501 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1503 // was bright
1504 steps = ANIM_STEPS;
1505 } else {
1506 // was dim
1507 steps = (int)(ANIM_STEPS*ratio*scale);
1508 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001509 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 if ((oldState & SCREEN_ON_BIT) != 0) {
1512 // was bright
1513 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1514 } else {
1515 // was dim
1516 steps = (int)(ANIM_STEPS*ratio);
1517 }
1518 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1519 // If the "stay on while plugged in" option is
1520 // turned on, then the screen will often not
1521 // automatically turn off while plugged in. To
1522 // still have a sense of when it is inactive, we
1523 // will then count going dim as turning off.
1524 mScreenOffTime = SystemClock.elapsedRealtime();
1525 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001526 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001529 long identity = Binder.clearCallingIdentity();
1530 try {
1531 mBatteryStats.noteScreenBrightness(brightness);
1532 } catch (RemoteException e) {
1533 // Nothing interesting to do.
1534 } finally {
1535 Binder.restoreCallingIdentity(identity);
1536 }
1537 mScreenBrightness.setTargetLocked(brightness,
1538 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 startAnimation = true;
1540 } else {
1541 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1542 // dim or turn off backlight, depending on if the screen is on
1543 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001544 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001546 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001549 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
1551 }
1552 }
1553
1554 if (startAnimation) {
1555 if (mSpew) {
1556 Log.i(TAG, "Scheduling light animator!");
1557 }
1558 mHandler.removeCallbacks(mLightAnimator);
1559 mHandler.post(mLightAnimator);
1560 }
1561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 if (offMask != 0) {
1563 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001564 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 }
1566 if (dimMask != 0) {
1567 int brightness = Power.BRIGHTNESS_DIM;
1568 if ((newState & BATTERY_LOW_BIT) != 0 &&
1569 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1570 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1571 }
1572 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001573 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 }
1575 if (onMask != 0) {
1576 int brightness = getPreferredBrightness();
1577 if ((newState & BATTERY_LOW_BIT) != 0 &&
1578 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1579 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1580 }
1581 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001582 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585
The Android Open Source Project10592532009-03-18 17:39:46 -07001586 private void setLightBrightness(int mask, int value) {
1587 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1588 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1589 }
1590 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1591 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1592 }
1593 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1594 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 }
1597
1598 class BrightnessState {
1599 final int mask;
1600
1601 boolean initialized;
1602 int targetValue;
1603 float curValue;
1604 float delta;
1605 boolean animating;
1606
1607 BrightnessState(int m) {
1608 mask = m;
1609 }
1610
1611 public void dump(PrintWriter pw, String prefix) {
1612 pw.println(prefix + "animating=" + animating
1613 + " targetValue=" + targetValue
1614 + " curValue=" + curValue
1615 + " delta=" + delta);
1616 }
1617
Joe Onorato128e7292009-03-24 18:41:31 -07001618 void setTargetLocked(int target, int stepsToTarget, int initialValue,
1619 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 if (!initialized) {
1621 initialized = true;
1622 curValue = (float)initialValue;
1623 }
1624 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001625 delta = (targetValue -
1626 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1627 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001629 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001631 + " target=" + targetValue + " delta=" + delta
1632 + " nominalCurrentValue=" + nominalCurrentValue
1633 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 }
1635 animating = true;
1636 }
1637
1638 boolean stepLocked() {
1639 if (!animating) return false;
1640 if (false && mSpew) {
1641 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1642 + " target=" + targetValue + " delta=" + delta);
1643 }
1644 curValue += delta;
1645 int curIntValue = (int)curValue;
1646 boolean more = true;
1647 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001648 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 more = false;
1650 } else if (delta > 0) {
1651 if (curIntValue >= targetValue) {
1652 curValue = curIntValue = targetValue;
1653 more = false;
1654 }
1655 } else {
1656 if (curIntValue <= targetValue) {
1657 curValue = curIntValue = targetValue;
1658 more = false;
1659 }
1660 }
1661 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001662 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 animating = more;
1664 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001665 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001666 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 }
1668 }
1669 return more;
1670 }
1671 }
1672
1673 private class LightAnimator implements Runnable {
1674 public void run() {
1675 synchronized (mLocks) {
1676 long now = SystemClock.uptimeMillis();
1677 boolean more = mScreenBrightness.stepLocked();
1678 if (mKeyboardBrightness.stepLocked()) {
1679 more = true;
1680 }
1681 if (mButtonBrightness.stepLocked()) {
1682 more = true;
1683 }
1684 if (more) {
1685 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1686 }
1687 }
1688 }
1689 }
1690
1691 private int getPreferredBrightness() {
1692 try {
1693 if (mScreenBrightnessOverride >= 0) {
1694 return mScreenBrightnessOverride;
1695 }
1696 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1697 SCREEN_BRIGHTNESS);
1698 // Don't let applications turn the screen all the way off
1699 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1700 } catch (SettingNotFoundException snfe) {
1701 return Power.BRIGHTNESS_ON;
1702 }
1703 }
1704
1705 boolean screenIsOn() {
1706 synchronized (mLocks) {
1707 return (mPowerState & SCREEN_ON_BIT) != 0;
1708 }
1709 }
1710
1711 boolean screenIsBright() {
1712 synchronized (mLocks) {
1713 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1714 }
1715 }
1716
1717 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1718 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1719 userActivity(time, noChangeLights, OTHER_EVENT, force);
1720 }
1721
1722 public void userActivity(long time, boolean noChangeLights) {
1723 userActivity(time, noChangeLights, OTHER_EVENT, false);
1724 }
1725
1726 public void userActivity(long time, boolean noChangeLights, int eventType) {
1727 userActivity(time, noChangeLights, eventType, false);
1728 }
1729
1730 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1731 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1732
1733 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001734 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001736 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 }
1738 return;
1739 }
1740
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001741 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1742 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1743 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1744 if (false) {
1745 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1746 }
1747 return;
1748 }
1749
1750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 if (false) {
1752 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1753 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1754 } else {
1755 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1756 }
1757 }
1758
1759 synchronized (mLocks) {
1760 if (mSpew) {
1761 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1762 + " mUserActivityAllowed=" + mUserActivityAllowed
1763 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001764 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1765 + " mProximitySensorActive=" + mProximitySensorActive
1766 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 }
1768 if (mLastEventTime <= time || force) {
1769 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001770 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 // Only turn on button backlights if a button was pressed.
1772 if (eventType == BUTTON_EVENT) {
1773 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1774 } else {
1775 // don't clear button/keyboard backlights when the screen is touched.
1776 mUserState |= SCREEN_BRIGHT;
1777 }
1778
Dianne Hackborn617f8772009-03-31 15:04:46 -07001779 int uid = Binder.getCallingUid();
1780 long ident = Binder.clearCallingIdentity();
1781 try {
1782 mBatteryStats.noteUserActivity(uid, eventType);
1783 } catch (RemoteException e) {
1784 // Ignore
1785 } finally {
1786 Binder.restoreCallingIdentity(ident);
1787 }
1788
Michael Chane96440f2009-05-06 10:27:36 -07001789 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1791 setTimeoutLocked(time, SCREEN_BRIGHT);
1792 }
1793 }
1794 }
1795 }
1796
1797 /**
1798 * The user requested that we go to sleep (probably with the power button).
1799 * This overrides all wake locks that are held.
1800 */
1801 public void goToSleep(long time)
1802 {
1803 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1804 synchronized (mLocks) {
1805 goToSleepLocked(time);
1806 }
1807 }
1808
1809 /**
1810 * Returns the time the screen has been on since boot, in millis.
1811 * @return screen on time
1812 */
1813 public long getScreenOnTime() {
1814 synchronized (mLocks) {
1815 if (mScreenOnStartTime == 0) {
1816 return mScreenOnTime;
1817 } else {
1818 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1819 }
1820 }
1821 }
1822
1823 private void goToSleepLocked(long time) {
1824
1825 if (mLastEventTime <= time) {
1826 mLastEventTime = time;
1827 // cancel all of the wake locks
1828 mWakeLockState = SCREEN_OFF;
1829 int N = mLocks.size();
1830 int numCleared = 0;
1831 for (int i=0; i<N; i++) {
1832 WakeLock wl = mLocks.get(i);
1833 if (isScreenLock(wl.flags)) {
1834 mLocks.get(i).activated = false;
1835 numCleared++;
1836 }
1837 }
1838 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07001839 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 mUserState = SCREEN_OFF;
1841 setPowerState(SCREEN_OFF, false, true);
1842 cancelTimerLocked();
1843 }
1844 }
1845
1846 public long timeSinceScreenOn() {
1847 synchronized (mLocks) {
1848 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1849 return 0;
1850 }
1851 return SystemClock.elapsedRealtime() - mScreenOffTime;
1852 }
1853 }
1854
1855 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07001856 synchronized (mLocks) {
1857 if (mSpew) {
1858 Log.d(TAG, "setKeyboardVisibility: " + visible);
1859 }
1860 mKeyboardVisible = visible;
1861 // don't signal user activity when closing keyboard if the screen is off.
1862 // otherwise, we want to make sure the backlights are adjusted.
1863 if (visible || (mPowerState & SCREEN_ON_BIT) != 0) {
1864 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
1865 }
1866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 }
1868
1869 /**
1870 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
1871 */
1872 public void enableUserActivity(boolean enabled) {
1873 synchronized (mLocks) {
1874 mUserActivityAllowed = enabled;
1875 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
1876 }
1877 }
1878
1879 /** Sets the screen off timeouts:
1880 * mKeylightDelay
1881 * mDimDelay
1882 * mScreenOffDelay
1883 * */
1884 private void setScreenOffTimeoutsLocked() {
1885 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
1886 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
1887 mDimDelay = -1;
1888 mScreenOffDelay = 0;
1889 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
1890 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
1891 mDimDelay = -1;
1892 mScreenOffDelay = 0;
1893 } else {
1894 int totalDelay = mTotalDelaySetting;
1895 mKeylightDelay = LONG_KEYLIGHT_DELAY;
1896 if (totalDelay < 0) {
1897 mScreenOffDelay = Integer.MAX_VALUE;
1898 } else if (mKeylightDelay < totalDelay) {
1899 // subtract the time that the keylight delay. This will give us the
1900 // remainder of the time that we need to sleep to get the accurate
1901 // screen off timeout.
1902 mScreenOffDelay = totalDelay - mKeylightDelay;
1903 } else {
1904 mScreenOffDelay = 0;
1905 }
1906 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
1907 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
1908 mScreenOffDelay = LONG_DIM_TIME;
1909 } else {
1910 mDimDelay = -1;
1911 }
1912 }
1913 if (mSpew) {
1914 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
1915 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
1916 + " mDimScreen=" + mDimScreen);
1917 }
1918 }
1919
1920 /**
1921 * Refreshes cached Gservices settings. Called once on startup, and
1922 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
1923 * GservicesChangedReceiver).
1924 */
1925 private void updateGservicesValues() {
1926 mShortKeylightDelay = Settings.Gservices.getInt(
1927 mContext.getContentResolver(),
1928 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
1929 SHORT_KEYLIGHT_DELAY_DEFAULT);
1930 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
1931 }
1932
1933 /**
1934 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
1935 * which tells us we need to refresh our cached Gservices settings.
1936 */
1937 private class GservicesChangedReceiver extends BroadcastReceiver {
1938 @Override
1939 public void onReceive(Context context, Intent intent) {
1940 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
1941 updateGservicesValues();
1942 }
1943 }
1944
1945 private class LockList extends ArrayList<WakeLock>
1946 {
1947 void addLock(WakeLock wl)
1948 {
1949 int index = getIndex(wl.binder);
1950 if (index < 0) {
1951 this.add(wl);
1952 }
1953 }
1954
1955 WakeLock removeLock(IBinder binder)
1956 {
1957 int index = getIndex(binder);
1958 if (index >= 0) {
1959 return this.remove(index);
1960 } else {
1961 return null;
1962 }
1963 }
1964
1965 int getIndex(IBinder binder)
1966 {
1967 int N = this.size();
1968 for (int i=0; i<N; i++) {
1969 if (this.get(i).binder == binder) {
1970 return i;
1971 }
1972 }
1973 return -1;
1974 }
1975
1976 int gatherState()
1977 {
1978 int result = 0;
1979 int N = this.size();
1980 for (int i=0; i<N; i++) {
1981 WakeLock wl = this.get(i);
1982 if (wl.activated) {
1983 if (isScreenLock(wl.flags)) {
1984 result |= wl.minState;
1985 }
1986 }
1987 }
1988 return result;
1989 }
Michael Chane96440f2009-05-06 10:27:36 -07001990
1991 int reactivateScreenLocksLocked()
1992 {
1993 int result = 0;
1994 int N = this.size();
1995 for (int i=0; i<N; i++) {
1996 WakeLock wl = this.get(i);
1997 if (isScreenLock(wl.flags)) {
1998 wl.activated = true;
1999 result |= wl.minState;
2000 }
2001 }
2002 return result;
2003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 }
2005
2006 void setPolicy(WindowManagerPolicy p) {
2007 synchronized (mLocks) {
2008 mPolicy = p;
2009 mLocks.notifyAll();
2010 }
2011 }
2012
2013 WindowManagerPolicy getPolicyLocked() {
2014 while (mPolicy == null || !mDoneBooting) {
2015 try {
2016 mLocks.wait();
2017 } catch (InterruptedException e) {
2018 // Ignore
2019 }
2020 }
2021 return mPolicy;
2022 }
2023
2024 void systemReady() {
2025 synchronized (mLocks) {
2026 Log.d(TAG, "system ready!");
2027 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002028 long identity = Binder.clearCallingIdentity();
2029 try {
2030 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2031 mBatteryStats.noteScreenOn();
2032 } catch (RemoteException e) {
2033 // Nothing interesting to do.
2034 } finally {
2035 Binder.restoreCallingIdentity(identity);
2036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2038 updateWakeLockLocked();
2039 mLocks.notifyAll();
2040 }
2041 }
2042
2043 public void monitor() {
2044 synchronized (mLocks) { }
2045 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002046
2047 public int getSupportedWakeLockFlags() {
2048 int result = PowerManager.PARTIAL_WAKE_LOCK
2049 | PowerManager.FULL_WAKE_LOCK
2050 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2051
2052 // call getSensorManager() to make sure mProximitySensor is initialized
2053 getSensorManager();
2054 if (mProximitySensor != null) {
2055 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2056 }
2057
2058 return result;
2059 }
2060
Mike Lockwood237a2992009-09-15 14:42:16 -04002061 public void setBacklightBrightness(int brightness) {
2062 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2063 // Don't let applications turn the screen all the way off
2064 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2065 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness);
2066 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, brightness);
2067 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness);
2068 long identity = Binder.clearCallingIdentity();
2069 try {
2070 mBatteryStats.noteScreenBrightness(brightness);
2071 } catch (RemoteException e) {
2072 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2073 } finally {
2074 Binder.restoreCallingIdentity(identity);
2075 }
2076
2077 // update our animation state
2078 if (ANIMATE_SCREEN_LIGHTS) {
2079 mScreenBrightness.curValue = brightness;
2080 mScreenBrightness.animating = false;
2081 }
2082 if (ANIMATE_KEYBOARD_LIGHTS) {
2083 mKeyboardBrightness.curValue = brightness;
2084 mKeyboardBrightness.animating = false;
2085 }
2086 if (ANIMATE_BUTTON_LIGHTS) {
2087 mButtonBrightness.curValue = brightness;
2088 mButtonBrightness.animating = false;
2089 }
2090 }
2091
2092 public void setAutoBrightness(boolean on) {
2093 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2094 mHardware.setAutoBrightness_UNCHECKED(on);
2095 }
2096
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002097 private SensorManager getSensorManager() {
2098 if (mSensorManager == null) {
2099 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2100 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2101 }
2102 return mSensorManager;
2103 }
2104
2105 private void enableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002106 if (mSpew) {
2107 Log.d(TAG, "enableProximityLockLocked");
2108 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002109 mSensorManager.registerListener(this, mProximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
2110 }
2111
2112 private void disableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002113 if (mSpew) {
2114 Log.d(TAG, "disableProximityLockLocked");
2115 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002116 mSensorManager.unregisterListener(this);
Mike Lockwood36fc3022009-08-25 16:49:06 -07002117 mProximitySensorActive = false;
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002118 }
2119
2120 public void onSensorChanged(SensorEvent event) {
2121 long milliseconds = event.timestamp / 1000000;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002122 synchronized (mLocks) {
Mike Lockwoodd20ea362009-09-15 00:13:38 -04002123 float distance = event.values[0];
2124 if (distance >= 0.0 && distance < PROXIMITY_THRESHOLD) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002125 if (mSpew) {
Mike Lockwoodd20ea362009-09-15 00:13:38 -04002126 Log.d(TAG, "onSensorChanged: proximity active, distance: " + distance);
Mike Lockwood36fc3022009-08-25 16:49:06 -07002127 }
2128 goToSleepLocked(milliseconds);
2129 mProximitySensorActive = true;
2130 } else {
Mike Lockwoodd20ea362009-09-15 00:13:38 -04002131 // proximity sensor negative events trigger as user activity.
Mike Lockwood36fc3022009-08-25 16:49:06 -07002132 // temporarily set mUserActivityAllowed to true so this will work
2133 // even when the keyguard is on.
2134 if (mSpew) {
Mike Lockwoodd20ea362009-09-15 00:13:38 -04002135 Log.d(TAG, "onSensorChanged: proximity inactive, distance: " + distance);
Mike Lockwood36fc3022009-08-25 16:49:06 -07002136 }
2137 mProximitySensorActive = false;
Mike Lockwood06952d92009-08-13 16:05:38 -04002138 boolean savedActivityAllowed = mUserActivityAllowed;
2139 mUserActivityAllowed = true;
2140 userActivity(milliseconds, false);
2141 mUserActivityAllowed = savedActivityAllowed;
2142 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002143 }
2144 }
2145
2146 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2147 // ignore
2148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149}