blob: 1249289ca27df0a38c02944e43061cecbb1778c6 [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;
55import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
56import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
57
58import java.io.FileDescriptor;
59import java.io.PrintWriter;
60import java.util.ArrayList;
61import java.util.HashMap;
62import java.util.Observable;
63import java.util.Observer;
64
Mike Lockwoodbc706a02009-07-27 13:50:57 -070065class PowerManagerService extends IPowerManager.Stub
66 implements LocalPowerManager,Watchdog.Monitor, SensorEventListener {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067
68 private static final String TAG = "PowerManagerService";
69 static final String PARTIAL_NAME = "PowerManagerService";
70
71 private static final boolean LOG_PARTIAL_WL = false;
72
73 // Indicates whether touch-down cycles should be logged as part of the
74 // LOG_POWER_SCREEN_STATE log events
75 private static final boolean LOG_TOUCH_DOWNS = true;
76
77 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
78 | PowerManager.SCREEN_DIM_WAKE_LOCK
79 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070080 | PowerManager.FULL_WAKE_LOCK
81 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
83 // time since last state: time since last event:
84 // The short keylight delay comes from Gservices; this is the default.
85 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
86 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
87 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
88 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
89
90 // Cached Gservices settings; see updateGservicesValues()
91 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
92
93 // flags for setPowerState
94 private static final int SCREEN_ON_BIT = 0x00000001;
95 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
96 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
97 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
98 private static final int BATTERY_LOW_BIT = 0x00000010;
99
100 // values for setPowerState
101
102 // SCREEN_OFF == everything off
103 private static final int SCREEN_OFF = 0x00000000;
104
105 // SCREEN_DIM == screen on, screen backlight dim
106 private static final int SCREEN_DIM = SCREEN_ON_BIT;
107
108 // SCREEN_BRIGHT == screen on, screen backlight bright
109 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
110
111 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
112 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
113
114 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
115 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
116
117 // used for noChangeLights in setPowerState()
118 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
119
120 static final boolean ANIMATE_SCREEN_LIGHTS = true;
121 static final boolean ANIMATE_BUTTON_LIGHTS = false;
122 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
123
124 static final int ANIM_STEPS = 60/4;
125
126 // These magic numbers are the initial state of the LEDs at boot. Ideally
127 // we should read them from the driver, but our current hardware returns 0
128 // for the initial value. Oops!
129 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
130 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
131 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
132
133 static final int LOG_POWER_SLEEP_REQUESTED = 2724;
134 static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
135 static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
136 static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
137 static final int LOG_POWER_SCREEN_STATE = 2728;
138 static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
139
140 private final int MY_UID;
141
142 private boolean mDoneBooting = false;
143 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700144 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
145 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146 private int mPartialCount = 0;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700147 private int mProximityCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 private int mPowerState;
149 private boolean mOffBecauseOfUser;
150 private int mUserState;
151 private boolean mKeyboardVisible = false;
152 private boolean mUserActivityAllowed = true;
153 private int mTotalDelaySetting;
154 private int mKeylightDelay;
155 private int mDimDelay;
156 private int mScreenOffDelay;
157 private int mWakeLockState;
158 private long mLastEventTime = 0;
159 private long mScreenOffTime;
160 private volatile WindowManagerPolicy mPolicy;
161 private final LockList mLocks = new LockList();
162 private Intent mScreenOffIntent;
163 private Intent mScreenOnIntent;
The Android Open Source Project10592532009-03-18 17:39:46 -0700164 private HardwareService mHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 private Context mContext;
166 private UnsynchronizedWakeLock mBroadcastWakeLock;
167 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
168 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
169 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
170 private HandlerThread mHandlerThread;
171 private Handler mHandler;
172 private TimeoutTask mTimeoutTask = new TimeoutTask();
173 private LightAnimator mLightAnimator = new LightAnimator();
174 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700175 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700177 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700179 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700180 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 private boolean mIsPowered = false;
182 private IActivityManager mActivityService;
183 private IBatteryStats mBatteryStats;
184 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700185 private SensorManager mSensorManager;
186 private Sensor mProximitySensor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 private boolean mDimScreen = true;
188 private long mNextTimeout;
189 private volatile int mPokey = 0;
190 private volatile boolean mPokeAwakeOnSet = false;
191 private volatile boolean mInitComplete = false;
192 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
193 private long mScreenOnTime;
194 private long mScreenOnStartTime;
195 private boolean mPreventScreenOn;
196 private int mScreenBrightnessOverride = -1;
197
198 // Used when logging number and duration of touch-down cycles
199 private long mTotalTouchDownTime;
200 private long mLastTouchDown;
201 private int mTouchCycles;
202
203 // could be either static or controllable at runtime
204 private static final boolean mSpew = false;
205
206 /*
207 static PrintStream mLog;
208 static {
209 try {
210 mLog = new PrintStream("/data/power.log");
211 }
212 catch (FileNotFoundException e) {
213 android.util.Log.e(TAG, "Life is hard", e);
214 }
215 }
216 static class Log {
217 static void d(String tag, String s) {
218 mLog.println(s);
219 android.util.Log.d(tag, s);
220 }
221 static void i(String tag, String s) {
222 mLog.println(s);
223 android.util.Log.i(tag, s);
224 }
225 static void w(String tag, String s) {
226 mLog.println(s);
227 android.util.Log.w(tag, s);
228 }
229 static void e(String tag, String s) {
230 mLog.println(s);
231 android.util.Log.e(tag, s);
232 }
233 }
234 */
235
236 /**
237 * This class works around a deadlock between the lock in PowerManager.WakeLock
238 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
239 * mToken object so it can be accessed from any thread, but it calls into here
240 * with its lock held. This class is essentially a reimplementation of
241 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
242 * only call it with our own locks held.
243 */
244 private class UnsynchronizedWakeLock {
245 int mFlags;
246 String mTag;
247 IBinder mToken;
248 int mCount = 0;
249 boolean mRefCounted;
250
251 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
252 mFlags = flags;
253 mTag = tag;
254 mToken = new Binder();
255 mRefCounted = refCounted;
256 }
257
258 public void acquire() {
259 if (!mRefCounted || mCount++ == 0) {
260 long ident = Binder.clearCallingIdentity();
261 try {
262 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
263 MY_UID, mTag);
264 } finally {
265 Binder.restoreCallingIdentity(ident);
266 }
267 }
268 }
269
270 public void release() {
271 if (!mRefCounted || --mCount == 0) {
272 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
273 }
274 if (mCount < 0) {
275 throw new RuntimeException("WakeLock under-locked " + mTag);
276 }
277 }
278
279 public String toString() {
280 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
281 + " mCount=" + mCount + ")";
282 }
283 }
284
285 private final class BatteryReceiver extends BroadcastReceiver {
286 @Override
287 public void onReceive(Context context, Intent intent) {
288 synchronized (mLocks) {
289 boolean wasPowered = mIsPowered;
290 mIsPowered = mBatteryService.isPowered();
291
292 if (mIsPowered != wasPowered) {
293 // update mStayOnWhilePluggedIn wake lock
294 updateWakeLockLocked();
295
296 // treat plugging and unplugging the devices as a user activity.
297 // users find it disconcerting when they unplug the device
298 // and it shuts off right away.
299 // temporarily set mUserActivityAllowed to true so this will work
300 // even when the keyguard is on.
301 synchronized (mLocks) {
302 boolean savedActivityAllowed = mUserActivityAllowed;
303 mUserActivityAllowed = true;
304 userActivity(SystemClock.uptimeMillis(), false);
305 mUserActivityAllowed = savedActivityAllowed;
306 }
307 }
308 }
309 }
310 }
311
312 /**
313 * Set the setting that determines whether the device stays on when plugged in.
314 * The argument is a bit string, with each bit specifying a power source that,
315 * when the device is connected to that source, causes the device to stay on.
316 * See {@link android.os.BatteryManager} for the list of power sources that
317 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
318 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
319 * @param val an {@code int} containing the bits that specify which power sources
320 * should cause the device to stay on.
321 */
322 public void setStayOnSetting(int val) {
323 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
324 Settings.System.putInt(mContext.getContentResolver(),
325 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
326 }
327
328 private class SettingsObserver implements Observer {
329 private int getInt(String name) {
330 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
331 }
332
333 public void update(Observable o, Object arg) {
334 synchronized (mLocks) {
335 // STAY_ON_WHILE_PLUGGED_IN
336 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
337 updateWakeLockLocked();
338
339 // SCREEN_OFF_TIMEOUT
340 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
341
342 // DIM_SCREEN
343 //mDimScreen = getInt(DIM_SCREEN) != 0;
344
345 // recalculate everything
346 setScreenOffTimeoutsLocked();
347 }
348 }
349 }
350
351 PowerManagerService()
352 {
353 // Hack to get our uid... should have a func for this.
354 long token = Binder.clearCallingIdentity();
355 MY_UID = Binder.getCallingUid();
356 Binder.restoreCallingIdentity(token);
357
358 // XXX remove this when the kernel doesn't timeout wake locks
359 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
360
361 // assume nothing is on yet
362 mUserState = mPowerState = 0;
363
364 // Add ourself to the Watchdog monitors.
365 Watchdog.getInstance().addMonitor(this);
366 mScreenOnStartTime = SystemClock.elapsedRealtime();
367 }
368
369 private ContentQueryMap mSettings;
370
The Android Open Source Project10592532009-03-18 17:39:46 -0700371 void init(Context context, HardwareService hardware, IActivityManager activity,
372 BatteryService battery) {
373 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 mContext = context;
375 mActivityService = activity;
376 mBatteryStats = BatteryStatsService.getService();
377 mBatteryService = battery;
378
379 mHandlerThread = new HandlerThread("PowerManagerService") {
380 @Override
381 protected void onLooperPrepared() {
382 super.onLooperPrepared();
383 initInThread();
384 }
385 };
386 mHandlerThread.start();
387
388 synchronized (mHandlerThread) {
389 while (!mInitComplete) {
390 try {
391 mHandlerThread.wait();
392 } catch (InterruptedException e) {
393 // Ignore
394 }
395 }
396 }
397 }
398
399 void initInThread() {
400 mHandler = new Handler();
401
402 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700403 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
405 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
406 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
407 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
408 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
409 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
410
411 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
412 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
413 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
414 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
415
416 ContentResolver resolver = mContext.getContentResolver();
417 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
418 "(" + Settings.System.NAME + "=?) or ("
419 + Settings.System.NAME + "=?) or ("
420 + Settings.System.NAME + "=?)",
421 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN},
422 null);
423 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
424 SettingsObserver settingsObserver = new SettingsObserver();
425 mSettings.addObserver(settingsObserver);
426
427 // pretend that the settings changed so we will get their initial state
428 settingsObserver.update(mSettings, null);
429
430 // register for the battery changed notifications
431 IntentFilter filter = new IntentFilter();
432 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
433 mContext.registerReceiver(new BatteryReceiver(), filter);
434
435 // Listen for Gservices changes
436 IntentFilter gservicesChangedFilter =
437 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
438 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
439 // And explicitly do the initial update of our cached settings
440 updateGservicesValues();
441
442 // turn everything on
443 setPowerState(ALL_BRIGHT);
444
445 synchronized (mHandlerThread) {
446 mInitComplete = true;
447 mHandlerThread.notifyAll();
448 }
449 }
450
451 private class WakeLock implements IBinder.DeathRecipient
452 {
453 WakeLock(int f, IBinder b, String t, int u) {
454 super();
455 flags = f;
456 binder = b;
457 tag = t;
458 uid = u == MY_UID ? Process.SYSTEM_UID : u;
459 if (u != MY_UID || (
460 !"KEEP_SCREEN_ON_FLAG".equals(tag)
461 && !"KeyInputQueue".equals(tag))) {
462 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
463 ? BatteryStats.WAKE_TYPE_PARTIAL
464 : BatteryStats.WAKE_TYPE_FULL;
465 } else {
466 monitorType = -1;
467 }
468 try {
469 b.linkToDeath(this, 0);
470 } catch (RemoteException e) {
471 binderDied();
472 }
473 }
474 public void binderDied() {
475 synchronized (mLocks) {
476 releaseWakeLockLocked(this.binder, true);
477 }
478 }
479 final int flags;
480 final IBinder binder;
481 final String tag;
482 final int uid;
483 final int monitorType;
484 boolean activated = true;
485 int minState;
486 }
487
488 private void updateWakeLockLocked() {
489 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
490 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
491 mStayOnWhilePluggedInScreenDimLock.acquire();
492 mStayOnWhilePluggedInPartialLock.acquire();
493 } else {
494 mStayOnWhilePluggedInScreenDimLock.release();
495 mStayOnWhilePluggedInPartialLock.release();
496 }
497 }
498
499 private boolean isScreenLock(int flags)
500 {
501 int n = flags & LOCK_MASK;
502 return n == PowerManager.FULL_WAKE_LOCK
503 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
504 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
505 }
506
507 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700509 if (uid != Process.myUid()) {
510 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 long ident = Binder.clearCallingIdentity();
513 try {
514 synchronized (mLocks) {
515 acquireWakeLockLocked(flags, lock, uid, tag);
516 }
517 } finally {
518 Binder.restoreCallingIdentity(ident);
519 }
520 }
521
522 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
523 int acquireUid = -1;
524 String acquireName = null;
525 int acquireType = -1;
526
527 if (mSpew) {
528 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
529 }
530
531 int index = mLocks.getIndex(lock);
532 WakeLock wl;
533 boolean newlock;
534 if (index < 0) {
535 wl = new WakeLock(flags, lock, tag, uid);
536 switch (wl.flags & LOCK_MASK)
537 {
538 case PowerManager.FULL_WAKE_LOCK:
539 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
540 break;
541 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
542 wl.minState = SCREEN_BRIGHT;
543 break;
544 case PowerManager.SCREEN_DIM_WAKE_LOCK:
545 wl.minState = SCREEN_DIM;
546 break;
547 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700548 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 break;
550 default:
551 // just log and bail. we're in the server, so don't
552 // throw an exception.
553 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
554 + " flags=" + flags);
555 return;
556 }
557 mLocks.addLock(wl);
558 newlock = true;
559 } else {
560 wl = mLocks.get(index);
561 newlock = false;
562 }
563 if (isScreenLock(flags)) {
564 // if this causes a wakeup, we reactivate all of the locks and
565 // set it to whatever they want. otherwise, we modulate that
566 // by the current state so we never turn it more on than
567 // it already is.
568 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700569 int oldWakeLockState = mWakeLockState;
570 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 if (mSpew) {
572 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700573 + " mWakeLockState=0x"
574 + Integer.toHexString(mWakeLockState)
575 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 } else {
578 if (mSpew) {
579 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
580 + " mLocks.gatherState()=0x"
581 + Integer.toHexString(mLocks.gatherState())
582 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
583 }
584 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
585 }
586 setPowerState(mWakeLockState | mUserState);
587 }
588 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
589 if (newlock) {
590 mPartialCount++;
591 if (mPartialCount == 1) {
592 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
593 }
594 }
595 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700596 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
597 mProximityCount++;
598 if (mProximityCount == 1) {
599 enableProximityLockLocked();
600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 }
602 if (newlock) {
603 acquireUid = wl.uid;
604 acquireName = wl.tag;
605 acquireType = wl.monitorType;
606 }
607
608 if (acquireType >= 0) {
609 try {
610 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
611 } catch (RemoteException e) {
612 // Ignore
613 }
614 }
615 }
616
617 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700618 int uid = Binder.getCallingUid();
619 if (uid != Process.myUid()) {
620 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622
623 synchronized (mLocks) {
624 releaseWakeLockLocked(lock, false);
625 }
626 }
627
628 private void releaseWakeLockLocked(IBinder lock, boolean death) {
629 int releaseUid;
630 String releaseName;
631 int releaseType;
632
633 WakeLock wl = mLocks.removeLock(lock);
634 if (wl == null) {
635 return;
636 }
637
638 if (mSpew) {
639 Log.d(TAG, "releaseWakeLock flags=0x"
640 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
641 }
642
643 if (isScreenLock(wl.flags)) {
644 mWakeLockState = mLocks.gatherState();
645 // goes in the middle to reduce flicker
646 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
647 userActivity(SystemClock.uptimeMillis(), false);
648 }
649 setPowerState(mWakeLockState | mUserState);
650 }
651 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
652 mPartialCount--;
653 if (mPartialCount == 0) {
654 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
655 Power.releaseWakeLock(PARTIAL_NAME);
656 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700657 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
658 mProximityCount--;
659 if (mProximityCount == 0) {
660 disableProximityLockLocked();
661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 }
663 // Unlink the lock from the binder.
664 wl.binder.unlinkToDeath(wl, 0);
665 releaseUid = wl.uid;
666 releaseName = wl.tag;
667 releaseType = wl.monitorType;
668
669 if (releaseType >= 0) {
670 long origId = Binder.clearCallingIdentity();
671 try {
672 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
673 } catch (RemoteException e) {
674 // Ignore
675 } finally {
676 Binder.restoreCallingIdentity(origId);
677 }
678 }
679 }
680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 private class PokeLock implements IBinder.DeathRecipient
682 {
683 PokeLock(int p, IBinder b, String t) {
684 super();
685 this.pokey = p;
686 this.binder = b;
687 this.tag = t;
688 try {
689 b.linkToDeath(this, 0);
690 } catch (RemoteException e) {
691 binderDied();
692 }
693 }
694 public void binderDied() {
695 setPokeLock(0, this.binder, this.tag);
696 }
697 int pokey;
698 IBinder binder;
699 String tag;
700 boolean awakeOnSet;
701 }
702
703 public void setPokeLock(int pokey, IBinder token, String tag) {
704 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
705 if (token == null) {
706 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
707 return;
708 }
709
710 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
711 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
712 + " and POKE_LOCK_MEDIUM_TIMEOUT");
713 }
714
715 synchronized (mLocks) {
716 if (pokey != 0) {
717 PokeLock p = mPokeLocks.get(token);
718 int oldPokey = 0;
719 if (p != null) {
720 oldPokey = p.pokey;
721 p.pokey = pokey;
722 } else {
723 p = new PokeLock(pokey, token, tag);
724 mPokeLocks.put(token, p);
725 }
726 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
727 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
728 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
729 p.awakeOnSet = true;
730 }
731 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700732 PokeLock rLock = mPokeLocks.remove(token);
733 if (rLock != null) {
734 token.unlinkToDeath(rLock, 0);
735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 }
737
738 int oldPokey = mPokey;
739 int cumulative = 0;
740 boolean oldAwakeOnSet = mPokeAwakeOnSet;
741 boolean awakeOnSet = false;
742 for (PokeLock p: mPokeLocks.values()) {
743 cumulative |= p.pokey;
744 if (p.awakeOnSet) {
745 awakeOnSet = true;
746 }
747 }
748 mPokey = cumulative;
749 mPokeAwakeOnSet = awakeOnSet;
750
751 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
752 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
753
754 if (oldCumulativeTimeout != newCumulativeTimeout) {
755 setScreenOffTimeoutsLocked();
756 // reset the countdown timer, but use the existing nextState so it doesn't
757 // change anything
758 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
759 }
760 }
761 }
762
763 private static String lockType(int type)
764 {
765 switch (type)
766 {
767 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700768 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700770 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700772 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700774 return "PARTIAL_WAKE_LOCK ";
775 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
776 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 default:
David Brown251faa62009-08-02 22:04:36 -0700778 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 }
780 }
781
782 private static String dumpPowerState(int state) {
783 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
784 ? "KEYBOARD_BRIGHT_BIT " : "")
785 + (((state & SCREEN_BRIGHT_BIT) != 0)
786 ? "SCREEN_BRIGHT_BIT " : "")
787 + (((state & SCREEN_ON_BIT) != 0)
788 ? "SCREEN_ON_BIT " : "")
789 + (((state & BATTERY_LOW_BIT) != 0)
790 ? "BATTERY_LOW_BIT " : "");
791 }
792
793 @Override
794 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
795 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
796 != PackageManager.PERMISSION_GRANTED) {
797 pw.println("Permission Denial: can't dump PowerManager from from pid="
798 + Binder.getCallingPid()
799 + ", uid=" + Binder.getCallingUid());
800 return;
801 }
802
803 long now = SystemClock.uptimeMillis();
804
805 pw.println("Power Manager State:");
806 pw.println(" mIsPowered=" + mIsPowered
807 + " mPowerState=" + mPowerState
808 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
809 + " ms");
810 pw.println(" mPartialCount=" + mPartialCount);
811 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
812 pw.println(" mUserState=" + dumpPowerState(mUserState));
813 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
814 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
815 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
816 + " " + ((mNextTimeout-now)/1000) + "s from now");
817 pw.println(" mDimScreen=" + mDimScreen
818 + " mStayOnConditions=" + mStayOnConditions);
819 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
820 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700821 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
822 + ',' + mBroadcastQueue[2] + "}");
823 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
824 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
826 pw.println(" mKeyboardVisible=" + mKeyboardVisible
827 + " mUserActivityAllowed=" + mUserActivityAllowed);
828 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
829 + " mScreenOffDelay=" + mScreenOffDelay);
830 pw.println(" mPreventScreenOn=" + mPreventScreenOn
831 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
832 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
833 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
834 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
835 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
836 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
837 mScreenBrightness.dump(pw, " mScreenBrightness: ");
838 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
839 mButtonBrightness.dump(pw, " mButtonBrightness: ");
840
841 int N = mLocks.size();
842 pw.println();
843 pw.println("mLocks.size=" + N + ":");
844 for (int i=0; i<N; i++) {
845 WakeLock wl = mLocks.get(i);
846 String type = lockType(wl.flags & LOCK_MASK);
847 String acquireCausesWakeup = "";
848 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
849 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
850 }
851 String activated = "";
852 if (wl.activated) {
853 activated = " activated";
854 }
855 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
856 + activated + " (minState=" + wl.minState + ")");
857 }
858
859 pw.println();
860 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
861 for (PokeLock p: mPokeLocks.values()) {
862 pw.println(" poke lock '" + p.tag + "':"
863 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
864 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700865 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
866 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
868 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
869 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
870 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
871 }
872
873 pw.println();
874 }
875
876 private void setTimeoutLocked(long now, int nextState)
877 {
878 if (mDoneBooting) {
879 mHandler.removeCallbacks(mTimeoutTask);
880 mTimeoutTask.nextState = nextState;
881 long when = now;
882 switch (nextState)
883 {
884 case SCREEN_BRIGHT:
885 when += mKeylightDelay;
886 break;
887 case SCREEN_DIM:
888 if (mDimDelay >= 0) {
889 when += mDimDelay;
890 break;
891 } else {
892 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
893 }
894 case SCREEN_OFF:
895 synchronized (mLocks) {
896 when += mScreenOffDelay;
897 }
898 break;
899 }
900 if (mSpew) {
901 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
902 + " when=" + when);
903 }
904 mHandler.postAtTime(mTimeoutTask, when);
905 mNextTimeout = when; // for debugging
906 }
907 }
908
909 private void cancelTimerLocked()
910 {
911 mHandler.removeCallbacks(mTimeoutTask);
912 mTimeoutTask.nextState = -1;
913 }
914
915 private class TimeoutTask implements Runnable
916 {
917 int nextState; // access should be synchronized on mLocks
918 public void run()
919 {
920 synchronized (mLocks) {
921 if (mSpew) {
922 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
923 }
924
925 if (nextState == -1) {
926 return;
927 }
928
929 mUserState = this.nextState;
930 setPowerState(this.nextState | mWakeLockState);
931
932 long now = SystemClock.uptimeMillis();
933
934 switch (this.nextState)
935 {
936 case SCREEN_BRIGHT:
937 if (mDimDelay >= 0) {
938 setTimeoutLocked(now, SCREEN_DIM);
939 break;
940 }
941 case SCREEN_DIM:
942 setTimeoutLocked(now, SCREEN_OFF);
943 break;
944 }
945 }
946 }
947 }
948
949 private void sendNotificationLocked(boolean on, int why)
950 {
Joe Onorato64c62ba2009-03-24 20:13:57 -0700951 if (!on) {
952 mStillNeedSleepNotification = false;
953 }
954
Joe Onorato128e7292009-03-24 18:41:31 -0700955 // Add to the queue.
956 int index = 0;
957 while (mBroadcastQueue[index] != -1) {
958 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 }
Joe Onorato128e7292009-03-24 18:41:31 -0700960 mBroadcastQueue[index] = on ? 1 : 0;
961 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962
Joe Onorato128e7292009-03-24 18:41:31 -0700963 // If we added it position 2, then there is a pair that can be stripped.
964 // If we added it position 1 and we're turning the screen off, we can strip
965 // the pair and do nothing, because the screen is already off, and therefore
966 // keyguard has already been enabled.
967 // However, if we added it at position 1 and we're turning it on, then position
968 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
969 // on, so have to run the queue then.
970 if (index == 2) {
971 // Also, while we're collapsing them, if it's going to be an "off," and one
972 // is off because of user, then use that, regardless of whether it's the first
973 // or second one.
974 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
975 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
976 }
977 mBroadcastQueue[0] = on ? 1 : 0;
978 mBroadcastQueue[1] = -1;
979 mBroadcastQueue[2] = -1;
980 index = 0;
981 }
982 if (index == 1 && !on) {
983 mBroadcastQueue[0] = -1;
984 mBroadcastQueue[1] = -1;
985 index = -1;
986 // The wake lock was being held, but we're not actually going to do any
987 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
989 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -0700990 }
991
992 // Now send the message.
993 if (index >= 0) {
994 // Acquire the broadcast wake lock before changing the power
995 // state. It will be release after the broadcast is sent.
996 // We always increment the ref count for each notification in the queue
997 // and always decrement when that notification is handled.
998 mBroadcastWakeLock.acquire();
999 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1000 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 }
1002 }
1003
1004 private Runnable mNotificationTask = new Runnable()
1005 {
1006 public void run()
1007 {
Joe Onorato128e7292009-03-24 18:41:31 -07001008 while (true) {
1009 int value;
1010 int why;
1011 WindowManagerPolicy policy;
1012 synchronized (mLocks) {
1013 value = mBroadcastQueue[0];
1014 why = mBroadcastWhy[0];
1015 for (int i=0; i<2; i++) {
1016 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1017 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1018 }
1019 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
Joe Onorato128e7292009-03-24 18:41:31 -07001021 if (value == 1) {
1022 mScreenOnStart = SystemClock.uptimeMillis();
1023
1024 policy.screenTurnedOn();
1025 try {
1026 ActivityManagerNative.getDefault().wakingUp();
1027 } catch (RemoteException e) {
1028 // ignore it
1029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030
Joe Onorato128e7292009-03-24 18:41:31 -07001031 if (mSpew) {
1032 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1033 }
1034 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1035 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1036 mScreenOnBroadcastDone, mHandler, 0, null, null);
1037 } else {
1038 synchronized (mLocks) {
1039 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1040 mBroadcastWakeLock.mCount);
1041 mBroadcastWakeLock.release();
1042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 }
1044 }
Joe Onorato128e7292009-03-24 18:41:31 -07001045 else if (value == 0) {
1046 mScreenOffStart = SystemClock.uptimeMillis();
1047
1048 policy.screenTurnedOff(why);
1049 try {
1050 ActivityManagerNative.getDefault().goingToSleep();
1051 } catch (RemoteException e) {
1052 // ignore it.
1053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054
Joe Onorato128e7292009-03-24 18:41:31 -07001055 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1056 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1057 mScreenOffBroadcastDone, mHandler, 0, null, null);
1058 } else {
1059 synchronized (mLocks) {
1060 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1061 mBroadcastWakeLock.mCount);
1062 mBroadcastWakeLock.release();
1063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 }
1065 }
Joe Onorato128e7292009-03-24 18:41:31 -07001066 else {
1067 // If we're in this case, then this handler is running for a previous
1068 // paired transaction. mBroadcastWakeLock will already have been released.
1069 break;
1070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 }
1072 }
1073 };
1074
1075 long mScreenOnStart;
1076 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1077 public void onReceive(Context context, Intent intent) {
1078 synchronized (mLocks) {
1079 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1080 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1081 mBroadcastWakeLock.release();
1082 }
1083 }
1084 };
1085
1086 long mScreenOffStart;
1087 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1088 public void onReceive(Context context, Intent intent) {
1089 synchronized (mLocks) {
1090 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1091 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1092 mBroadcastWakeLock.release();
1093 }
1094 }
1095 };
1096
1097 void logPointerUpEvent() {
1098 if (LOG_TOUCH_DOWNS) {
1099 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1100 mLastTouchDown = 0;
1101 }
1102 }
1103
1104 void logPointerDownEvent() {
1105 if (LOG_TOUCH_DOWNS) {
1106 // If we are not already timing a down/up sequence
1107 if (mLastTouchDown == 0) {
1108 mLastTouchDown = SystemClock.elapsedRealtime();
1109 mTouchCycles++;
1110 }
1111 }
1112 }
1113
1114 /**
1115 * Prevents the screen from turning on even if it *should* turn on due
1116 * to a subsequent full wake lock being acquired.
1117 * <p>
1118 * This is a temporary hack that allows an activity to "cover up" any
1119 * display glitches that happen during the activity's startup
1120 * sequence. (Specifically, this API was added to work around a
1121 * cosmetic bug in the "incoming call" sequence, where the lock screen
1122 * would flicker briefly before the incoming call UI became visible.)
1123 * TODO: There ought to be a more elegant way of doing this,
1124 * probably by having the PowerManager and ActivityManager
1125 * work together to let apps specify that the screen on/off
1126 * state should be synchronized with the Activity lifecycle.
1127 * <p>
1128 * Note that calling preventScreenOn(true) will NOT turn the screen
1129 * off if it's currently on. (This API only affects *future*
1130 * acquisitions of full wake locks.)
1131 * But calling preventScreenOn(false) WILL turn the screen on if
1132 * it's currently off because of a prior preventScreenOn(true) call.
1133 * <p>
1134 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1135 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1136 * call doesn't occur within 5 seconds, we'll turn the screen back on
1137 * ourselves (and log a warning about it); this prevents a buggy app
1138 * from disabling the screen forever.)
1139 * <p>
1140 * TODO: this feature should really be controlled by a new type of poke
1141 * lock (rather than an IPowerManager call).
1142 */
1143 public void preventScreenOn(boolean prevent) {
1144 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1145
1146 synchronized (mLocks) {
1147 if (prevent) {
1148 // First of all, grab a partial wake lock to
1149 // make sure the CPU stays on during the entire
1150 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1151 mPreventScreenOnPartialLock.acquire();
1152
1153 // Post a forceReenableScreen() call (for 5 seconds in the
1154 // future) to make sure the matching preventScreenOn(false) call
1155 // has happened by then.
1156 mHandler.removeCallbacks(mForceReenableScreenTask);
1157 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1158
1159 // Finally, set the flag that prevents the screen from turning on.
1160 // (Below, in setPowerState(), we'll check mPreventScreenOn and
1161 // we *won't* call Power.setScreenState(true) if it's set.)
1162 mPreventScreenOn = true;
1163 } else {
1164 // (Re)enable the screen.
1165 mPreventScreenOn = false;
1166
1167 // We're "undoing" a the prior preventScreenOn(true) call, so we
1168 // no longer need the 5-second safeguard.
1169 mHandler.removeCallbacks(mForceReenableScreenTask);
1170
1171 // Forcibly turn on the screen if it's supposed to be on. (This
1172 // handles the case where the screen is currently off because of
1173 // a prior preventScreenOn(true) call.)
1174 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1175 if (mSpew) {
1176 Log.d(TAG,
1177 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1178 }
1179 int err = Power.setScreenState(true);
1180 if (err != 0) {
1181 Log.w(TAG, "preventScreenOn: error from Power.setScreenState(): " + err);
1182 }
1183 }
1184
1185 // Release the partial wake lock that we held during the
1186 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1187 mPreventScreenOnPartialLock.release();
1188 }
1189 }
1190 }
1191
1192 public void setScreenBrightnessOverride(int brightness) {
1193 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1194
1195 synchronized (mLocks) {
1196 if (mScreenBrightnessOverride != brightness) {
1197 mScreenBrightnessOverride = brightness;
1198 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1199 }
1200 }
1201 }
1202
1203 /**
1204 * Sanity-check that gets called 5 seconds after any call to
1205 * preventScreenOn(true). This ensures that the original call
1206 * is followed promptly by a call to preventScreenOn(false).
1207 */
1208 private void forceReenableScreen() {
1209 // We shouldn't get here at all if mPreventScreenOn is false, since
1210 // we should have already removed any existing
1211 // mForceReenableScreenTask messages...
1212 if (!mPreventScreenOn) {
1213 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1214 return;
1215 }
1216
1217 // Uh oh. It's been 5 seconds since a call to
1218 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1219 // This means the app that called preventScreenOn(true) is either
1220 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1221 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1222 // crashed before doing so.)
1223
1224 // Log a warning, and forcibly turn the screen back on.
1225 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1226 + "Forcing the screen back on...");
1227 preventScreenOn(false);
1228 }
1229
1230 private Runnable mForceReenableScreenTask = new Runnable() {
1231 public void run() {
1232 forceReenableScreen();
1233 }
1234 };
1235
1236 private void setPowerState(int state)
1237 {
1238 setPowerState(state, false, false);
1239 }
1240
1241 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1242 {
1243 synchronized (mLocks) {
1244 int err;
1245
1246 if (mSpew) {
1247 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1248 + " newState=0x" + Integer.toHexString(newState)
1249 + " noChangeLights=" + noChangeLights);
1250 }
1251
1252 if (noChangeLights) {
1253 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1254 }
1255
1256 if (batteryIsLow()) {
1257 newState |= BATTERY_LOW_BIT;
1258 } else {
1259 newState &= ~BATTERY_LOW_BIT;
1260 }
1261 if (newState == mPowerState) {
1262 return;
1263 }
1264
1265 if (!mDoneBooting) {
1266 newState |= ALL_BRIGHT;
1267 }
1268
1269 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1270 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1271
1272 if (mSpew) {
1273 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1274 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1275 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1276 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1277 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1278 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1279 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1280 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1281 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1282 + " newScreenOn=" + newScreenOn);
1283 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1284 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1285 }
1286
1287 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001288 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1290 }
1291
1292 if (oldScreenOn != newScreenOn) {
1293 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001294 // When the user presses the power button, we need to always send out the
1295 // notification that it's going to sleep so the keyguard goes on. But
1296 // we can't do that until the screen fades out, so we don't show the keyguard
1297 // too early.
1298 if (mStillNeedSleepNotification) {
1299 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1300 }
1301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 // Turn on the screen UNLESS there was a prior
1303 // preventScreenOn(true) request. (Note that the lifetime
1304 // of a single preventScreenOn() request is limited to 5
1305 // seconds to prevent a buggy app from disabling the
1306 // screen forever; see forceReenableScreen().)
1307 boolean reallyTurnScreenOn = true;
1308 if (mSpew) {
1309 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1310 + mPreventScreenOn);
1311 }
1312
1313 if (mPreventScreenOn) {
1314 if (mSpew) {
1315 Log.d(TAG, "- PREVENTING screen from really turning on!");
1316 }
1317 reallyTurnScreenOn = false;
1318 }
1319 if (reallyTurnScreenOn) {
1320 err = Power.setScreenState(true);
1321 long identity = Binder.clearCallingIdentity();
1322 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001323 mBatteryStats.noteScreenBrightness(
1324 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 mBatteryStats.noteScreenOn();
1326 } catch (RemoteException e) {
1327 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1328 } finally {
1329 Binder.restoreCallingIdentity(identity);
1330 }
1331 } else {
1332 Power.setScreenState(false);
1333 // But continue as if we really did turn the screen on...
1334 err = 0;
1335 }
1336
1337 mScreenOnStartTime = SystemClock.elapsedRealtime();
1338 mLastTouchDown = 0;
1339 mTotalTouchDownTime = 0;
1340 mTouchCycles = 0;
1341 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1342 mTotalTouchDownTime, mTouchCycles);
1343 if (err == 0) {
1344 mPowerState |= SCREEN_ON_BIT;
1345 sendNotificationLocked(true, -1);
1346 }
1347 } else {
1348 mScreenOffTime = SystemClock.elapsedRealtime();
1349 long identity = Binder.clearCallingIdentity();
1350 try {
1351 mBatteryStats.noteScreenOff();
1352 } catch (RemoteException e) {
1353 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1354 } finally {
1355 Binder.restoreCallingIdentity(identity);
1356 }
1357 mPowerState &= ~SCREEN_ON_BIT;
1358 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001359 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 } else {
1361 mOffBecauseOfUser = becauseOfUser;
1362 err = 0;
1363 mLastTouchDown = 0;
1364 }
1365 }
1366 }
1367 }
1368 }
1369
Joe Onorato128e7292009-03-24 18:41:31 -07001370 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 // I don't think we need to check the current state here because all of these
1372 // Power.setScreenState and sendNotificationLocked can both handle being
1373 // called multiple times in the same state. -joeo
1374 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1375 mTotalTouchDownTime, mTouchCycles);
1376 mLastTouchDown = 0;
1377 int err = Power.setScreenState(false);
1378 if (mScreenOnStartTime != 0) {
1379 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1380 mScreenOnStartTime = 0;
1381 }
1382 if (err == 0) {
1383 int why = becauseOfUser
1384 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1385 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1386 sendNotificationLocked(false, why);
1387 }
1388 return err;
1389 }
1390
1391 private boolean batteryIsLow() {
1392 return (!mIsPowered &&
1393 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1394 }
1395
The Android Open Source Project10592532009-03-18 17:39:46 -07001396 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001397 final int oldState = mPowerState;
1398 final int realDifference = (newState ^ oldState);
1399 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001401 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 }
1403
1404 int offMask = 0;
1405 int dimMask = 0;
1406 int onMask = 0;
1407
1408 int preferredBrightness = getPreferredBrightness();
1409 boolean startAnimation = false;
1410
1411 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1412 if (ANIMATE_KEYBOARD_LIGHTS) {
1413 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1414 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001415 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1416 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 } else {
1418 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001419 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1420 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 }
1422 startAnimation = true;
1423 } else {
1424 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001425 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001427 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429 }
1430 }
1431
1432 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1433 if (ANIMATE_BUTTON_LIGHTS) {
1434 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1435 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001436 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1437 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 } else {
1439 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001440 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1441 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 }
1443 startAnimation = true;
1444 } else {
1445 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001446 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001448 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 }
1450 }
1451 }
1452
1453 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1454 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001455 int nominalCurrentValue = -1;
1456 // If there was an actual difference in the light state, then
1457 // figure out the "ideal" current value based on the previous
1458 // state. Otherwise, this is a change due to the brightness
1459 // override, so we want to animate from whatever the current
1460 // value is.
1461 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1462 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1463 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1464 nominalCurrentValue = preferredBrightness;
1465 break;
1466 case SCREEN_ON_BIT:
1467 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1468 break;
1469 case 0:
1470 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1471 break;
1472 case SCREEN_BRIGHT_BIT:
1473 default:
1474 // not possible
1475 nominalCurrentValue = (int)mScreenBrightness.curValue;
1476 break;
1477 }
Joe Onorato128e7292009-03-24 18:41:31 -07001478 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001479 int brightness = preferredBrightness;
1480 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1482 // dim or turn off backlight, depending on if the screen is on
1483 // the scale is because the brightness ramp isn't linear and this biases
1484 // it so the later parts take longer.
1485 final float scale = 1.5f;
1486 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1487 if (ratio > 1.0f) ratio = 1.0f;
1488 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1490 // was bright
1491 steps = ANIM_STEPS;
1492 } else {
1493 // was dim
1494 steps = (int)(ANIM_STEPS*ratio*scale);
1495 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001496 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 if ((oldState & SCREEN_ON_BIT) != 0) {
1499 // was bright
1500 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1501 } else {
1502 // was dim
1503 steps = (int)(ANIM_STEPS*ratio);
1504 }
1505 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1506 // If the "stay on while plugged in" option is
1507 // turned on, then the screen will often not
1508 // automatically turn off while plugged in. To
1509 // still have a sense of when it is inactive, we
1510 // will then count going dim as turning off.
1511 mScreenOffTime = SystemClock.elapsedRealtime();
1512 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001513 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001516 long identity = Binder.clearCallingIdentity();
1517 try {
1518 mBatteryStats.noteScreenBrightness(brightness);
1519 } catch (RemoteException e) {
1520 // Nothing interesting to do.
1521 } finally {
1522 Binder.restoreCallingIdentity(identity);
1523 }
1524 mScreenBrightness.setTargetLocked(brightness,
1525 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 startAnimation = true;
1527 } else {
1528 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1529 // dim or turn off backlight, depending on if the screen is on
1530 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001531 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001533 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 }
1535 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001536 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 }
1538 }
1539 }
1540
1541 if (startAnimation) {
1542 if (mSpew) {
1543 Log.i(TAG, "Scheduling light animator!");
1544 }
1545 mHandler.removeCallbacks(mLightAnimator);
1546 mHandler.post(mLightAnimator);
1547 }
1548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 if (offMask != 0) {
1550 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001551 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 }
1553 if (dimMask != 0) {
1554 int brightness = Power.BRIGHTNESS_DIM;
1555 if ((newState & BATTERY_LOW_BIT) != 0 &&
1556 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1557 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1558 }
1559 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001560 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 }
1562 if (onMask != 0) {
1563 int brightness = getPreferredBrightness();
1564 if ((newState & BATTERY_LOW_BIT) != 0 &&
1565 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1566 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1567 }
1568 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001569 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572
The Android Open Source Project10592532009-03-18 17:39:46 -07001573 private void setLightBrightness(int mask, int value) {
1574 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1575 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1576 }
1577 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1578 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1579 }
1580 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1581 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 }
1584
1585 class BrightnessState {
1586 final int mask;
1587
1588 boolean initialized;
1589 int targetValue;
1590 float curValue;
1591 float delta;
1592 boolean animating;
1593
1594 BrightnessState(int m) {
1595 mask = m;
1596 }
1597
1598 public void dump(PrintWriter pw, String prefix) {
1599 pw.println(prefix + "animating=" + animating
1600 + " targetValue=" + targetValue
1601 + " curValue=" + curValue
1602 + " delta=" + delta);
1603 }
1604
Joe Onorato128e7292009-03-24 18:41:31 -07001605 void setTargetLocked(int target, int stepsToTarget, int initialValue,
1606 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 if (!initialized) {
1608 initialized = true;
1609 curValue = (float)initialValue;
1610 }
1611 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001612 delta = (targetValue -
1613 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1614 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001616 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001618 + " target=" + targetValue + " delta=" + delta
1619 + " nominalCurrentValue=" + nominalCurrentValue
1620 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 }
1622 animating = true;
1623 }
1624
1625 boolean stepLocked() {
1626 if (!animating) return false;
1627 if (false && mSpew) {
1628 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1629 + " target=" + targetValue + " delta=" + delta);
1630 }
1631 curValue += delta;
1632 int curIntValue = (int)curValue;
1633 boolean more = true;
1634 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001635 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 more = false;
1637 } else if (delta > 0) {
1638 if (curIntValue >= targetValue) {
1639 curValue = curIntValue = targetValue;
1640 more = false;
1641 }
1642 } else {
1643 if (curIntValue <= targetValue) {
1644 curValue = curIntValue = targetValue;
1645 more = false;
1646 }
1647 }
1648 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001649 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 animating = more;
1651 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001652 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001653 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 }
1655 }
1656 return more;
1657 }
1658 }
1659
1660 private class LightAnimator implements Runnable {
1661 public void run() {
1662 synchronized (mLocks) {
1663 long now = SystemClock.uptimeMillis();
1664 boolean more = mScreenBrightness.stepLocked();
1665 if (mKeyboardBrightness.stepLocked()) {
1666 more = true;
1667 }
1668 if (mButtonBrightness.stepLocked()) {
1669 more = true;
1670 }
1671 if (more) {
1672 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1673 }
1674 }
1675 }
1676 }
1677
1678 private int getPreferredBrightness() {
1679 try {
1680 if (mScreenBrightnessOverride >= 0) {
1681 return mScreenBrightnessOverride;
1682 }
1683 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1684 SCREEN_BRIGHTNESS);
1685 // Don't let applications turn the screen all the way off
1686 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1687 } catch (SettingNotFoundException snfe) {
1688 return Power.BRIGHTNESS_ON;
1689 }
1690 }
1691
1692 boolean screenIsOn() {
1693 synchronized (mLocks) {
1694 return (mPowerState & SCREEN_ON_BIT) != 0;
1695 }
1696 }
1697
1698 boolean screenIsBright() {
1699 synchronized (mLocks) {
1700 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1701 }
1702 }
1703
1704 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1705 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1706 userActivity(time, noChangeLights, OTHER_EVENT, force);
1707 }
1708
1709 public void userActivity(long time, boolean noChangeLights) {
1710 userActivity(time, noChangeLights, OTHER_EVENT, false);
1711 }
1712
1713 public void userActivity(long time, boolean noChangeLights, int eventType) {
1714 userActivity(time, noChangeLights, eventType, false);
1715 }
1716
1717 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1718 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1719
1720 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001721 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001723 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 }
1725 return;
1726 }
1727
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001728 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1729 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1730 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1731 if (false) {
1732 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1733 }
1734 return;
1735 }
1736
1737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 if (false) {
1739 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1740 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1741 } else {
1742 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1743 }
1744 }
1745
1746 synchronized (mLocks) {
1747 if (mSpew) {
1748 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1749 + " mUserActivityAllowed=" + mUserActivityAllowed
1750 + " mUserState=0x" + Integer.toHexString(mUserState)
1751 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
1752 }
1753 if (mLastEventTime <= time || force) {
1754 mLastEventTime = time;
1755 if (mUserActivityAllowed || force) {
1756 // Only turn on button backlights if a button was pressed.
1757 if (eventType == BUTTON_EVENT) {
1758 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1759 } else {
1760 // don't clear button/keyboard backlights when the screen is touched.
1761 mUserState |= SCREEN_BRIGHT;
1762 }
1763
Dianne Hackborn617f8772009-03-31 15:04:46 -07001764 int uid = Binder.getCallingUid();
1765 long ident = Binder.clearCallingIdentity();
1766 try {
1767 mBatteryStats.noteUserActivity(uid, eventType);
1768 } catch (RemoteException e) {
1769 // Ignore
1770 } finally {
1771 Binder.restoreCallingIdentity(ident);
1772 }
1773
Michael Chane96440f2009-05-06 10:27:36 -07001774 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1776 setTimeoutLocked(time, SCREEN_BRIGHT);
1777 }
1778 }
1779 }
1780 }
1781
1782 /**
1783 * The user requested that we go to sleep (probably with the power button).
1784 * This overrides all wake locks that are held.
1785 */
1786 public void goToSleep(long time)
1787 {
1788 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1789 synchronized (mLocks) {
1790 goToSleepLocked(time);
1791 }
1792 }
1793
1794 /**
1795 * Returns the time the screen has been on since boot, in millis.
1796 * @return screen on time
1797 */
1798 public long getScreenOnTime() {
1799 synchronized (mLocks) {
1800 if (mScreenOnStartTime == 0) {
1801 return mScreenOnTime;
1802 } else {
1803 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1804 }
1805 }
1806 }
1807
1808 private void goToSleepLocked(long time) {
1809
1810 if (mLastEventTime <= time) {
1811 mLastEventTime = time;
1812 // cancel all of the wake locks
1813 mWakeLockState = SCREEN_OFF;
1814 int N = mLocks.size();
1815 int numCleared = 0;
1816 for (int i=0; i<N; i++) {
1817 WakeLock wl = mLocks.get(i);
1818 if (isScreenLock(wl.flags)) {
1819 mLocks.get(i).activated = false;
1820 numCleared++;
1821 }
1822 }
1823 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07001824 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 mUserState = SCREEN_OFF;
1826 setPowerState(SCREEN_OFF, false, true);
1827 cancelTimerLocked();
1828 }
1829 }
1830
1831 public long timeSinceScreenOn() {
1832 synchronized (mLocks) {
1833 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1834 return 0;
1835 }
1836 return SystemClock.elapsedRealtime() - mScreenOffTime;
1837 }
1838 }
1839
1840 public void setKeyboardVisibility(boolean visible) {
1841 mKeyboardVisible = visible;
1842 }
1843
1844 /**
1845 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
1846 */
1847 public void enableUserActivity(boolean enabled) {
1848 synchronized (mLocks) {
1849 mUserActivityAllowed = enabled;
1850 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
1851 }
1852 }
1853
1854 /** Sets the screen off timeouts:
1855 * mKeylightDelay
1856 * mDimDelay
1857 * mScreenOffDelay
1858 * */
1859 private void setScreenOffTimeoutsLocked() {
1860 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
1861 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
1862 mDimDelay = -1;
1863 mScreenOffDelay = 0;
1864 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
1865 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
1866 mDimDelay = -1;
1867 mScreenOffDelay = 0;
1868 } else {
1869 int totalDelay = mTotalDelaySetting;
1870 mKeylightDelay = LONG_KEYLIGHT_DELAY;
1871 if (totalDelay < 0) {
1872 mScreenOffDelay = Integer.MAX_VALUE;
1873 } else if (mKeylightDelay < totalDelay) {
1874 // subtract the time that the keylight delay. This will give us the
1875 // remainder of the time that we need to sleep to get the accurate
1876 // screen off timeout.
1877 mScreenOffDelay = totalDelay - mKeylightDelay;
1878 } else {
1879 mScreenOffDelay = 0;
1880 }
1881 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
1882 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
1883 mScreenOffDelay = LONG_DIM_TIME;
1884 } else {
1885 mDimDelay = -1;
1886 }
1887 }
1888 if (mSpew) {
1889 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
1890 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
1891 + " mDimScreen=" + mDimScreen);
1892 }
1893 }
1894
1895 /**
1896 * Refreshes cached Gservices settings. Called once on startup, and
1897 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
1898 * GservicesChangedReceiver).
1899 */
1900 private void updateGservicesValues() {
1901 mShortKeylightDelay = Settings.Gservices.getInt(
1902 mContext.getContentResolver(),
1903 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
1904 SHORT_KEYLIGHT_DELAY_DEFAULT);
1905 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
1906 }
1907
1908 /**
1909 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
1910 * which tells us we need to refresh our cached Gservices settings.
1911 */
1912 private class GservicesChangedReceiver extends BroadcastReceiver {
1913 @Override
1914 public void onReceive(Context context, Intent intent) {
1915 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
1916 updateGservicesValues();
1917 }
1918 }
1919
1920 private class LockList extends ArrayList<WakeLock>
1921 {
1922 void addLock(WakeLock wl)
1923 {
1924 int index = getIndex(wl.binder);
1925 if (index < 0) {
1926 this.add(wl);
1927 }
1928 }
1929
1930 WakeLock removeLock(IBinder binder)
1931 {
1932 int index = getIndex(binder);
1933 if (index >= 0) {
1934 return this.remove(index);
1935 } else {
1936 return null;
1937 }
1938 }
1939
1940 int getIndex(IBinder binder)
1941 {
1942 int N = this.size();
1943 for (int i=0; i<N; i++) {
1944 if (this.get(i).binder == binder) {
1945 return i;
1946 }
1947 }
1948 return -1;
1949 }
1950
1951 int gatherState()
1952 {
1953 int result = 0;
1954 int N = this.size();
1955 for (int i=0; i<N; i++) {
1956 WakeLock wl = this.get(i);
1957 if (wl.activated) {
1958 if (isScreenLock(wl.flags)) {
1959 result |= wl.minState;
1960 }
1961 }
1962 }
1963 return result;
1964 }
Michael Chane96440f2009-05-06 10:27:36 -07001965
1966 int reactivateScreenLocksLocked()
1967 {
1968 int result = 0;
1969 int N = this.size();
1970 for (int i=0; i<N; i++) {
1971 WakeLock wl = this.get(i);
1972 if (isScreenLock(wl.flags)) {
1973 wl.activated = true;
1974 result |= wl.minState;
1975 }
1976 }
1977 return result;
1978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 }
1980
1981 void setPolicy(WindowManagerPolicy p) {
1982 synchronized (mLocks) {
1983 mPolicy = p;
1984 mLocks.notifyAll();
1985 }
1986 }
1987
1988 WindowManagerPolicy getPolicyLocked() {
1989 while (mPolicy == null || !mDoneBooting) {
1990 try {
1991 mLocks.wait();
1992 } catch (InterruptedException e) {
1993 // Ignore
1994 }
1995 }
1996 return mPolicy;
1997 }
1998
1999 void systemReady() {
2000 synchronized (mLocks) {
2001 Log.d(TAG, "system ready!");
2002 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002003 long identity = Binder.clearCallingIdentity();
2004 try {
2005 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2006 mBatteryStats.noteScreenOn();
2007 } catch (RemoteException e) {
2008 // Nothing interesting to do.
2009 } finally {
2010 Binder.restoreCallingIdentity(identity);
2011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2013 updateWakeLockLocked();
2014 mLocks.notifyAll();
2015 }
2016 }
2017
2018 public void monitor() {
2019 synchronized (mLocks) { }
2020 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002021
2022 public int getSupportedWakeLockFlags() {
2023 int result = PowerManager.PARTIAL_WAKE_LOCK
2024 | PowerManager.FULL_WAKE_LOCK
2025 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2026
2027 // call getSensorManager() to make sure mProximitySensor is initialized
2028 getSensorManager();
2029 if (mProximitySensor != null) {
2030 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2031 }
2032
2033 return result;
2034 }
2035
2036 private SensorManager getSensorManager() {
2037 if (mSensorManager == null) {
2038 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2039 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2040 }
2041 return mSensorManager;
2042 }
2043
2044 private void enableProximityLockLocked() {
2045 mSensorManager.registerListener(this, mProximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
2046 }
2047
2048 private void disableProximityLockLocked() {
2049 mSensorManager.unregisterListener(this);
2050 }
2051
2052 public void onSensorChanged(SensorEvent event) {
2053 long milliseconds = event.timestamp / 1000000;
2054 if (event.values[0] == 0.0) {
2055 goToSleep(milliseconds);
2056 } else {
Mike Lockwood06952d92009-08-13 16:05:38 -04002057 // proximity sensor negative events user activity.
2058 // temporarily set mUserActivityAllowed to true so this will work
2059 // even when the keyguard is on.
2060 synchronized (mLocks) {
2061 boolean savedActivityAllowed = mUserActivityAllowed;
2062 mUserActivityAllowed = true;
2063 userActivity(milliseconds, false);
2064 mUserActivityAllowed = savedActivityAllowed;
2065 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002066 }
2067 }
2068
2069 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2070 // ignore
2071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072}