blob: a1220b650dccf389534d446741ec3ec8a6ac8493 [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;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070056import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
58import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
59
60import java.io.FileDescriptor;
61import java.io.PrintWriter;
62import java.util.ArrayList;
63import java.util.HashMap;
64import java.util.Observable;
65import java.util.Observer;
66
Mike Lockwoodbc706a02009-07-27 13:50:57 -070067class PowerManagerService extends IPowerManager.Stub
Mike Lockwooda625b382009-09-12 17:36:03 -070068 implements LocalPowerManager, Watchdog.Monitor, SensorEventListener {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
70 private static final String TAG = "PowerManagerService";
71 static final String PARTIAL_NAME = "PowerManagerService";
72
73 private static final boolean LOG_PARTIAL_WL = false;
74
75 // Indicates whether touch-down cycles should be logged as part of the
76 // LOG_POWER_SCREEN_STATE log events
77 private static final boolean LOG_TOUCH_DOWNS = true;
78
79 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
80 | PowerManager.SCREEN_DIM_WAKE_LOCK
81 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070082 | PowerManager.FULL_WAKE_LOCK
83 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084
85 // time since last state: time since last event:
86 // The short keylight delay comes from Gservices; this is the default.
87 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
88 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
89 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
90 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
91
Mike Lockwoodd20ea362009-09-15 00:13:38 -040092 // trigger proximity if distance is less than 5 cm
93 private static final float PROXIMITY_THRESHOLD = 5.0f;
94
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 // Cached Gservices settings; see updateGservicesValues()
96 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
97
98 // flags for setPowerState
99 private static final int SCREEN_ON_BIT = 0x00000001;
100 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
101 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
102 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
103 private static final int BATTERY_LOW_BIT = 0x00000010;
104
105 // values for setPowerState
106
107 // SCREEN_OFF == everything off
108 private static final int SCREEN_OFF = 0x00000000;
109
110 // SCREEN_DIM == screen on, screen backlight dim
111 private static final int SCREEN_DIM = SCREEN_ON_BIT;
112
113 // SCREEN_BRIGHT == screen on, screen backlight bright
114 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
115
116 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
117 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
118
119 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
120 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
121
122 // used for noChangeLights in setPowerState()
123 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
124
125 static final boolean ANIMATE_SCREEN_LIGHTS = true;
126 static final boolean ANIMATE_BUTTON_LIGHTS = false;
127 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
128
129 static final int ANIM_STEPS = 60/4;
130
131 // These magic numbers are the initial state of the LEDs at boot. Ideally
132 // we should read them from the driver, but our current hardware returns 0
133 // for the initial value. Oops!
134 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
135 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
136 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
137
138 static final int LOG_POWER_SLEEP_REQUESTED = 2724;
139 static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
140 static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
141 static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
142 static final int LOG_POWER_SCREEN_STATE = 2728;
143 static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
144
145 private final int MY_UID;
146
147 private boolean mDoneBooting = false;
148 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700149 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
150 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 private int mPartialCount = 0;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700152 private int mProximityCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 private int mPowerState;
154 private boolean mOffBecauseOfUser;
155 private int mUserState;
156 private boolean mKeyboardVisible = false;
157 private boolean mUserActivityAllowed = true;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700158 private boolean mProximitySensorActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private int mTotalDelaySetting;
160 private int mKeylightDelay;
161 private int mDimDelay;
162 private int mScreenOffDelay;
163 private int mWakeLockState;
164 private long mLastEventTime = 0;
165 private long mScreenOffTime;
166 private volatile WindowManagerPolicy mPolicy;
167 private final LockList mLocks = new LockList();
168 private Intent mScreenOffIntent;
169 private Intent mScreenOnIntent;
The Android Open Source Project10592532009-03-18 17:39:46 -0700170 private HardwareService mHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 private Context mContext;
172 private UnsynchronizedWakeLock mBroadcastWakeLock;
173 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
174 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
175 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
176 private HandlerThread mHandlerThread;
177 private Handler mHandler;
178 private TimeoutTask mTimeoutTask = new TimeoutTask();
179 private LightAnimator mLightAnimator = new LightAnimator();
180 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700181 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700183 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700185 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700186 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 private boolean mIsPowered = false;
188 private IActivityManager mActivityService;
189 private IBatteryStats mBatteryStats;
190 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700191 private SensorManager mSensorManager;
192 private Sensor mProximitySensor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private boolean mDimScreen = true;
194 private long mNextTimeout;
195 private volatile int mPokey = 0;
196 private volatile boolean mPokeAwakeOnSet = false;
197 private volatile boolean mInitComplete = false;
198 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
199 private long mScreenOnTime;
200 private long mScreenOnStartTime;
201 private boolean mPreventScreenOn;
202 private int mScreenBrightnessOverride = -1;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700203 private boolean mHasHardwareAutoBrightness;
204 private boolean mAutoBrightessEnabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
206 // Used when logging number and duration of touch-down cycles
207 private long mTotalTouchDownTime;
208 private long mLastTouchDown;
209 private int mTouchCycles;
210
211 // could be either static or controllable at runtime
212 private static final boolean mSpew = false;
213
214 /*
215 static PrintStream mLog;
216 static {
217 try {
218 mLog = new PrintStream("/data/power.log");
219 }
220 catch (FileNotFoundException e) {
221 android.util.Log.e(TAG, "Life is hard", e);
222 }
223 }
224 static class Log {
225 static void d(String tag, String s) {
226 mLog.println(s);
227 android.util.Log.d(tag, s);
228 }
229 static void i(String tag, String s) {
230 mLog.println(s);
231 android.util.Log.i(tag, s);
232 }
233 static void w(String tag, String s) {
234 mLog.println(s);
235 android.util.Log.w(tag, s);
236 }
237 static void e(String tag, String s) {
238 mLog.println(s);
239 android.util.Log.e(tag, s);
240 }
241 }
242 */
243
244 /**
245 * This class works around a deadlock between the lock in PowerManager.WakeLock
246 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
247 * mToken object so it can be accessed from any thread, but it calls into here
248 * with its lock held. This class is essentially a reimplementation of
249 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
250 * only call it with our own locks held.
251 */
252 private class UnsynchronizedWakeLock {
253 int mFlags;
254 String mTag;
255 IBinder mToken;
256 int mCount = 0;
257 boolean mRefCounted;
258
259 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
260 mFlags = flags;
261 mTag = tag;
262 mToken = new Binder();
263 mRefCounted = refCounted;
264 }
265
266 public void acquire() {
267 if (!mRefCounted || mCount++ == 0) {
268 long ident = Binder.clearCallingIdentity();
269 try {
270 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
271 MY_UID, mTag);
272 } finally {
273 Binder.restoreCallingIdentity(ident);
274 }
275 }
276 }
277
278 public void release() {
279 if (!mRefCounted || --mCount == 0) {
280 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
281 }
282 if (mCount < 0) {
283 throw new RuntimeException("WakeLock under-locked " + mTag);
284 }
285 }
286
287 public String toString() {
288 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
289 + " mCount=" + mCount + ")";
290 }
291 }
292
293 private final class BatteryReceiver extends BroadcastReceiver {
294 @Override
295 public void onReceive(Context context, Intent intent) {
296 synchronized (mLocks) {
297 boolean wasPowered = mIsPowered;
298 mIsPowered = mBatteryService.isPowered();
299
300 if (mIsPowered != wasPowered) {
301 // update mStayOnWhilePluggedIn wake lock
302 updateWakeLockLocked();
303
304 // treat plugging and unplugging the devices as a user activity.
305 // users find it disconcerting when they unplug the device
306 // and it shuts off right away.
307 // temporarily set mUserActivityAllowed to true so this will work
308 // even when the keyguard is on.
309 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400310 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 }
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
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700350 // SCREEN_BRIGHTNESS_MODE
351 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 // recalculate everything
354 setScreenOffTimeoutsLocked();
355 }
356 }
357 }
358
359 PowerManagerService()
360 {
361 // Hack to get our uid... should have a func for this.
362 long token = Binder.clearCallingIdentity();
363 MY_UID = Binder.getCallingUid();
364 Binder.restoreCallingIdentity(token);
365
366 // XXX remove this when the kernel doesn't timeout wake locks
367 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
368
369 // assume nothing is on yet
370 mUserState = mPowerState = 0;
371
372 // Add ourself to the Watchdog monitors.
373 Watchdog.getInstance().addMonitor(this);
374 mScreenOnStartTime = SystemClock.elapsedRealtime();
375 }
376
377 private ContentQueryMap mSettings;
378
The Android Open Source Project10592532009-03-18 17:39:46 -0700379 void init(Context context, HardwareService hardware, IActivityManager activity,
380 BatteryService battery) {
381 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 mContext = context;
383 mActivityService = activity;
384 mBatteryStats = BatteryStatsService.getService();
385 mBatteryService = battery;
386
387 mHandlerThread = new HandlerThread("PowerManagerService") {
388 @Override
389 protected void onLooperPrepared() {
390 super.onLooperPrepared();
391 initInThread();
392 }
393 };
394 mHandlerThread.start();
395
396 synchronized (mHandlerThread) {
397 while (!mInitComplete) {
398 try {
399 mHandlerThread.wait();
400 } catch (InterruptedException e) {
401 // Ignore
402 }
403 }
404 }
405 }
406
407 void initInThread() {
408 mHandler = new Handler();
409
410 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700411 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
413 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
414 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
415 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
416 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
417 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
418
419 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
420 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
421 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
422 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
423
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700424 mHasHardwareAutoBrightness = mContext.getResources().getBoolean(
425 com.android.internal.R.bool.config_hardware_automatic_brightness_available);
426
427 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
429 "(" + Settings.System.NAME + "=?) or ("
430 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700431 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700433 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
434 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 null);
436 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
437 SettingsObserver settingsObserver = new SettingsObserver();
438 mSettings.addObserver(settingsObserver);
439
440 // pretend that the settings changed so we will get their initial state
441 settingsObserver.update(mSettings, null);
442
443 // register for the battery changed notifications
444 IntentFilter filter = new IntentFilter();
445 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
446 mContext.registerReceiver(new BatteryReceiver(), filter);
447
448 // Listen for Gservices changes
449 IntentFilter gservicesChangedFilter =
450 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
451 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
452 // And explicitly do the initial update of our cached settings
453 updateGservicesValues();
454
455 // turn everything on
456 setPowerState(ALL_BRIGHT);
Dan Murphy951764b2009-08-27 14:59:03 -0500457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 synchronized (mHandlerThread) {
459 mInitComplete = true;
460 mHandlerThread.notifyAll();
461 }
462 }
463
464 private class WakeLock implements IBinder.DeathRecipient
465 {
466 WakeLock(int f, IBinder b, String t, int u) {
467 super();
468 flags = f;
469 binder = b;
470 tag = t;
471 uid = u == MY_UID ? Process.SYSTEM_UID : u;
472 if (u != MY_UID || (
473 !"KEEP_SCREEN_ON_FLAG".equals(tag)
474 && !"KeyInputQueue".equals(tag))) {
475 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
476 ? BatteryStats.WAKE_TYPE_PARTIAL
477 : BatteryStats.WAKE_TYPE_FULL;
478 } else {
479 monitorType = -1;
480 }
481 try {
482 b.linkToDeath(this, 0);
483 } catch (RemoteException e) {
484 binderDied();
485 }
486 }
487 public void binderDied() {
488 synchronized (mLocks) {
489 releaseWakeLockLocked(this.binder, true);
490 }
491 }
492 final int flags;
493 final IBinder binder;
494 final String tag;
495 final int uid;
496 final int monitorType;
497 boolean activated = true;
498 int minState;
499 }
500
501 private void updateWakeLockLocked() {
502 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
503 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
504 mStayOnWhilePluggedInScreenDimLock.acquire();
505 mStayOnWhilePluggedInPartialLock.acquire();
506 } else {
507 mStayOnWhilePluggedInScreenDimLock.release();
508 mStayOnWhilePluggedInPartialLock.release();
509 }
510 }
511
512 private boolean isScreenLock(int flags)
513 {
514 int n = flags & LOCK_MASK;
515 return n == PowerManager.FULL_WAKE_LOCK
516 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
517 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
518 }
519
520 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700522 if (uid != Process.myUid()) {
523 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 long ident = Binder.clearCallingIdentity();
526 try {
527 synchronized (mLocks) {
528 acquireWakeLockLocked(flags, lock, uid, tag);
529 }
530 } finally {
531 Binder.restoreCallingIdentity(ident);
532 }
533 }
534
535 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
536 int acquireUid = -1;
537 String acquireName = null;
538 int acquireType = -1;
539
540 if (mSpew) {
541 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
542 }
543
544 int index = mLocks.getIndex(lock);
545 WakeLock wl;
546 boolean newlock;
547 if (index < 0) {
548 wl = new WakeLock(flags, lock, tag, uid);
549 switch (wl.flags & LOCK_MASK)
550 {
551 case PowerManager.FULL_WAKE_LOCK:
552 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
553 break;
554 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
555 wl.minState = SCREEN_BRIGHT;
556 break;
557 case PowerManager.SCREEN_DIM_WAKE_LOCK:
558 wl.minState = SCREEN_DIM;
559 break;
560 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700561 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 break;
563 default:
564 // just log and bail. we're in the server, so don't
565 // throw an exception.
566 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
567 + " flags=" + flags);
568 return;
569 }
570 mLocks.addLock(wl);
571 newlock = true;
572 } else {
573 wl = mLocks.get(index);
574 newlock = false;
575 }
576 if (isScreenLock(flags)) {
577 // if this causes a wakeup, we reactivate all of the locks and
578 // set it to whatever they want. otherwise, we modulate that
579 // by the current state so we never turn it more on than
580 // it already is.
581 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700582 int oldWakeLockState = mWakeLockState;
583 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 if (mSpew) {
585 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700586 + " mWakeLockState=0x"
587 + Integer.toHexString(mWakeLockState)
588 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 } else {
591 if (mSpew) {
592 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
593 + " mLocks.gatherState()=0x"
594 + Integer.toHexString(mLocks.gatherState())
595 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
596 }
597 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
598 }
599 setPowerState(mWakeLockState | mUserState);
600 }
601 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
602 if (newlock) {
603 mPartialCount++;
604 if (mPartialCount == 1) {
605 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
606 }
607 }
608 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700609 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
610 mProximityCount++;
611 if (mProximityCount == 1) {
612 enableProximityLockLocked();
613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 }
615 if (newlock) {
616 acquireUid = wl.uid;
617 acquireName = wl.tag;
618 acquireType = wl.monitorType;
619 }
620
621 if (acquireType >= 0) {
622 try {
623 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
624 } catch (RemoteException e) {
625 // Ignore
626 }
627 }
628 }
629
630 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700631 int uid = Binder.getCallingUid();
632 if (uid != Process.myUid()) {
633 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635
636 synchronized (mLocks) {
637 releaseWakeLockLocked(lock, false);
638 }
639 }
640
641 private void releaseWakeLockLocked(IBinder lock, boolean death) {
642 int releaseUid;
643 String releaseName;
644 int releaseType;
645
646 WakeLock wl = mLocks.removeLock(lock);
647 if (wl == null) {
648 return;
649 }
650
651 if (mSpew) {
652 Log.d(TAG, "releaseWakeLock flags=0x"
653 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
654 }
655
656 if (isScreenLock(wl.flags)) {
657 mWakeLockState = mLocks.gatherState();
658 // goes in the middle to reduce flicker
659 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
660 userActivity(SystemClock.uptimeMillis(), false);
661 }
662 setPowerState(mWakeLockState | mUserState);
663 }
664 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
665 mPartialCount--;
666 if (mPartialCount == 0) {
667 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
668 Power.releaseWakeLock(PARTIAL_NAME);
669 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700670 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
671 mProximityCount--;
672 if (mProximityCount == 0) {
673 disableProximityLockLocked();
674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 }
676 // Unlink the lock from the binder.
677 wl.binder.unlinkToDeath(wl, 0);
678 releaseUid = wl.uid;
679 releaseName = wl.tag;
680 releaseType = wl.monitorType;
681
682 if (releaseType >= 0) {
683 long origId = Binder.clearCallingIdentity();
684 try {
685 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
686 } catch (RemoteException e) {
687 // Ignore
688 } finally {
689 Binder.restoreCallingIdentity(origId);
690 }
691 }
692 }
693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 private class PokeLock implements IBinder.DeathRecipient
695 {
696 PokeLock(int p, IBinder b, String t) {
697 super();
698 this.pokey = p;
699 this.binder = b;
700 this.tag = t;
701 try {
702 b.linkToDeath(this, 0);
703 } catch (RemoteException e) {
704 binderDied();
705 }
706 }
707 public void binderDied() {
708 setPokeLock(0, this.binder, this.tag);
709 }
710 int pokey;
711 IBinder binder;
712 String tag;
713 boolean awakeOnSet;
714 }
715
716 public void setPokeLock(int pokey, IBinder token, String tag) {
717 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
718 if (token == null) {
719 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
720 return;
721 }
722
723 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
724 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
725 + " and POKE_LOCK_MEDIUM_TIMEOUT");
726 }
727
728 synchronized (mLocks) {
729 if (pokey != 0) {
730 PokeLock p = mPokeLocks.get(token);
731 int oldPokey = 0;
732 if (p != null) {
733 oldPokey = p.pokey;
734 p.pokey = pokey;
735 } else {
736 p = new PokeLock(pokey, token, tag);
737 mPokeLocks.put(token, p);
738 }
739 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
740 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
741 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
742 p.awakeOnSet = true;
743 }
744 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700745 PokeLock rLock = mPokeLocks.remove(token);
746 if (rLock != null) {
747 token.unlinkToDeath(rLock, 0);
748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 }
750
751 int oldPokey = mPokey;
752 int cumulative = 0;
753 boolean oldAwakeOnSet = mPokeAwakeOnSet;
754 boolean awakeOnSet = false;
755 for (PokeLock p: mPokeLocks.values()) {
756 cumulative |= p.pokey;
757 if (p.awakeOnSet) {
758 awakeOnSet = true;
759 }
760 }
761 mPokey = cumulative;
762 mPokeAwakeOnSet = awakeOnSet;
763
764 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
765 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
766
767 if (oldCumulativeTimeout != newCumulativeTimeout) {
768 setScreenOffTimeoutsLocked();
769 // reset the countdown timer, but use the existing nextState so it doesn't
770 // change anything
771 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
772 }
773 }
774 }
775
776 private static String lockType(int type)
777 {
778 switch (type)
779 {
780 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700781 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700783 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700785 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700787 return "PARTIAL_WAKE_LOCK ";
788 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
789 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 default:
David Brown251faa62009-08-02 22:04:36 -0700791 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 }
793 }
794
795 private static String dumpPowerState(int state) {
796 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
797 ? "KEYBOARD_BRIGHT_BIT " : "")
798 + (((state & SCREEN_BRIGHT_BIT) != 0)
799 ? "SCREEN_BRIGHT_BIT " : "")
800 + (((state & SCREEN_ON_BIT) != 0)
801 ? "SCREEN_ON_BIT " : "")
802 + (((state & BATTERY_LOW_BIT) != 0)
803 ? "BATTERY_LOW_BIT " : "");
804 }
805
806 @Override
807 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
808 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
809 != PackageManager.PERMISSION_GRANTED) {
810 pw.println("Permission Denial: can't dump PowerManager from from pid="
811 + Binder.getCallingPid()
812 + ", uid=" + Binder.getCallingUid());
813 return;
814 }
815
816 long now = SystemClock.uptimeMillis();
817
818 pw.println("Power Manager State:");
819 pw.println(" mIsPowered=" + mIsPowered
820 + " mPowerState=" + mPowerState
821 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
822 + " ms");
823 pw.println(" mPartialCount=" + mPartialCount);
824 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
825 pw.println(" mUserState=" + dumpPowerState(mUserState));
826 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
827 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
828 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
829 + " " + ((mNextTimeout-now)/1000) + "s from now");
830 pw.println(" mDimScreen=" + mDimScreen
831 + " mStayOnConditions=" + mStayOnConditions);
832 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
833 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700834 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
835 + ',' + mBroadcastQueue[2] + "}");
836 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
837 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
839 pw.println(" mKeyboardVisible=" + mKeyboardVisible
840 + " mUserActivityAllowed=" + mUserActivityAllowed);
841 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
842 + " mScreenOffDelay=" + mScreenOffDelay);
843 pw.println(" mPreventScreenOn=" + mPreventScreenOn
844 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
845 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
846 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
847 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
848 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
849 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
850 mScreenBrightness.dump(pw, " mScreenBrightness: ");
851 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
852 mButtonBrightness.dump(pw, " mButtonBrightness: ");
853
854 int N = mLocks.size();
855 pw.println();
856 pw.println("mLocks.size=" + N + ":");
857 for (int i=0; i<N; i++) {
858 WakeLock wl = mLocks.get(i);
859 String type = lockType(wl.flags & LOCK_MASK);
860 String acquireCausesWakeup = "";
861 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
862 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
863 }
864 String activated = "";
865 if (wl.activated) {
866 activated = " activated";
867 }
868 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
869 + activated + " (minState=" + wl.minState + ")");
870 }
871
872 pw.println();
873 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
874 for (PokeLock p: mPokeLocks.values()) {
875 pw.println(" poke lock '" + p.tag + "':"
876 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
877 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700878 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
879 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
881 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
882 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
883 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
884 }
885
886 pw.println();
887 }
888
889 private void setTimeoutLocked(long now, int nextState)
890 {
891 if (mDoneBooting) {
892 mHandler.removeCallbacks(mTimeoutTask);
893 mTimeoutTask.nextState = nextState;
894 long when = now;
895 switch (nextState)
896 {
897 case SCREEN_BRIGHT:
898 when += mKeylightDelay;
899 break;
900 case SCREEN_DIM:
901 if (mDimDelay >= 0) {
902 when += mDimDelay;
903 break;
904 } else {
905 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
906 }
907 case SCREEN_OFF:
908 synchronized (mLocks) {
909 when += mScreenOffDelay;
910 }
911 break;
912 }
913 if (mSpew) {
914 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
915 + " when=" + when);
916 }
917 mHandler.postAtTime(mTimeoutTask, when);
918 mNextTimeout = when; // for debugging
919 }
920 }
921
922 private void cancelTimerLocked()
923 {
924 mHandler.removeCallbacks(mTimeoutTask);
925 mTimeoutTask.nextState = -1;
926 }
927
928 private class TimeoutTask implements Runnable
929 {
930 int nextState; // access should be synchronized on mLocks
931 public void run()
932 {
933 synchronized (mLocks) {
934 if (mSpew) {
935 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
936 }
937
938 if (nextState == -1) {
939 return;
940 }
941
942 mUserState = this.nextState;
943 setPowerState(this.nextState | mWakeLockState);
944
945 long now = SystemClock.uptimeMillis();
946
947 switch (this.nextState)
948 {
949 case SCREEN_BRIGHT:
950 if (mDimDelay >= 0) {
951 setTimeoutLocked(now, SCREEN_DIM);
952 break;
953 }
954 case SCREEN_DIM:
955 setTimeoutLocked(now, SCREEN_OFF);
956 break;
957 }
958 }
959 }
960 }
961
962 private void sendNotificationLocked(boolean on, int why)
963 {
Joe Onorato64c62ba2009-03-24 20:13:57 -0700964 if (!on) {
965 mStillNeedSleepNotification = false;
966 }
967
Joe Onorato128e7292009-03-24 18:41:31 -0700968 // Add to the queue.
969 int index = 0;
970 while (mBroadcastQueue[index] != -1) {
971 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 }
Joe Onorato128e7292009-03-24 18:41:31 -0700973 mBroadcastQueue[index] = on ? 1 : 0;
974 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975
Joe Onorato128e7292009-03-24 18:41:31 -0700976 // If we added it position 2, then there is a pair that can be stripped.
977 // If we added it position 1 and we're turning the screen off, we can strip
978 // the pair and do nothing, because the screen is already off, and therefore
979 // keyguard has already been enabled.
980 // However, if we added it at position 1 and we're turning it on, then position
981 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
982 // on, so have to run the queue then.
983 if (index == 2) {
984 // Also, while we're collapsing them, if it's going to be an "off," and one
985 // is off because of user, then use that, regardless of whether it's the first
986 // or second one.
987 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
988 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
989 }
990 mBroadcastQueue[0] = on ? 1 : 0;
991 mBroadcastQueue[1] = -1;
992 mBroadcastQueue[2] = -1;
993 index = 0;
994 }
995 if (index == 1 && !on) {
996 mBroadcastQueue[0] = -1;
997 mBroadcastQueue[1] = -1;
998 index = -1;
999 // The wake lock was being held, but we're not actually going to do any
1000 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1002 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001003 }
1004
1005 // Now send the message.
1006 if (index >= 0) {
1007 // Acquire the broadcast wake lock before changing the power
1008 // state. It will be release after the broadcast is sent.
1009 // We always increment the ref count for each notification in the queue
1010 // and always decrement when that notification is handled.
1011 mBroadcastWakeLock.acquire();
1012 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1013 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 }
1015 }
1016
1017 private Runnable mNotificationTask = new Runnable()
1018 {
1019 public void run()
1020 {
Joe Onorato128e7292009-03-24 18:41:31 -07001021 while (true) {
1022 int value;
1023 int why;
1024 WindowManagerPolicy policy;
1025 synchronized (mLocks) {
1026 value = mBroadcastQueue[0];
1027 why = mBroadcastWhy[0];
1028 for (int i=0; i<2; i++) {
1029 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1030 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1031 }
1032 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 }
Joe Onorato128e7292009-03-24 18:41:31 -07001034 if (value == 1) {
1035 mScreenOnStart = SystemClock.uptimeMillis();
1036
1037 policy.screenTurnedOn();
1038 try {
1039 ActivityManagerNative.getDefault().wakingUp();
1040 } catch (RemoteException e) {
1041 // ignore it
1042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043
Joe Onorato128e7292009-03-24 18:41:31 -07001044 if (mSpew) {
1045 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1046 }
1047 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1048 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1049 mScreenOnBroadcastDone, mHandler, 0, null, null);
1050 } else {
1051 synchronized (mLocks) {
1052 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1053 mBroadcastWakeLock.mCount);
1054 mBroadcastWakeLock.release();
1055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 }
1057 }
Joe Onorato128e7292009-03-24 18:41:31 -07001058 else if (value == 0) {
1059 mScreenOffStart = SystemClock.uptimeMillis();
1060
1061 policy.screenTurnedOff(why);
1062 try {
1063 ActivityManagerNative.getDefault().goingToSleep();
1064 } catch (RemoteException e) {
1065 // ignore it.
1066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067
Joe Onorato128e7292009-03-24 18:41:31 -07001068 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1069 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1070 mScreenOffBroadcastDone, mHandler, 0, null, null);
1071 } else {
1072 synchronized (mLocks) {
1073 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1074 mBroadcastWakeLock.mCount);
1075 mBroadcastWakeLock.release();
1076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 }
1078 }
Joe Onorato128e7292009-03-24 18:41:31 -07001079 else {
1080 // If we're in this case, then this handler is running for a previous
1081 // paired transaction. mBroadcastWakeLock will already have been released.
1082 break;
1083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 }
1085 }
1086 };
1087
1088 long mScreenOnStart;
1089 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1090 public void onReceive(Context context, Intent intent) {
1091 synchronized (mLocks) {
1092 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1093 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1094 mBroadcastWakeLock.release();
1095 }
1096 }
1097 };
1098
1099 long mScreenOffStart;
1100 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1101 public void onReceive(Context context, Intent intent) {
1102 synchronized (mLocks) {
1103 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1104 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1105 mBroadcastWakeLock.release();
1106 }
1107 }
1108 };
1109
1110 void logPointerUpEvent() {
1111 if (LOG_TOUCH_DOWNS) {
1112 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1113 mLastTouchDown = 0;
1114 }
1115 }
1116
1117 void logPointerDownEvent() {
1118 if (LOG_TOUCH_DOWNS) {
1119 // If we are not already timing a down/up sequence
1120 if (mLastTouchDown == 0) {
1121 mLastTouchDown = SystemClock.elapsedRealtime();
1122 mTouchCycles++;
1123 }
1124 }
1125 }
1126
1127 /**
1128 * Prevents the screen from turning on even if it *should* turn on due
1129 * to a subsequent full wake lock being acquired.
1130 * <p>
1131 * This is a temporary hack that allows an activity to "cover up" any
1132 * display glitches that happen during the activity's startup
1133 * sequence. (Specifically, this API was added to work around a
1134 * cosmetic bug in the "incoming call" sequence, where the lock screen
1135 * would flicker briefly before the incoming call UI became visible.)
1136 * TODO: There ought to be a more elegant way of doing this,
1137 * probably by having the PowerManager and ActivityManager
1138 * work together to let apps specify that the screen on/off
1139 * state should be synchronized with the Activity lifecycle.
1140 * <p>
1141 * Note that calling preventScreenOn(true) will NOT turn the screen
1142 * off if it's currently on. (This API only affects *future*
1143 * acquisitions of full wake locks.)
1144 * But calling preventScreenOn(false) WILL turn the screen on if
1145 * it's currently off because of a prior preventScreenOn(true) call.
1146 * <p>
1147 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1148 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1149 * call doesn't occur within 5 seconds, we'll turn the screen back on
1150 * ourselves (and log a warning about it); this prevents a buggy app
1151 * from disabling the screen forever.)
1152 * <p>
1153 * TODO: this feature should really be controlled by a new type of poke
1154 * lock (rather than an IPowerManager call).
1155 */
1156 public void preventScreenOn(boolean prevent) {
1157 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1158
1159 synchronized (mLocks) {
1160 if (prevent) {
1161 // First of all, grab a partial wake lock to
1162 // make sure the CPU stays on during the entire
1163 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1164 mPreventScreenOnPartialLock.acquire();
1165
1166 // Post a forceReenableScreen() call (for 5 seconds in the
1167 // future) to make sure the matching preventScreenOn(false) call
1168 // has happened by then.
1169 mHandler.removeCallbacks(mForceReenableScreenTask);
1170 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1171
1172 // Finally, set the flag that prevents the screen from turning on.
1173 // (Below, in setPowerState(), we'll check mPreventScreenOn and
1174 // we *won't* call Power.setScreenState(true) if it's set.)
1175 mPreventScreenOn = true;
1176 } else {
1177 // (Re)enable the screen.
1178 mPreventScreenOn = false;
1179
1180 // We're "undoing" a the prior preventScreenOn(true) call, so we
1181 // no longer need the 5-second safeguard.
1182 mHandler.removeCallbacks(mForceReenableScreenTask);
1183
1184 // Forcibly turn on the screen if it's supposed to be on. (This
1185 // handles the case where the screen is currently off because of
1186 // a prior preventScreenOn(true) call.)
1187 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1188 if (mSpew) {
1189 Log.d(TAG,
1190 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1191 }
1192 int err = Power.setScreenState(true);
1193 if (err != 0) {
1194 Log.w(TAG, "preventScreenOn: error from Power.setScreenState(): " + err);
1195 }
1196 }
1197
1198 // Release the partial wake lock that we held during the
1199 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1200 mPreventScreenOnPartialLock.release();
1201 }
1202 }
1203 }
1204
1205 public void setScreenBrightnessOverride(int brightness) {
1206 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1207
1208 synchronized (mLocks) {
1209 if (mScreenBrightnessOverride != brightness) {
1210 mScreenBrightnessOverride = brightness;
1211 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1212 }
1213 }
1214 }
1215
1216 /**
1217 * Sanity-check that gets called 5 seconds after any call to
1218 * preventScreenOn(true). This ensures that the original call
1219 * is followed promptly by a call to preventScreenOn(false).
1220 */
1221 private void forceReenableScreen() {
1222 // We shouldn't get here at all if mPreventScreenOn is false, since
1223 // we should have already removed any existing
1224 // mForceReenableScreenTask messages...
1225 if (!mPreventScreenOn) {
1226 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1227 return;
1228 }
1229
1230 // Uh oh. It's been 5 seconds since a call to
1231 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1232 // This means the app that called preventScreenOn(true) is either
1233 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1234 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1235 // crashed before doing so.)
1236
1237 // Log a warning, and forcibly turn the screen back on.
1238 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1239 + "Forcing the screen back on...");
1240 preventScreenOn(false);
1241 }
1242
1243 private Runnable mForceReenableScreenTask = new Runnable() {
1244 public void run() {
1245 forceReenableScreen();
1246 }
1247 };
1248
1249 private void setPowerState(int state)
1250 {
1251 setPowerState(state, false, false);
1252 }
1253
1254 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1255 {
1256 synchronized (mLocks) {
1257 int err;
1258
1259 if (mSpew) {
1260 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1261 + " newState=0x" + Integer.toHexString(newState)
1262 + " noChangeLights=" + noChangeLights);
1263 }
1264
1265 if (noChangeLights) {
1266 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1267 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001268 if (mProximitySensorActive) {
1269 // don't turn on the screen when the proximity sensor lock is held
1270 newState = (newState & ~SCREEN_BRIGHT);
1271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272
1273 if (batteryIsLow()) {
1274 newState |= BATTERY_LOW_BIT;
1275 } else {
1276 newState &= ~BATTERY_LOW_BIT;
1277 }
1278 if (newState == mPowerState) {
1279 return;
1280 }
1281
1282 if (!mDoneBooting) {
1283 newState |= ALL_BRIGHT;
1284 }
1285
1286 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1287 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1288
1289 if (mSpew) {
1290 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1291 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1292 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1293 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1294 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1295 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1296 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1297 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1298 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1299 + " newScreenOn=" + newScreenOn);
1300 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1301 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1302 }
1303
1304 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001305 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1307 }
1308
1309 if (oldScreenOn != newScreenOn) {
1310 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001311 // When the user presses the power button, we need to always send out the
1312 // notification that it's going to sleep so the keyguard goes on. But
1313 // we can't do that until the screen fades out, so we don't show the keyguard
1314 // too early.
1315 if (mStillNeedSleepNotification) {
1316 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1317 }
1318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 // Turn on the screen UNLESS there was a prior
1320 // preventScreenOn(true) request. (Note that the lifetime
1321 // of a single preventScreenOn() request is limited to 5
1322 // seconds to prevent a buggy app from disabling the
1323 // screen forever; see forceReenableScreen().)
1324 boolean reallyTurnScreenOn = true;
1325 if (mSpew) {
1326 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1327 + mPreventScreenOn);
1328 }
1329
1330 if (mPreventScreenOn) {
1331 if (mSpew) {
1332 Log.d(TAG, "- PREVENTING screen from really turning on!");
1333 }
1334 reallyTurnScreenOn = false;
1335 }
1336 if (reallyTurnScreenOn) {
1337 err = Power.setScreenState(true);
1338 long identity = Binder.clearCallingIdentity();
1339 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001340 mBatteryStats.noteScreenBrightness(
1341 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 mBatteryStats.noteScreenOn();
1343 } catch (RemoteException e) {
1344 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1345 } finally {
1346 Binder.restoreCallingIdentity(identity);
1347 }
1348 } else {
1349 Power.setScreenState(false);
1350 // But continue as if we really did turn the screen on...
1351 err = 0;
1352 }
1353
1354 mScreenOnStartTime = SystemClock.elapsedRealtime();
1355 mLastTouchDown = 0;
1356 mTotalTouchDownTime = 0;
1357 mTouchCycles = 0;
1358 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1359 mTotalTouchDownTime, mTouchCycles);
1360 if (err == 0) {
1361 mPowerState |= SCREEN_ON_BIT;
1362 sendNotificationLocked(true, -1);
1363 }
1364 } else {
1365 mScreenOffTime = SystemClock.elapsedRealtime();
1366 long identity = Binder.clearCallingIdentity();
1367 try {
1368 mBatteryStats.noteScreenOff();
1369 } catch (RemoteException e) {
1370 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1371 } finally {
1372 Binder.restoreCallingIdentity(identity);
1373 }
1374 mPowerState &= ~SCREEN_ON_BIT;
1375 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001376 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 } else {
1378 mOffBecauseOfUser = becauseOfUser;
1379 err = 0;
1380 mLastTouchDown = 0;
1381 }
1382 }
1383 }
1384 }
1385 }
1386
Joe Onorato128e7292009-03-24 18:41:31 -07001387 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 // I don't think we need to check the current state here because all of these
1389 // Power.setScreenState and sendNotificationLocked can both handle being
1390 // called multiple times in the same state. -joeo
1391 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1392 mTotalTouchDownTime, mTouchCycles);
1393 mLastTouchDown = 0;
1394 int err = Power.setScreenState(false);
1395 if (mScreenOnStartTime != 0) {
1396 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1397 mScreenOnStartTime = 0;
1398 }
1399 if (err == 0) {
1400 int why = becauseOfUser
1401 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1402 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1403 sendNotificationLocked(false, why);
1404 }
1405 return err;
1406 }
1407
1408 private boolean batteryIsLow() {
1409 return (!mIsPowered &&
1410 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1411 }
1412
The Android Open Source Project10592532009-03-18 17:39:46 -07001413 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001414 final int oldState = mPowerState;
1415 final int realDifference = (newState ^ oldState);
1416 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001418 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 }
1420
1421 int offMask = 0;
1422 int dimMask = 0;
1423 int onMask = 0;
1424
1425 int preferredBrightness = getPreferredBrightness();
1426 boolean startAnimation = false;
1427
1428 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1429 if (ANIMATE_KEYBOARD_LIGHTS) {
1430 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1431 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001432 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1433 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 } else {
1435 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001436 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1437 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439 startAnimation = true;
1440 } else {
1441 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001442 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001444 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 }
1446 }
1447 }
1448
1449 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1450 if (ANIMATE_BUTTON_LIGHTS) {
1451 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1452 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001453 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1454 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 } else {
1456 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001457 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1458 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 }
1460 startAnimation = true;
1461 } else {
1462 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001463 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001465 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 }
1467 }
1468 }
1469
1470 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1471 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001472 int nominalCurrentValue = -1;
1473 // If there was an actual difference in the light state, then
1474 // figure out the "ideal" current value based on the previous
1475 // state. Otherwise, this is a change due to the brightness
1476 // override, so we want to animate from whatever the current
1477 // value is.
1478 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1479 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1480 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1481 nominalCurrentValue = preferredBrightness;
1482 break;
1483 case SCREEN_ON_BIT:
1484 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1485 break;
1486 case 0:
1487 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1488 break;
1489 case SCREEN_BRIGHT_BIT:
1490 default:
1491 // not possible
1492 nominalCurrentValue = (int)mScreenBrightness.curValue;
1493 break;
1494 }
Joe Onorato128e7292009-03-24 18:41:31 -07001495 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001496 int brightness = preferredBrightness;
1497 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1499 // dim or turn off backlight, depending on if the screen is on
1500 // the scale is because the brightness ramp isn't linear and this biases
1501 // it so the later parts take longer.
1502 final float scale = 1.5f;
1503 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1504 if (ratio > 1.0f) ratio = 1.0f;
1505 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1507 // was bright
1508 steps = ANIM_STEPS;
1509 } else {
1510 // was dim
1511 steps = (int)(ANIM_STEPS*ratio*scale);
1512 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001513 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 if ((oldState & SCREEN_ON_BIT) != 0) {
1516 // was bright
1517 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1518 } else {
1519 // was dim
1520 steps = (int)(ANIM_STEPS*ratio);
1521 }
1522 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1523 // If the "stay on while plugged in" option is
1524 // turned on, then the screen will often not
1525 // automatically turn off while plugged in. To
1526 // still have a sense of when it is inactive, we
1527 // will then count going dim as turning off.
1528 mScreenOffTime = SystemClock.elapsedRealtime();
1529 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001530 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001533 long identity = Binder.clearCallingIdentity();
1534 try {
1535 mBatteryStats.noteScreenBrightness(brightness);
1536 } catch (RemoteException e) {
1537 // Nothing interesting to do.
1538 } finally {
1539 Binder.restoreCallingIdentity(identity);
1540 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001541 if (mScreenBrightness.setTargetLocked(brightness,
1542 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1543 startAnimation = true;
1544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 } else {
1546 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1547 // dim or turn off backlight, depending on if the screen is on
1548 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001549 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001551 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 }
1553 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001554 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 }
1556 }
1557 }
1558
1559 if (startAnimation) {
1560 if (mSpew) {
1561 Log.i(TAG, "Scheduling light animator!");
1562 }
1563 mHandler.removeCallbacks(mLightAnimator);
1564 mHandler.post(mLightAnimator);
1565 }
1566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 if (offMask != 0) {
1568 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001569 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 }
1571 if (dimMask != 0) {
1572 int brightness = Power.BRIGHTNESS_DIM;
1573 if ((newState & BATTERY_LOW_BIT) != 0 &&
1574 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1575 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1576 }
1577 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001578 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 }
1580 if (onMask != 0) {
1581 int brightness = getPreferredBrightness();
1582 if ((newState & BATTERY_LOW_BIT) != 0 &&
1583 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1584 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1585 }
1586 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001587 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590
The Android Open Source Project10592532009-03-18 17:39:46 -07001591 private void setLightBrightness(int mask, int value) {
1592 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1593 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1594 }
1595 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1596 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1597 }
1598 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1599 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 }
1602
1603 class BrightnessState {
1604 final int mask;
1605
1606 boolean initialized;
1607 int targetValue;
1608 float curValue;
1609 float delta;
1610 boolean animating;
1611
1612 BrightnessState(int m) {
1613 mask = m;
1614 }
1615
1616 public void dump(PrintWriter pw, String prefix) {
1617 pw.println(prefix + "animating=" + animating
1618 + " targetValue=" + targetValue
1619 + " curValue=" + curValue
1620 + " delta=" + delta);
1621 }
1622
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001623 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001624 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 if (!initialized) {
1626 initialized = true;
1627 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001628 } else if (targetValue == target) {
1629 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 }
1631 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001632 delta = (targetValue -
1633 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1634 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001636 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001638 + " target=" + targetValue + " delta=" + delta
1639 + " nominalCurrentValue=" + nominalCurrentValue
1640 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 }
1642 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001643 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645
1646 boolean stepLocked() {
1647 if (!animating) return false;
1648 if (false && mSpew) {
1649 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1650 + " target=" + targetValue + " delta=" + delta);
1651 }
1652 curValue += delta;
1653 int curIntValue = (int)curValue;
1654 boolean more = true;
1655 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001656 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 more = false;
1658 } else if (delta > 0) {
1659 if (curIntValue >= targetValue) {
1660 curValue = curIntValue = targetValue;
1661 more = false;
1662 }
1663 } else {
1664 if (curIntValue <= targetValue) {
1665 curValue = curIntValue = targetValue;
1666 more = false;
1667 }
1668 }
1669 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001670 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 animating = more;
1672 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001673 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001674 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 }
1676 }
1677 return more;
1678 }
1679 }
1680
1681 private class LightAnimator implements Runnable {
1682 public void run() {
1683 synchronized (mLocks) {
1684 long now = SystemClock.uptimeMillis();
1685 boolean more = mScreenBrightness.stepLocked();
1686 if (mKeyboardBrightness.stepLocked()) {
1687 more = true;
1688 }
1689 if (mButtonBrightness.stepLocked()) {
1690 more = true;
1691 }
1692 if (more) {
1693 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1694 }
1695 }
1696 }
1697 }
1698
1699 private int getPreferredBrightness() {
1700 try {
1701 if (mScreenBrightnessOverride >= 0) {
1702 return mScreenBrightnessOverride;
1703 }
1704 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1705 SCREEN_BRIGHTNESS);
1706 // Don't let applications turn the screen all the way off
1707 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1708 } catch (SettingNotFoundException snfe) {
1709 return Power.BRIGHTNESS_ON;
1710 }
1711 }
1712
1713 boolean screenIsOn() {
1714 synchronized (mLocks) {
1715 return (mPowerState & SCREEN_ON_BIT) != 0;
1716 }
1717 }
1718
1719 boolean screenIsBright() {
1720 synchronized (mLocks) {
1721 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1722 }
1723 }
1724
Mike Lockwood200b30b2009-09-20 00:23:59 -04001725 private void forceUserActivityLocked() {
1726 boolean savedActivityAllowed = mUserActivityAllowed;
1727 mUserActivityAllowed = true;
1728 userActivity(SystemClock.uptimeMillis(), false);
1729 mUserActivityAllowed = savedActivityAllowed;
1730 }
1731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1733 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1734 userActivity(time, noChangeLights, OTHER_EVENT, force);
1735 }
1736
1737 public void userActivity(long time, boolean noChangeLights) {
1738 userActivity(time, noChangeLights, OTHER_EVENT, false);
1739 }
1740
1741 public void userActivity(long time, boolean noChangeLights, int eventType) {
1742 userActivity(time, noChangeLights, eventType, false);
1743 }
1744
1745 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1746 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1747
1748 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001749 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001751 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
1753 return;
1754 }
1755
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001756 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1757 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1758 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1759 if (false) {
1760 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1761 }
1762 return;
1763 }
1764
1765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 if (false) {
1767 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1768 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1769 } else {
1770 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1771 }
1772 }
1773
1774 synchronized (mLocks) {
1775 if (mSpew) {
1776 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1777 + " mUserActivityAllowed=" + mUserActivityAllowed
1778 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001779 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1780 + " mProximitySensorActive=" + mProximitySensorActive
1781 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 }
1783 if (mLastEventTime <= time || force) {
1784 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001785 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 // Only turn on button backlights if a button was pressed.
1787 if (eventType == BUTTON_EVENT) {
1788 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1789 } else {
1790 // don't clear button/keyboard backlights when the screen is touched.
1791 mUserState |= SCREEN_BRIGHT;
1792 }
1793
Dianne Hackborn617f8772009-03-31 15:04:46 -07001794 int uid = Binder.getCallingUid();
1795 long ident = Binder.clearCallingIdentity();
1796 try {
1797 mBatteryStats.noteUserActivity(uid, eventType);
1798 } catch (RemoteException e) {
1799 // Ignore
1800 } finally {
1801 Binder.restoreCallingIdentity(ident);
1802 }
1803
Michael Chane96440f2009-05-06 10:27:36 -07001804 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1806 setTimeoutLocked(time, SCREEN_BRIGHT);
1807 }
1808 }
1809 }
1810 }
1811
1812 /**
1813 * The user requested that we go to sleep (probably with the power button).
1814 * This overrides all wake locks that are held.
1815 */
1816 public void goToSleep(long time)
1817 {
1818 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1819 synchronized (mLocks) {
1820 goToSleepLocked(time);
1821 }
1822 }
1823
1824 /**
1825 * Returns the time the screen has been on since boot, in millis.
1826 * @return screen on time
1827 */
1828 public long getScreenOnTime() {
1829 synchronized (mLocks) {
1830 if (mScreenOnStartTime == 0) {
1831 return mScreenOnTime;
1832 } else {
1833 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1834 }
1835 }
1836 }
1837
1838 private void goToSleepLocked(long time) {
1839
1840 if (mLastEventTime <= time) {
1841 mLastEventTime = time;
1842 // cancel all of the wake locks
1843 mWakeLockState = SCREEN_OFF;
1844 int N = mLocks.size();
1845 int numCleared = 0;
1846 for (int i=0; i<N; i++) {
1847 WakeLock wl = mLocks.get(i);
1848 if (isScreenLock(wl.flags)) {
1849 mLocks.get(i).activated = false;
1850 numCleared++;
1851 }
1852 }
1853 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07001854 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 mUserState = SCREEN_OFF;
1856 setPowerState(SCREEN_OFF, false, true);
1857 cancelTimerLocked();
1858 }
1859 }
1860
1861 public long timeSinceScreenOn() {
1862 synchronized (mLocks) {
1863 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1864 return 0;
1865 }
1866 return SystemClock.elapsedRealtime() - mScreenOffTime;
1867 }
1868 }
1869
1870 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07001871 synchronized (mLocks) {
1872 if (mSpew) {
1873 Log.d(TAG, "setKeyboardVisibility: " + visible);
1874 }
1875 mKeyboardVisible = visible;
Dianne Hackbornfe2bddf2009-09-20 15:21:10 -07001876 // don't signal user activity if the screen is off; other code
1877 // will take care of turning on due to a true change to the lid
1878 // switch and synchronized with the lock screen.
1879 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwooda625b382009-09-12 17:36:03 -07001880 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
1881 }
1882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 }
1884
1885 /**
1886 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
1887 */
1888 public void enableUserActivity(boolean enabled) {
1889 synchronized (mLocks) {
1890 mUserActivityAllowed = enabled;
1891 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
1892 }
1893 }
1894
Mike Lockwooddc3494e2009-10-14 21:17:09 -07001895 private void setScreenBrightnessMode(int mode) {
1896 mAutoBrightessEnabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
1897
1898 if (mHasHardwareAutoBrightness) {
1899 // When setting auto-brightness, must reset the brightness afterwards
1900 mHardware.setAutoBrightness_UNCHECKED(mAutoBrightessEnabled);
1901 setBacklightBrightness((int)mScreenBrightness.curValue);
1902 } else {
1903 // not yet implemented
1904 }
1905 }
1906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 /** Sets the screen off timeouts:
1908 * mKeylightDelay
1909 * mDimDelay
1910 * mScreenOffDelay
1911 * */
1912 private void setScreenOffTimeoutsLocked() {
1913 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
1914 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
1915 mDimDelay = -1;
1916 mScreenOffDelay = 0;
1917 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
1918 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
1919 mDimDelay = -1;
1920 mScreenOffDelay = 0;
1921 } else {
1922 int totalDelay = mTotalDelaySetting;
1923 mKeylightDelay = LONG_KEYLIGHT_DELAY;
1924 if (totalDelay < 0) {
1925 mScreenOffDelay = Integer.MAX_VALUE;
1926 } else if (mKeylightDelay < totalDelay) {
1927 // subtract the time that the keylight delay. This will give us the
1928 // remainder of the time that we need to sleep to get the accurate
1929 // screen off timeout.
1930 mScreenOffDelay = totalDelay - mKeylightDelay;
1931 } else {
1932 mScreenOffDelay = 0;
1933 }
1934 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
1935 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
1936 mScreenOffDelay = LONG_DIM_TIME;
1937 } else {
1938 mDimDelay = -1;
1939 }
1940 }
1941 if (mSpew) {
1942 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
1943 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
1944 + " mDimScreen=" + mDimScreen);
1945 }
1946 }
1947
1948 /**
1949 * Refreshes cached Gservices settings. Called once on startup, and
1950 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
1951 * GservicesChangedReceiver).
1952 */
1953 private void updateGservicesValues() {
1954 mShortKeylightDelay = Settings.Gservices.getInt(
1955 mContext.getContentResolver(),
1956 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
1957 SHORT_KEYLIGHT_DELAY_DEFAULT);
1958 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
1959 }
1960
1961 /**
1962 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
1963 * which tells us we need to refresh our cached Gservices settings.
1964 */
1965 private class GservicesChangedReceiver extends BroadcastReceiver {
1966 @Override
1967 public void onReceive(Context context, Intent intent) {
1968 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
1969 updateGservicesValues();
1970 }
1971 }
1972
1973 private class LockList extends ArrayList<WakeLock>
1974 {
1975 void addLock(WakeLock wl)
1976 {
1977 int index = getIndex(wl.binder);
1978 if (index < 0) {
1979 this.add(wl);
1980 }
1981 }
1982
1983 WakeLock removeLock(IBinder binder)
1984 {
1985 int index = getIndex(binder);
1986 if (index >= 0) {
1987 return this.remove(index);
1988 } else {
1989 return null;
1990 }
1991 }
1992
1993 int getIndex(IBinder binder)
1994 {
1995 int N = this.size();
1996 for (int i=0; i<N; i++) {
1997 if (this.get(i).binder == binder) {
1998 return i;
1999 }
2000 }
2001 return -1;
2002 }
2003
2004 int gatherState()
2005 {
2006 int result = 0;
2007 int N = this.size();
2008 for (int i=0; i<N; i++) {
2009 WakeLock wl = this.get(i);
2010 if (wl.activated) {
2011 if (isScreenLock(wl.flags)) {
2012 result |= wl.minState;
2013 }
2014 }
2015 }
2016 return result;
2017 }
Michael Chane96440f2009-05-06 10:27:36 -07002018
2019 int reactivateScreenLocksLocked()
2020 {
2021 int result = 0;
2022 int N = this.size();
2023 for (int i=0; i<N; i++) {
2024 WakeLock wl = this.get(i);
2025 if (isScreenLock(wl.flags)) {
2026 wl.activated = true;
2027 result |= wl.minState;
2028 }
2029 }
2030 return result;
2031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033
2034 void setPolicy(WindowManagerPolicy p) {
2035 synchronized (mLocks) {
2036 mPolicy = p;
2037 mLocks.notifyAll();
2038 }
2039 }
2040
2041 WindowManagerPolicy getPolicyLocked() {
2042 while (mPolicy == null || !mDoneBooting) {
2043 try {
2044 mLocks.wait();
2045 } catch (InterruptedException e) {
2046 // Ignore
2047 }
2048 }
2049 return mPolicy;
2050 }
2051
2052 void systemReady() {
2053 synchronized (mLocks) {
2054 Log.d(TAG, "system ready!");
2055 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002056 long identity = Binder.clearCallingIdentity();
2057 try {
2058 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2059 mBatteryStats.noteScreenOn();
2060 } catch (RemoteException e) {
2061 // Nothing interesting to do.
2062 } finally {
2063 Binder.restoreCallingIdentity(identity);
2064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2066 updateWakeLockLocked();
2067 mLocks.notifyAll();
2068 }
2069 }
2070
2071 public void monitor() {
2072 synchronized (mLocks) { }
2073 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002074
2075 public int getSupportedWakeLockFlags() {
2076 int result = PowerManager.PARTIAL_WAKE_LOCK
2077 | PowerManager.FULL_WAKE_LOCK
2078 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2079
2080 // call getSensorManager() to make sure mProximitySensor is initialized
2081 getSensorManager();
2082 if (mProximitySensor != null) {
2083 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2084 }
2085
2086 return result;
2087 }
2088
Mike Lockwood237a2992009-09-15 14:42:16 -04002089 public void setBacklightBrightness(int brightness) {
2090 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2091 // Don't let applications turn the screen all the way off
2092 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2093 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness);
2094 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, brightness);
2095 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness);
2096 long identity = Binder.clearCallingIdentity();
2097 try {
2098 mBatteryStats.noteScreenBrightness(brightness);
2099 } catch (RemoteException e) {
2100 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2101 } finally {
2102 Binder.restoreCallingIdentity(identity);
2103 }
2104
2105 // update our animation state
2106 if (ANIMATE_SCREEN_LIGHTS) {
2107 mScreenBrightness.curValue = brightness;
2108 mScreenBrightness.animating = false;
2109 }
2110 if (ANIMATE_KEYBOARD_LIGHTS) {
2111 mKeyboardBrightness.curValue = brightness;
2112 mKeyboardBrightness.animating = false;
2113 }
2114 if (ANIMATE_BUTTON_LIGHTS) {
2115 mButtonBrightness.curValue = brightness;
2116 mButtonBrightness.animating = false;
2117 }
2118 }
2119
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002120 private SensorManager getSensorManager() {
2121 if (mSensorManager == null) {
2122 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2123 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2124 }
2125 return mSensorManager;
2126 }
2127
2128 private void enableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002129 if (mSpew) {
2130 Log.d(TAG, "enableProximityLockLocked");
2131 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002132 mSensorManager.registerListener(this, mProximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
2133 }
2134
2135 private void disableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002136 if (mSpew) {
2137 Log.d(TAG, "disableProximityLockLocked");
2138 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002139 mSensorManager.unregisterListener(this);
Mike Lockwood200b30b2009-09-20 00:23:59 -04002140 synchronized (mLocks) {
2141 if (mProximitySensorActive) {
2142 mProximitySensorActive = false;
2143 forceUserActivityLocked();
2144 }
2145 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002146 }
2147
2148 public void onSensorChanged(SensorEvent event) {
2149 long milliseconds = event.timestamp / 1000000;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002150 synchronized (mLocks) {
Mike Lockwoodd20ea362009-09-15 00:13:38 -04002151 float distance = event.values[0];
Mike Lockwood94db9282009-09-21 22:29:25 -04002152 // compare against getMaximumRange to support sensors that only return 0 or 1
2153 if (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2154 distance < mProximitySensor.getMaximumRange()) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002155 if (mSpew) {
Mike Lockwoodd20ea362009-09-15 00:13:38 -04002156 Log.d(TAG, "onSensorChanged: proximity active, distance: " + distance);
Mike Lockwood36fc3022009-08-25 16:49:06 -07002157 }
2158 goToSleepLocked(milliseconds);
2159 mProximitySensorActive = true;
2160 } else {
Mike Lockwoodd20ea362009-09-15 00:13:38 -04002161 // proximity sensor negative events trigger as user activity.
Mike Lockwood36fc3022009-08-25 16:49:06 -07002162 // temporarily set mUserActivityAllowed to true so this will work
2163 // even when the keyguard is on.
2164 if (mSpew) {
Mike Lockwoodd20ea362009-09-15 00:13:38 -04002165 Log.d(TAG, "onSensorChanged: proximity inactive, distance: " + distance);
Mike Lockwood36fc3022009-08-25 16:49:06 -07002166 }
2167 mProximitySensorActive = false;
Mike Lockwood200b30b2009-09-20 00:23:59 -04002168 forceUserActivityLocked();
Mike Lockwood06952d92009-08-13 16:05:38 -04002169 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002170 }
2171 }
2172
2173 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2174 // ignore
2175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176}