blob: 6974b5ef5792e19de2bfa0150b118f572d89de88 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
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;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080020import com.android.server.am.BatteryStatsService;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070021
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;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080032import android.os.BatteryStats;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070033import android.os.Binder;
34import android.os.Handler;
35import android.os.HandlerThread;
36import android.os.IBinder;
37import android.os.IPowerManager;
38import android.os.LocalPowerManager;
39import android.os.Power;
40import android.os.PowerManager;
41import android.os.Process;
42import android.os.RemoteException;
43import android.os.SystemClock;
44import android.provider.Settings.SettingNotFoundException;
45import android.provider.Settings;
46import android.util.EventLog;
47import android.util.Log;
48import android.view.WindowManagerPolicy;
49import static android.provider.Settings.System.DIM_SCREEN;
50import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
51import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
52import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
53
54import java.io.FileDescriptor;
55import java.io.PrintWriter;
56import java.util.ArrayList;
57import java.util.HashMap;
58import java.util.Observable;
59import java.util.Observer;
60
61class PowerManagerService extends IPowerManager.Stub implements LocalPowerManager, Watchdog.Monitor {
62
63 private static final String TAG = "PowerManagerService";
64 static final String PARTIAL_NAME = "PowerManagerService";
65
66 private static final boolean LOG_PARTIAL_WL = false;
67
68 // Indicates whether touch-down cycles should be logged as part of the
69 // LOG_POWER_SCREEN_STATE log events
70 private static final boolean LOG_TOUCH_DOWNS = true;
71
72 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
73 | PowerManager.SCREEN_DIM_WAKE_LOCK
74 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
75 | PowerManager.FULL_WAKE_LOCK;
76
77 // time since last state: time since last event:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080078 // The short keylight delay comes from Gservices; this is the default.
79 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070080 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
81 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
82 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
83
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080084 // Cached Gservices settings; see updateGservicesValues()
85 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
86
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070087 // flags for setPowerState
88 private static final int SCREEN_ON_BIT = 0x00000001;
89 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
90 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
91 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
92 private static final int BATTERY_LOW_BIT = 0x00000010;
93
94 // values for setPowerState
95
96 // SCREEN_OFF == everything off
97 private static final int SCREEN_OFF = 0x00000000;
98
99 // SCREEN_DIM == screen on, screen backlight dim
100 private static final int SCREEN_DIM = SCREEN_ON_BIT;
101
102 // SCREEN_BRIGHT == screen on, screen backlight bright
103 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
104
105 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
106 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
107
108 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
109 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
110
111 // used for noChangeLights in setPowerState()
112 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
113
114 static final boolean ANIMATE_SCREEN_LIGHTS = true;
115 static final boolean ANIMATE_BUTTON_LIGHTS = false;
116 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
117
118 static final int ANIM_STEPS = 60/4;
119
120 // These magic numbers are the initial state of the LEDs at boot. Ideally
121 // we should read them from the driver, but our current hardware returns 0
122 // for the initial value. Oops!
123 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
124 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
125 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
126
127 static final int LOG_POWER_SLEEP_REQUESTED = 2724;
128 static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
129 static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
130 static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
131 static final int LOG_POWER_SCREEN_STATE = 2728;
132 static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
133
134 private final int MY_UID;
135
136 private boolean mDoneBooting = false;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800137 private int mStayOnConditions = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700138 private int mNotificationQueue = -1;
139 private int mNotificationWhy;
140 private int mPartialCount = 0;
141 private int mPowerState;
142 private boolean mOffBecauseOfUser;
143 private int mUserState;
144 private boolean mKeyboardVisible = false;
145 private boolean mUserActivityAllowed = true;
146 private int mTotalDelaySetting;
147 private int mKeylightDelay;
148 private int mDimDelay;
149 private int mScreenOffDelay;
150 private int mWakeLockState;
151 private long mLastEventTime = 0;
152 private long mScreenOffTime;
153 private volatile WindowManagerPolicy mPolicy;
154 private final LockList mLocks = new LockList();
155 private Intent mScreenOffIntent;
156 private Intent mScreenOnIntent;
157 private Context mContext;
158 private UnsynchronizedWakeLock mBroadcastWakeLock;
159 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
160 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800161 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700162 private HandlerThread mHandlerThread;
163 private Handler mHandler;
164 private TimeoutTask mTimeoutTask = new TimeoutTask();
165 private LightAnimator mLightAnimator = new LightAnimator();
166 private final BrightnessState mScreenBrightness
167 = new BrightnessState(Power.SCREEN_LIGHT);
168 private final BrightnessState mKeyboardBrightness
169 = new BrightnessState(Power.KEYBOARD_LIGHT);
170 private final BrightnessState mButtonBrightness
171 = new BrightnessState(Power.BUTTON_LIGHT);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700172 private boolean mIsPowered = false;
173 private IActivityManager mActivityService;
174 private IBatteryStats mBatteryStats;
175 private BatteryService mBatteryService;
176 private boolean mDimScreen = true;
177 private long mNextTimeout;
178 private volatile int mPokey = 0;
179 private volatile boolean mPokeAwakeOnSet = false;
180 private volatile boolean mInitComplete = false;
181 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
182 private long mScreenOnTime;
183 private long mScreenOnStartTime;
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800184 private boolean mPreventScreenOn;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700185
186 // Used when logging number and duration of touch-down cycles
187 private long mTotalTouchDownTime;
188 private long mLastTouchDown;
189 private int mTouchCycles;
190
191 // could be either static or controllable at runtime
192 private static final boolean mSpew = false;
193
194 /*
195 static PrintStream mLog;
196 static {
197 try {
198 mLog = new PrintStream("/data/power.log");
199 }
200 catch (FileNotFoundException e) {
201 android.util.Log.e(TAG, "Life is hard", e);
202 }
203 }
204 static class Log {
205 static void d(String tag, String s) {
206 mLog.println(s);
207 android.util.Log.d(tag, s);
208 }
209 static void i(String tag, String s) {
210 mLog.println(s);
211 android.util.Log.i(tag, s);
212 }
213 static void w(String tag, String s) {
214 mLog.println(s);
215 android.util.Log.w(tag, s);
216 }
217 static void e(String tag, String s) {
218 mLog.println(s);
219 android.util.Log.e(tag, s);
220 }
221 }
222 */
223
224 /**
225 * This class works around a deadlock between the lock in PowerManager.WakeLock
226 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
227 * mToken object so it can be accessed from any thread, but it calls into here
228 * with its lock held. This class is essentially a reimplementation of
229 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
230 * only call it with our own locks held.
231 */
232 private class UnsynchronizedWakeLock {
233 int mFlags;
234 String mTag;
235 IBinder mToken;
236 int mCount = 0;
237 boolean mRefCounted;
238
239 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
240 mFlags = flags;
241 mTag = tag;
242 mToken = new Binder();
243 mRefCounted = refCounted;
244 }
245
246 public void acquire() {
247 if (!mRefCounted || mCount++ == 0) {
248 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken, mTag);
249 }
250 }
251
252 public void release() {
253 if (!mRefCounted || --mCount == 0) {
254 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
255 }
256 if (mCount < 0) {
257 throw new RuntimeException("WakeLock under-locked " + mTag);
258 }
259 }
260
261 public String toString() {
262 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
263 + " mCount=" + mCount + ")";
264 }
265 }
266
267 private final class BatteryReceiver extends BroadcastReceiver {
268 @Override
269 public void onReceive(Context context, Intent intent) {
270 synchronized (mLocks) {
271 boolean wasPowered = mIsPowered;
272 mIsPowered = mBatteryService.isPowered();
273
274 if (mIsPowered != wasPowered) {
275 // update mStayOnWhilePluggedIn wake lock
276 updateWakeLockLocked();
277
278 // treat plugging and unplugging the devices as a user activity.
279 // users find it disconcerting when they unplug the device
280 // and it shuts off right away.
281 // temporarily set mUserActivityAllowed to true so this will work
282 // even when the keyguard is on.
283 synchronized (mLocks) {
284 boolean savedActivityAllowed = mUserActivityAllowed;
285 mUserActivityAllowed = true;
286 userActivity(SystemClock.uptimeMillis(), false);
287 mUserActivityAllowed = savedActivityAllowed;
288 }
289 }
290 }
291 }
292 }
293
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800294 /**
295 * Set the setting that determines whether the device stays on when plugged in.
296 * The argument is a bit string, with each bit specifying a power source that,
297 * when the device is connected to that source, causes the device to stay on.
298 * See {@link android.os.BatteryManager} for the list of power sources that
299 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
300 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
301 * @param val an {@code int} containing the bits that specify which power sources
302 * should cause the device to stay on.
303 */
304 public void setStayOnSetting(int val) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700305 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
306 Settings.System.putInt(mContext.getContentResolver(),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800307 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700308 }
309
310 private class SettingsObserver implements Observer {
311 private int getInt(String name) {
312 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
313 }
314
315 public void update(Observable o, Object arg) {
316 synchronized (mLocks) {
317 // STAY_ON_WHILE_PLUGGED_IN
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800318 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700319 updateWakeLockLocked();
320
321 // SCREEN_OFF_TIMEOUT
322 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
323
324 // DIM_SCREEN
325 //mDimScreen = getInt(DIM_SCREEN) != 0;
326
327 // recalculate everything
328 setScreenOffTimeoutsLocked();
329 }
330 }
331 }
332
333 PowerManagerService()
334 {
335 // Hack to get our uid... should have a func for this.
336 long token = Binder.clearCallingIdentity();
337 MY_UID = Binder.getCallingUid();
338 Binder.restoreCallingIdentity(token);
339
340 // XXX remove this when the kernel doesn't timeout wake locks
341 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
342
343 // assume nothing is on yet
344 mUserState = mPowerState = 0;
345
346 // Add ourself to the Watchdog monitors.
347 Watchdog.getInstance().addMonitor(this);
348 mScreenOnStartTime = SystemClock.elapsedRealtime();
349 }
350
351 private ContentQueryMap mSettings;
352
353 void init(Context context, IActivityManager activity, BatteryService battery) {
354 mContext = context;
355 mActivityService = activity;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800356 mBatteryStats = BatteryStatsService.getService();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700357 mBatteryService = battery;
358
359 mHandlerThread = new HandlerThread("PowerManagerService") {
360 @Override
361 protected void onLooperPrepared() {
362 super.onLooperPrepared();
363 initInThread();
364 }
365 };
366 mHandlerThread.start();
367
368 synchronized (mHandlerThread) {
369 while (!mInitComplete) {
370 try {
371 mHandlerThread.wait();
372 } catch (InterruptedException e) {
373 // Ignore
374 }
375 }
376 }
377 }
378
379 void initInThread() {
380 mHandler = new Handler();
381
382 mBroadcastWakeLock = new UnsynchronizedWakeLock(
383 PowerManager.PARTIAL_WAKE_LOCK, "sleep_notification", true);
384 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
385 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
386 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
387 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800388 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
389 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700390
391 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
392 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
393 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
394 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
395
396 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800397 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700398 "(" + Settings.System.NAME + "=?) or ("
399 + Settings.System.NAME + "=?) or ("
400 + Settings.System.NAME + "=?)",
401 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN},
402 null);
403 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
404 SettingsObserver settingsObserver = new SettingsObserver();
405 mSettings.addObserver(settingsObserver);
406
407 // pretend that the settings changed so we will get their initial state
408 settingsObserver.update(mSettings, null);
409
410 // register for the battery changed notifications
411 IntentFilter filter = new IntentFilter();
412 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
413 mContext.registerReceiver(new BatteryReceiver(), filter);
414
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800415 // Listen for Gservices changes
416 IntentFilter gservicesChangedFilter =
417 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
418 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
419 // And explicitly do the initial update of our cached settings
420 updateGservicesValues();
421
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700422 // turn everything on
423 setPowerState(ALL_BRIGHT);
424
425 synchronized (mHandlerThread) {
426 mInitComplete = true;
427 mHandlerThread.notifyAll();
428 }
429 }
430
431 private class WakeLock implements IBinder.DeathRecipient
432 {
433 WakeLock(int f, IBinder b, String t, int u) {
434 super();
435 flags = f;
436 binder = b;
437 tag = t;
438 uid = u == MY_UID ? Process.SYSTEM_UID : u;
439 if (u != MY_UID || (
440 !"KEEP_SCREEN_ON_FLAG".equals(tag)
441 && !"KeyInputQueue".equals(tag))) {
442 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
443 ? BatteryStats.WAKE_TYPE_PARTIAL
444 : BatteryStats.WAKE_TYPE_FULL;
445 } else {
446 monitorType = -1;
447 }
448 try {
449 b.linkToDeath(this, 0);
450 } catch (RemoteException e) {
451 binderDied();
452 }
453 }
454 public void binderDied() {
455 synchronized (mLocks) {
456 releaseWakeLockLocked(this.binder, true);
457 }
458 }
459 final int flags;
460 final IBinder binder;
461 final String tag;
462 final int uid;
463 final int monitorType;
464 boolean activated = true;
465 int minState;
466 }
467
468 private void updateWakeLockLocked() {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800469 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700470 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
471 mStayOnWhilePluggedInScreenDimLock.acquire();
472 mStayOnWhilePluggedInPartialLock.acquire();
473 } else {
474 mStayOnWhilePluggedInScreenDimLock.release();
475 mStayOnWhilePluggedInPartialLock.release();
476 }
477 }
478
479 private boolean isScreenLock(int flags)
480 {
481 int n = flags & LOCK_MASK;
482 return n == PowerManager.FULL_WAKE_LOCK
483 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
484 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
485 }
486
487 public void acquireWakeLock(int flags, IBinder lock, String tag) {
488 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
The Android Open Source Projectd24b8182009-02-10 15:44:00 -0800489 long ident = Binder.clearCallingIdentity();
490 try {
491 synchronized (mLocks) {
492 acquireWakeLockLocked(flags, lock, tag);
493 }
494 } finally {
495 Binder.restoreCallingIdentity(ident);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700496 }
497 }
498
499 public void acquireWakeLockLocked(int flags, IBinder lock, String tag) {
500 int acquireUid = -1;
501 String acquireName = null;
502 int acquireType = -1;
503
504 if (mSpew) {
505 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
506 }
507
508 int index = mLocks.getIndex(lock);
509 WakeLock wl;
510 boolean newlock;
511 if (index < 0) {
512 wl = new WakeLock(flags, lock, tag, Binder.getCallingUid());
513 switch (wl.flags & LOCK_MASK)
514 {
515 case PowerManager.FULL_WAKE_LOCK:
516 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
517 break;
518 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
519 wl.minState = SCREEN_BRIGHT;
520 break;
521 case PowerManager.SCREEN_DIM_WAKE_LOCK:
522 wl.minState = SCREEN_DIM;
523 break;
524 case PowerManager.PARTIAL_WAKE_LOCK:
525 break;
526 default:
527 // just log and bail. we're in the server, so don't
528 // throw an exception.
529 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
530 + " flags=" + flags);
531 return;
532 }
533 mLocks.addLock(wl);
534 newlock = true;
535 } else {
536 wl = mLocks.get(index);
537 newlock = false;
538 }
539 if (isScreenLock(flags)) {
540 // if this causes a wakeup, we reactivate all of the locks and
541 // set it to whatever they want. otherwise, we modulate that
542 // by the current state so we never turn it more on than
543 // it already is.
544 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
545 reactivateWakeLocksLocked();
546 if (mSpew) {
547 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
548 + " mLocks.gatherState()=0x"
549 + Integer.toHexString(mLocks.gatherState())
550 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
551 }
552 mWakeLockState = mLocks.gatherState();
553 } else {
554 if (mSpew) {
555 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
556 + " mLocks.gatherState()=0x"
557 + Integer.toHexString(mLocks.gatherState())
558 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
559 }
560 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
561 }
562 setPowerState(mWakeLockState | mUserState);
563 }
564 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
565 if (newlock) {
566 mPartialCount++;
567 if (mPartialCount == 1) {
568 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
569 }
570 }
571 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
572 }
573 if (newlock) {
574 acquireUid = wl.uid;
575 acquireName = wl.tag;
576 acquireType = wl.monitorType;
577 }
578
579 if (acquireType >= 0) {
The Android Open Source Projectd24b8182009-02-10 15:44:00 -0800580 long origId = Binder.clearCallingIdentity();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700581 try {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700582 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700583 } catch (RemoteException e) {
584 // Ignore
The Android Open Source Projectd24b8182009-02-10 15:44:00 -0800585 } finally {
586 Binder.restoreCallingIdentity(origId);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700587 }
588 }
589 }
590
591 public void releaseWakeLock(IBinder lock) {
592 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
593
594 synchronized (mLocks) {
595 releaseWakeLockLocked(lock, false);
596 }
597 }
598
599 private void releaseWakeLockLocked(IBinder lock, boolean death) {
600 int releaseUid;
601 String releaseName;
602 int releaseType;
603
604 WakeLock wl = mLocks.removeLock(lock);
605 if (wl == null) {
606 return;
607 }
608
609 if (mSpew) {
610 Log.d(TAG, "releaseWakeLock flags=0x"
611 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
612 }
613
614 if (isScreenLock(wl.flags)) {
615 mWakeLockState = mLocks.gatherState();
616 // goes in the middle to reduce flicker
617 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
618 userActivity(SystemClock.uptimeMillis(), false);
619 }
620 setPowerState(mWakeLockState | mUserState);
621 }
622 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
623 mPartialCount--;
624 if (mPartialCount == 0) {
625 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
626 Power.releaseWakeLock(PARTIAL_NAME);
627 }
628 }
629 // Unlink the lock from the binder.
630 wl.binder.unlinkToDeath(wl, 0);
631 releaseUid = wl.uid;
632 releaseName = wl.tag;
633 releaseType = wl.monitorType;
634
635 if (releaseType >= 0) {
The Android Open Source Projectd24b8182009-02-10 15:44:00 -0800636 long origId = Binder.clearCallingIdentity();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700637 try {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700638 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700639 } catch (RemoteException e) {
640 // Ignore
The Android Open Source Projectd24b8182009-02-10 15:44:00 -0800641 } finally {
642 Binder.restoreCallingIdentity(origId);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700643 }
644 }
645 }
646
647 private void reactivateWakeLocksLocked()
648 {
649 int N = mLocks.size();
650 for (int i=0; i<N; i++) {
651 WakeLock wl = mLocks.get(i);
652 if (isScreenLock(wl.flags)) {
653 mLocks.get(i).activated = true;
654 }
655 }
656 }
657
658 private class PokeLock implements IBinder.DeathRecipient
659 {
660 PokeLock(int p, IBinder b, String t) {
661 super();
662 this.pokey = p;
663 this.binder = b;
664 this.tag = t;
665 try {
666 b.linkToDeath(this, 0);
667 } catch (RemoteException e) {
668 binderDied();
669 }
670 }
671 public void binderDied() {
672 setPokeLock(0, this.binder, this.tag);
673 }
674 int pokey;
675 IBinder binder;
676 String tag;
677 boolean awakeOnSet;
678 }
679
680 public void setPokeLock(int pokey, IBinder token, String tag) {
681 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
682 if (token == null) {
683 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
684 return;
685 }
686
687 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
688 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
689 + " and POKE_LOCK_MEDIUM_TIMEOUT");
690 }
691
692 synchronized (mLocks) {
693 if (pokey != 0) {
694 PokeLock p = mPokeLocks.get(token);
695 int oldPokey = 0;
696 if (p != null) {
697 oldPokey = p.pokey;
698 p.pokey = pokey;
699 } else {
700 p = new PokeLock(pokey, token, tag);
701 mPokeLocks.put(token, p);
702 }
703 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
704 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
705 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
706 p.awakeOnSet = true;
707 }
708 } else {
709 mPokeLocks.remove(token);
710 }
711
712 int oldPokey = mPokey;
713 int cumulative = 0;
714 boolean oldAwakeOnSet = mPokeAwakeOnSet;
715 boolean awakeOnSet = false;
716 for (PokeLock p: mPokeLocks.values()) {
717 cumulative |= p.pokey;
718 if (p.awakeOnSet) {
719 awakeOnSet = true;
720 }
721 }
722 mPokey = cumulative;
723 mPokeAwakeOnSet = awakeOnSet;
724
725 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
726 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
727
728 if (oldCumulativeTimeout != newCumulativeTimeout) {
729 setScreenOffTimeoutsLocked();
730 // reset the countdown timer, but use the existing nextState so it doesn't
731 // change anything
732 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
733 }
734 }
735 }
736
737 private static String lockType(int type)
738 {
739 switch (type)
740 {
741 case PowerManager.FULL_WAKE_LOCK:
742 return "FULL_WAKE_LOCK ";
743 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
744 return "SCREEN_BRIGHT_WAKE_LOCK";
745 case PowerManager.SCREEN_DIM_WAKE_LOCK:
746 return "SCREEN_DIM_WAKE_LOCK ";
747 case PowerManager.PARTIAL_WAKE_LOCK:
748 return "PARTIAL_WAKE_LOCK ";
749 default:
750 return "??? ";
751 }
752 }
753
754 private static String dumpPowerState(int state) {
755 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
756 ? "KEYBOARD_BRIGHT_BIT " : "")
757 + (((state & SCREEN_BRIGHT_BIT) != 0)
758 ? "SCREEN_BRIGHT_BIT " : "")
759 + (((state & SCREEN_ON_BIT) != 0)
760 ? "SCREEN_ON_BIT " : "")
761 + (((state & BATTERY_LOW_BIT) != 0)
762 ? "BATTERY_LOW_BIT " : "");
763 }
764
765 @Override
766 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
The Android Open Source Projectd24b8182009-02-10 15:44:00 -0800767 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700768 != PackageManager.PERMISSION_GRANTED) {
769 pw.println("Permission Denial: can't dump PowerManager from from pid="
770 + Binder.getCallingPid()
771 + ", uid=" + Binder.getCallingUid());
772 return;
773 }
774
775 long now = SystemClock.uptimeMillis();
776
777 pw.println("Power Manager State:");
778 pw.println(" mIsPowered=" + mIsPowered
779 + " mPowerState=" + mPowerState
780 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
781 + " ms");
782 pw.println(" mPartialCount=" + mPartialCount);
783 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
784 pw.println(" mUserState=" + dumpPowerState(mUserState));
785 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
786 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
787 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
788 + " " + ((mNextTimeout-now)/1000) + "s from now");
789 pw.println(" mDimScreen=" + mDimScreen
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800790 + " mStayOnConditions=" + mStayOnConditions);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700791 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
792 + " mUserState=" + mUserState);
793 pw.println(" mNotificationQueue=" + mNotificationQueue
794 + " mNotificationWhy=" + mNotificationWhy);
795 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
796 pw.println(" mKeyboardVisible=" + mKeyboardVisible
797 + " mUserActivityAllowed=" + mUserActivityAllowed);
798 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
799 + " mScreenOffDelay=" + mScreenOffDelay);
800 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
801 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
802 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
803 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800804 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700805 mScreenBrightness.dump(pw, " mScreenBrightness: ");
806 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
807 mButtonBrightness.dump(pw, " mButtonBrightness: ");
808
809 int N = mLocks.size();
810 pw.println();
811 pw.println("mLocks.size=" + N + ":");
812 for (int i=0; i<N; i++) {
813 WakeLock wl = mLocks.get(i);
814 String type = lockType(wl.flags & LOCK_MASK);
815 String acquireCausesWakeup = "";
816 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
817 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
818 }
819 String activated = "";
820 if (wl.activated) {
821 activated = " activated";
822 }
823 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
824 + activated + " (minState=" + wl.minState + ")");
825 }
826
827 pw.println();
828 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
829 for (PokeLock p: mPokeLocks.values()) {
830 pw.println(" poke lock '" + p.tag + "':"
831 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
832 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
833 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
834 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
835 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
836 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
837 }
838
839 pw.println();
840 }
841
842 private void setTimeoutLocked(long now, int nextState)
843 {
844 if (mDoneBooting) {
845 mHandler.removeCallbacks(mTimeoutTask);
846 mTimeoutTask.nextState = nextState;
847 long when = now;
848 switch (nextState)
849 {
850 case SCREEN_BRIGHT:
851 when += mKeylightDelay;
852 break;
853 case SCREEN_DIM:
854 if (mDimDelay >= 0) {
855 when += mDimDelay;
856 break;
857 } else {
858 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
859 }
860 case SCREEN_OFF:
861 synchronized (mLocks) {
862 when += mScreenOffDelay;
863 }
864 break;
865 }
866 if (mSpew) {
867 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
868 + " when=" + when);
869 }
870 mHandler.postAtTime(mTimeoutTask, when);
871 mNextTimeout = when; // for debugging
872 }
873 }
874
875 private void cancelTimerLocked()
876 {
877 mHandler.removeCallbacks(mTimeoutTask);
878 mTimeoutTask.nextState = -1;
879 }
880
881 private class TimeoutTask implements Runnable
882 {
883 int nextState; // access should be synchronized on mLocks
884 public void run()
885 {
886 synchronized (mLocks) {
887 if (mSpew) {
888 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
889 }
890
891 if (nextState == -1) {
892 return;
893 }
894
895 mUserState = this.nextState;
896 setPowerState(this.nextState | mWakeLockState);
897
898 long now = SystemClock.uptimeMillis();
899
900 switch (this.nextState)
901 {
902 case SCREEN_BRIGHT:
903 if (mDimDelay >= 0) {
904 setTimeoutLocked(now, SCREEN_DIM);
905 break;
906 }
907 case SCREEN_DIM:
908 setTimeoutLocked(now, SCREEN_OFF);
909 break;
910 }
911 }
912 }
913 }
914
915 private void sendNotificationLocked(boolean on, int why)
916 {
917
918 if (!on) {
919 mNotificationWhy = why;
920 }
921
922 int value = on ? 1 : 0;
923 if (mNotificationQueue == -1) {
924 // empty
925 // Acquire the broadcast wake lock before changing the power
926 // state. It will be release after the broadcast is sent.
927 mBroadcastWakeLock.acquire();
928 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
929 mNotificationQueue = value;
930 mHandler.post(mNotificationTask);
931 } else if (mNotificationQueue != value) {
932 // it's a pair, so cancel it
933 mNotificationQueue = -1;
934 mHandler.removeCallbacks(mNotificationTask);
935 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
936 mBroadcastWakeLock.release();
937 } else {
938 // else, same so do nothing -- maybe we should warn?
939 Log.w(TAG, "Duplicate notification: on=" + on + " why=" + why);
940 }
941 }
942
943 private Runnable mNotificationTask = new Runnable()
944 {
945 public void run()
946 {
947 int value;
948 int why;
949 WindowManagerPolicy policy;
950 synchronized (mLocks) {
951 policy = getPolicyLocked();
952 value = mNotificationQueue;
953 why = mNotificationWhy;
954 mNotificationQueue = -1;
955 }
956 if (value == 1) {
957 mScreenOnStart = SystemClock.uptimeMillis();
958
959 policy.screenTurnedOn();
960 try {
961 ActivityManagerNative.getDefault().wakingUp();
962 } catch (RemoteException e) {
963 // ignore it
964 }
965
966 if (mSpew) {
967 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
968 }
969 if (mContext != null) {
The Android Open Source Projectd24b8182009-02-10 15:44:00 -0800970 if (ActivityManagerNative.isSystemReady()) {
971 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
972 mScreenOnBroadcastDone, mHandler, 0, null, null);
973 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700974 } else {
975 synchronized (mLocks) {
976 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
977 mBroadcastWakeLock.mCount);
978 mBroadcastWakeLock.release();
979 }
980 }
981 }
982 else if (value == 0) {
983 mScreenOffStart = SystemClock.uptimeMillis();
984
985 policy.screenTurnedOff(why);
986 try {
987 ActivityManagerNative.getDefault().goingToSleep();
988 } catch (RemoteException e) {
989 // ignore it.
990 }
991
992 if (mContext != null) {
993 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
994 mScreenOffBroadcastDone, mHandler, 0, null, null);
995 } else {
996 synchronized (mLocks) {
997 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
998 mBroadcastWakeLock.mCount);
999 mBroadcastWakeLock.release();
1000 }
1001 }
1002 }
1003 else {
The Android Open Source Projectda996f32009-02-13 12:57:50 -08001004 // If we're in this case, then this handler is running for a previous
1005 // paired transaction. mBroadcastWakeLock will already have been released
1006 // in sendNotificationLocked.
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001007 }
1008 }
1009 };
1010
1011 long mScreenOnStart;
1012 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1013 public void onReceive(Context context, Intent intent) {
1014 synchronized (mLocks) {
1015 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1016 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1017 mBroadcastWakeLock.release();
1018 }
1019 }
1020 };
1021
1022 long mScreenOffStart;
1023 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1024 public void onReceive(Context context, Intent intent) {
1025 synchronized (mLocks) {
1026 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1027 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1028 mBroadcastWakeLock.release();
1029 }
1030 }
1031 };
1032
1033 void logPointerUpEvent() {
1034 if (LOG_TOUCH_DOWNS) {
1035 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1036 mLastTouchDown = 0;
1037 }
1038 }
1039
1040 void logPointerDownEvent() {
1041 if (LOG_TOUCH_DOWNS) {
1042 // If we are not already timing a down/up sequence
1043 if (mLastTouchDown == 0) {
1044 mLastTouchDown = SystemClock.elapsedRealtime();
1045 mTouchCycles++;
1046 }
1047 }
1048 }
1049
The Android Open Source Projectb7986892009-01-09 17:51:23 -08001050 /**
1051 * Prevents the screen from turning on even if it *should* turn on due
1052 * to a subsequent full wake lock being acquired.
1053 * <p>
1054 * This is a temporary hack that allows an activity to "cover up" any
1055 * display glitches that happen during the activity's startup
1056 * sequence. (Specifically, this API was added to work around a
1057 * cosmetic bug in the "incoming call" sequence, where the lock screen
1058 * would flicker briefly before the incoming call UI became visible.)
1059 * TODO: There ought to be a more elegant way of doing this,
1060 * probably by having the PowerManager and ActivityManager
1061 * work together to let apps specify that the screen on/off
1062 * state should be synchronized with the Activity lifecycle.
1063 * <p>
1064 * Note that calling preventScreenOn(true) will NOT turn the screen
1065 * off if it's currently on. (This API only affects *future*
1066 * acquisitions of full wake locks.)
1067 * But calling preventScreenOn(false) WILL turn the screen on if
1068 * it's currently off because of a prior preventScreenOn(true) call.
1069 * <p>
1070 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1071 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1072 * call doesn't occur within 5 seconds, we'll turn the screen back on
1073 * ourselves (and log a warning about it); this prevents a buggy app
1074 * from disabling the screen forever.)
1075 * <p>
1076 * TODO: this feature should really be controlled by a new type of poke
1077 * lock (rather than an IPowerManager call).
1078 */
1079 public void preventScreenOn(boolean prevent) {
1080 // TODO: use a totally new permission (separate from DEVICE_POWER) for this?
1081 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1082
1083 synchronized (mLocks) {
1084 if (prevent) {
1085 // First of all, grab a partial wake lock to
1086 // make sure the CPU stays on during the entire
1087 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1088 mPreventScreenOnPartialLock.acquire();
1089
1090 // Post a forceReenableScreen() call (for 5 seconds in the
1091 // future) to make sure the matching preventScreenOn(false) call
1092 // has happened by then.
1093 mHandler.removeCallbacks(mForceReenableScreenTask);
1094 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1095
1096 // Finally, set the flag that prevents the screen from turning on.
1097 // (Below, in setPowerState(), we'll check mPreventScreenOn and
1098 // we *won't* call Power.setScreenState(true) if it's set.)
1099 mPreventScreenOn = true;
1100 } else {
1101 // (Re)enable the screen.
1102 mPreventScreenOn = false;
1103
1104 // We're "undoing" a the prior preventScreenOn(true) call, so we
1105 // no longer need the 5-second safeguard.
1106 mHandler.removeCallbacks(mForceReenableScreenTask);
1107
1108 // Forcibly turn on the screen if it's supposed to be on. (This
1109 // handles the case where the screen is currently off because of
1110 // a prior preventScreenOn(true) call.)
1111 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1112 if (mSpew) {
1113 Log.d(TAG,
1114 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1115 }
1116 int err = Power.setScreenState(true);
1117 if (err != 0) {
1118 Log.w(TAG, "preventScreenOn: error from Power.setScreenState(): " + err);
1119 }
1120 }
1121
1122 // Release the partial wake lock that we held during the
1123 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1124 mPreventScreenOnPartialLock.release();
1125 }
1126 }
1127 }
1128
1129 /**
1130 * Sanity-check that gets called 5 seconds after any call to
1131 * preventScreenOn(true). This ensures that the original call
1132 * is followed promptly by a call to preventScreenOn(false).
1133 */
1134 private void forceReenableScreen() {
1135 // We shouldn't get here at all if mPreventScreenOn is false, since
1136 // we should have already removed any existing
1137 // mForceReenableScreenTask messages...
1138 if (!mPreventScreenOn) {
1139 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1140 return;
1141 }
1142
1143 // Uh oh. It's been 5 seconds since a call to
1144 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1145 // This means the app that called preventScreenOn(true) is either
1146 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1147 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1148 // crashed before doing so.)
1149
1150 // Log a warning, and forcibly turn the screen back on.
1151 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1152 + "Forcing the screen back on...");
1153 preventScreenOn(false);
1154 }
1155
1156 private Runnable mForceReenableScreenTask = new Runnable() {
1157 public void run() {
1158 forceReenableScreen();
1159 }
1160 };
1161
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001162 private void setPowerState(int state)
1163 {
1164 setPowerState(state, false, false);
1165 }
1166
1167 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1168 {
1169 synchronized (mLocks) {
1170 int err;
1171
1172 if (mSpew) {
1173 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1174 + " newState=0x" + Integer.toHexString(newState)
1175 + " noChangeLights=" + noChangeLights);
1176 }
1177
1178 if (noChangeLights) {
1179 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1180 }
1181
1182 if (batteryIsLow()) {
1183 newState |= BATTERY_LOW_BIT;
1184 } else {
1185 newState &= ~BATTERY_LOW_BIT;
1186 }
1187 if (newState == mPowerState) {
1188 return;
1189 }
1190
1191 if (!mDoneBooting) {
1192 newState |= ALL_BRIGHT;
1193 }
1194
1195 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1196 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1197
1198 if (mSpew) {
1199 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1200 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1201 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1202 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1203 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1204 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1205 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1206 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1207 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1208 + " newScreenOn=" + newScreenOn);
1209 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1210 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1211 }
1212
1213 if (mPowerState != newState) {
1214 err = updateLightsLocked(newState, becauseOfUser);
1215 if (err != 0) {
1216 return;
1217 }
1218 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1219 }
1220
1221 if (oldScreenOn != newScreenOn) {
1222 if (newScreenOn) {
The Android Open Source Projectb7986892009-01-09 17:51:23 -08001223 // Turn on the screen UNLESS there was a prior
1224 // preventScreenOn(true) request. (Note that the lifetime
1225 // of a single preventScreenOn() request is limited to 5
1226 // seconds to prevent a buggy app from disabling the
1227 // screen forever; see forceReenableScreen().)
1228 boolean reallyTurnScreenOn = true;
1229 if (mSpew) {
1230 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1231 + mPreventScreenOn);
1232 }
1233
1234 if (mPreventScreenOn) {
1235 if (mSpew) {
1236 Log.d(TAG, "- PREVENTING screen from really turning on!");
1237 }
1238 reallyTurnScreenOn = false;
1239 }
1240 if (reallyTurnScreenOn) {
1241 err = Power.setScreenState(true);
The Android Open Source Projectd24b8182009-02-10 15:44:00 -08001242 long identity = Binder.clearCallingIdentity();
1243 try {
1244 mBatteryStats.noteScreenOn();
1245 } catch (RemoteException e) {
1246 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1247 } finally {
1248 Binder.restoreCallingIdentity(identity);
1249 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -08001250 } else {
1251 Power.setScreenState(false);
1252 // But continue as if we really did turn the screen on...
1253 err = 0;
1254 }
1255
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001256 mScreenOnStartTime = SystemClock.elapsedRealtime();
1257 mLastTouchDown = 0;
1258 mTotalTouchDownTime = 0;
1259 mTouchCycles = 0;
1260 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1261 mTotalTouchDownTime, mTouchCycles);
1262 if (err == 0) {
1263 mPowerState |= SCREEN_ON_BIT;
1264 sendNotificationLocked(true, -1);
1265 }
1266 } else {
1267 mScreenOffTime = SystemClock.elapsedRealtime();
The Android Open Source Projectd24b8182009-02-10 15:44:00 -08001268 long identity = Binder.clearCallingIdentity();
1269 try {
1270 mBatteryStats.noteScreenOff();
1271 } catch (RemoteException e) {
1272 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1273 } finally {
1274 Binder.restoreCallingIdentity(identity);
1275 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001276 if (!mScreenBrightness.animating) {
1277 err = turnScreenOffLocked(becauseOfUser);
1278 } else {
1279 mOffBecauseOfUser = becauseOfUser;
1280 err = 0;
1281 mLastTouchDown = 0;
1282 }
1283 }
1284 }
1285 }
1286 }
1287
1288 private int turnScreenOffLocked(boolean becauseOfUser) {
1289 if ((mPowerState&SCREEN_ON_BIT) != 0) {
1290 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1291 mTotalTouchDownTime, mTouchCycles);
1292 mLastTouchDown = 0;
1293 int err = Power.setScreenState(false);
1294 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1295 mScreenOnStartTime = 0;
1296 if (err == 0) {
1297 mPowerState &= ~SCREEN_ON_BIT;
1298 int why = becauseOfUser
1299 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1300 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1301 sendNotificationLocked(false, why);
1302 }
1303 return err;
1304 }
1305 return 0;
1306 }
1307
1308 private boolean batteryIsLow() {
1309 return (!mIsPowered &&
1310 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1311 }
1312
1313 private int updateLightsLocked(int newState, boolean becauseOfUser) {
1314 int oldState = mPowerState;
1315 int difference = newState ^ oldState;
1316 if (difference == 0) {
1317 return 0;
1318 }
1319
1320 int offMask = 0;
1321 int dimMask = 0;
1322 int onMask = 0;
1323
1324 int preferredBrightness = getPreferredBrightness();
1325 boolean startAnimation = false;
1326
1327 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1328 if (ANIMATE_KEYBOARD_LIGHTS) {
1329 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1330 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
1331 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS);
1332 } else {
1333 mKeyboardBrightness.setTargetLocked(preferredBrightness,
1334 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS);
1335 }
1336 startAnimation = true;
1337 } else {
1338 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1339 offMask |= Power.KEYBOARD_LIGHT;
1340 } else {
1341 onMask |= Power.KEYBOARD_LIGHT;
1342 }
1343 }
1344 }
1345
1346 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1347 if (ANIMATE_BUTTON_LIGHTS) {
1348 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1349 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
1350 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS);
1351 } else {
1352 mButtonBrightness.setTargetLocked(preferredBrightness,
1353 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS);
1354 }
1355 startAnimation = true;
1356 } else {
1357 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1358 offMask |= Power.BUTTON_LIGHT;
1359 } else {
1360 onMask |= Power.BUTTON_LIGHT;
1361 }
1362 }
1363 }
1364
1365 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1366 if (ANIMATE_SCREEN_LIGHTS) {
1367 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1368 // dim or turn off backlight, depending on if the screen is on
1369 // the scale is because the brightness ramp isn't linear and this biases
1370 // it so the later parts take longer.
1371 final float scale = 1.5f;
1372 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1373 if (ratio > 1.0f) ratio = 1.0f;
1374 if ((newState & SCREEN_ON_BIT) == 0) {
1375 int steps;
1376 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1377 // was bright
1378 steps = ANIM_STEPS;
1379 } else {
1380 // was dim
1381 steps = (int)(ANIM_STEPS*ratio*scale);
1382 }
1383 mScreenBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
1384 steps, INITIAL_SCREEN_BRIGHTNESS);
1385 } else {
1386 int steps;
1387 if ((oldState & SCREEN_ON_BIT) != 0) {
1388 // was bright
1389 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1390 } else {
1391 // was dim
1392 steps = (int)(ANIM_STEPS*ratio);
1393 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001394 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001395 // If the "stay on while plugged in" option is
1396 // turned on, then the screen will often not
1397 // automatically turn off while plugged in. To
1398 // still have a sense of when it is inactive, we
1399 // will then count going dim as turning off.
1400 mScreenOffTime = SystemClock.elapsedRealtime();
1401 }
1402 mScreenBrightness.setTargetLocked(Power.BRIGHTNESS_DIM,
1403 steps, INITIAL_SCREEN_BRIGHTNESS);
1404 }
1405 } else {
1406 mScreenBrightness.setTargetLocked(preferredBrightness,
1407 ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS);
1408 }
1409 startAnimation = true;
1410 } else {
1411 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1412 // dim or turn off backlight, depending on if the screen is on
1413 if ((newState & SCREEN_ON_BIT) == 0) {
1414 offMask |= Power.SCREEN_LIGHT;
1415 } else {
1416 dimMask |= Power.SCREEN_LIGHT;
1417 }
1418 } else {
1419 onMask |= Power.SCREEN_LIGHT;
1420 }
1421 }
1422 }
1423
1424 if (startAnimation) {
1425 if (mSpew) {
1426 Log.i(TAG, "Scheduling light animator!");
1427 }
1428 mHandler.removeCallbacks(mLightAnimator);
1429 mHandler.post(mLightAnimator);
1430 }
1431
1432 int err = 0;
1433 if (offMask != 0) {
1434 //Log.i(TAG, "Setting brightess off: " + offMask);
1435 err |= Power.setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
1436 }
1437 if (dimMask != 0) {
1438 int brightness = Power.BRIGHTNESS_DIM;
1439 if ((newState & BATTERY_LOW_BIT) != 0 &&
1440 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1441 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1442 }
1443 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
1444 err |= Power.setLightBrightness(dimMask, brightness);
1445 }
1446 if (onMask != 0) {
1447 int brightness = getPreferredBrightness();
1448 if ((newState & BATTERY_LOW_BIT) != 0 &&
1449 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1450 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1451 }
1452 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
1453 err |= Power.setLightBrightness(onMask, brightness);
1454 }
1455
1456 return err;
1457 }
1458
1459 class BrightnessState {
1460 final int mask;
1461
1462 boolean initialized;
1463 int targetValue;
1464 float curValue;
1465 float delta;
1466 boolean animating;
1467
1468 BrightnessState(int m) {
1469 mask = m;
1470 }
1471
1472 public void dump(PrintWriter pw, String prefix) {
1473 pw.println(prefix + "animating=" + animating
1474 + " targetValue=" + targetValue
1475 + " curValue=" + curValue
1476 + " delta=" + delta);
1477 }
1478
1479 void setTargetLocked(int target, int stepsToTarget, int initialValue) {
1480 if (!initialized) {
1481 initialized = true;
1482 curValue = (float)initialValue;
1483 }
1484 targetValue = target;
1485 delta = (targetValue-curValue) / stepsToTarget;
1486 if (mSpew) {
1487 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
1488 + " target=" + targetValue + " delta=" + delta);
1489 }
1490 animating = true;
1491 }
1492
1493 boolean stepLocked() {
1494 if (!animating) return false;
1495 if (false && mSpew) {
1496 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1497 + " target=" + targetValue + " delta=" + delta);
1498 }
1499 curValue += delta;
1500 int curIntValue = (int)curValue;
1501 boolean more = true;
1502 if (delta == 0) {
1503 more = false;
1504 } else if (delta > 0) {
1505 if (curIntValue >= targetValue) {
1506 curValue = curIntValue = targetValue;
1507 more = false;
1508 }
1509 } else {
1510 if (curIntValue <= targetValue) {
1511 curValue = curIntValue = targetValue;
1512 more = false;
1513 }
1514 }
1515 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
1516 Power.setLightBrightness(mask, curIntValue);
1517 animating = more;
1518 if (!more) {
1519 if (mask == Power.SCREEN_LIGHT && curIntValue == Power.BRIGHTNESS_OFF) {
1520 turnScreenOffLocked(mOffBecauseOfUser);
1521 }
1522 }
1523 return more;
1524 }
1525 }
1526
1527 private class LightAnimator implements Runnable {
1528 public void run() {
1529 synchronized (mLocks) {
1530 long now = SystemClock.uptimeMillis();
1531 boolean more = mScreenBrightness.stepLocked();
1532 if (mKeyboardBrightness.stepLocked()) {
1533 more = true;
1534 }
1535 if (mButtonBrightness.stepLocked()) {
1536 more = true;
1537 }
1538 if (more) {
1539 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1540 }
1541 }
1542 }
1543 }
1544
1545 private int getPreferredBrightness() {
1546 try {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001547 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1548 SCREEN_BRIGHTNESS);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001549 // Don't let applications turn the screen all the way off
1550 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1551 } catch (SettingNotFoundException snfe) {
1552 return Power.BRIGHTNESS_ON;
1553 }
1554 }
1555
1556 boolean screenIsOn() {
1557 synchronized (mLocks) {
1558 return (mPowerState & SCREEN_ON_BIT) != 0;
1559 }
1560 }
1561
1562 boolean screenIsBright() {
1563 synchronized (mLocks) {
1564 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1565 }
1566 }
1567
1568 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1569 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1570 userActivity(time, noChangeLights, OTHER_EVENT, force);
1571 }
1572
1573 public void userActivity(long time, boolean noChangeLights) {
1574 userActivity(time, noChangeLights, OTHER_EVENT, false);
1575 }
1576
1577 public void userActivity(long time, boolean noChangeLights, int eventType) {
1578 userActivity(time, noChangeLights, eventType, false);
1579 }
1580
1581 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1582 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1583
1584 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
1585 && !((eventType == OTHER_EVENT) || (eventType == BUTTON_EVENT))) {
1586 if (false) {
1587 Log.d(TAG, "dropping mPokey=0x" + Integer.toHexString(mPokey));
1588 }
1589 return;
1590 }
1591
1592 if (false) {
1593 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1594 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1595 } else {
1596 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1597 }
1598 }
1599
1600 synchronized (mLocks) {
1601 if (mSpew) {
1602 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1603 + " mUserActivityAllowed=" + mUserActivityAllowed
1604 + " mUserState=0x" + Integer.toHexString(mUserState)
1605 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
1606 }
1607 if (mLastEventTime <= time || force) {
1608 mLastEventTime = time;
1609 if (mUserActivityAllowed || force) {
1610 // Only turn on button backlights if a button was pressed.
1611 if (eventType == BUTTON_EVENT) {
1612 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1613 } else {
1614 // don't clear button/keyboard backlights when the screen is touched.
1615 mUserState |= SCREEN_BRIGHT;
1616 }
1617
1618 reactivateWakeLocksLocked();
1619 mWakeLockState = mLocks.gatherState();
1620 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1621 setTimeoutLocked(time, SCREEN_BRIGHT);
1622 }
1623 }
1624 }
1625 }
1626
1627 /**
1628 * The user requested that we go to sleep (probably with the power button).
1629 * This overrides all wake locks that are held.
1630 */
1631 public void goToSleep(long time)
1632 {
1633 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1634 synchronized (mLocks) {
1635 goToSleepLocked(time);
1636 }
1637 }
1638
1639 /**
1640 * Returns the time the screen has been on since boot, in millis.
1641 * @return screen on time
1642 */
1643 public long getScreenOnTime() {
1644 synchronized (mLocks) {
1645 if (mScreenOnStartTime == 0) {
1646 return mScreenOnTime;
1647 } else {
1648 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1649 }
1650 }
1651 }
1652
1653 private void goToSleepLocked(long time) {
1654
1655 if (mLastEventTime <= time) {
1656 mLastEventTime = time;
1657 // cancel all of the wake locks
1658 mWakeLockState = SCREEN_OFF;
1659 int N = mLocks.size();
1660 int numCleared = 0;
1661 for (int i=0; i<N; i++) {
1662 WakeLock wl = mLocks.get(i);
1663 if (isScreenLock(wl.flags)) {
1664 mLocks.get(i).activated = false;
1665 numCleared++;
1666 }
1667 }
1668 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
1669 mUserState = SCREEN_OFF;
1670 setPowerState(SCREEN_OFF, false, true);
1671 cancelTimerLocked();
1672 }
1673 }
1674
1675 public long timeSinceScreenOn() {
1676 synchronized (mLocks) {
1677 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1678 return 0;
1679 }
1680 return SystemClock.elapsedRealtime() - mScreenOffTime;
1681 }
1682 }
1683
1684 public void setKeyboardVisibility(boolean visible) {
1685 mKeyboardVisible = visible;
1686 }
1687
1688 /**
1689 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
1690 */
1691 public void enableUserActivity(boolean enabled) {
1692 synchronized (mLocks) {
1693 mUserActivityAllowed = enabled;
1694 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
1695 }
1696 }
1697
1698 /** Sets the screen off timeouts:
1699 * mKeylightDelay
1700 * mDimDelay
1701 * mScreenOffDelay
1702 * */
1703 private void setScreenOffTimeoutsLocked() {
1704 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001705 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001706 mDimDelay = -1;
1707 mScreenOffDelay = 0;
1708 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
1709 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
1710 mDimDelay = -1;
1711 mScreenOffDelay = 0;
1712 } else {
1713 int totalDelay = mTotalDelaySetting;
1714 mKeylightDelay = LONG_KEYLIGHT_DELAY;
1715 if (totalDelay < 0) {
1716 mScreenOffDelay = Integer.MAX_VALUE;
1717 } else if (mKeylightDelay < totalDelay) {
1718 // subtract the time that the keylight delay. This will give us the
1719 // remainder of the time that we need to sleep to get the accurate
1720 // screen off timeout.
1721 mScreenOffDelay = totalDelay - mKeylightDelay;
1722 } else {
1723 mScreenOffDelay = 0;
1724 }
1725 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
1726 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
1727 mScreenOffDelay = LONG_DIM_TIME;
1728 } else {
1729 mDimDelay = -1;
1730 }
1731 }
1732 if (mSpew) {
1733 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
1734 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
1735 + " mDimScreen=" + mDimScreen);
1736 }
1737 }
1738
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001739 /**
1740 * Refreshes cached Gservices settings. Called once on startup, and
1741 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
1742 * GservicesChangedReceiver).
1743 */
1744 private void updateGservicesValues() {
1745 mShortKeylightDelay = Settings.Gservices.getInt(
1746 mContext.getContentResolver(),
1747 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
1748 SHORT_KEYLIGHT_DELAY_DEFAULT);
1749 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
1750 }
1751
1752 /**
1753 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
1754 * which tells us we need to refresh our cached Gservices settings.
1755 */
1756 private class GservicesChangedReceiver extends BroadcastReceiver {
1757 @Override
1758 public void onReceive(Context context, Intent intent) {
1759 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
1760 updateGservicesValues();
1761 }
1762 }
1763
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001764 private class LockList extends ArrayList<WakeLock>
1765 {
1766 void addLock(WakeLock wl)
1767 {
1768 int index = getIndex(wl.binder);
1769 if (index < 0) {
1770 this.add(wl);
1771 }
1772 }
1773
1774 WakeLock removeLock(IBinder binder)
1775 {
1776 int index = getIndex(binder);
1777 if (index >= 0) {
1778 return this.remove(index);
1779 } else {
1780 return null;
1781 }
1782 }
1783
1784 int getIndex(IBinder binder)
1785 {
1786 int N = this.size();
1787 for (int i=0; i<N; i++) {
1788 if (this.get(i).binder == binder) {
1789 return i;
1790 }
1791 }
1792 return -1;
1793 }
1794
1795 int gatherState()
1796 {
1797 int result = 0;
1798 int N = this.size();
1799 for (int i=0; i<N; i++) {
1800 WakeLock wl = this.get(i);
1801 if (wl.activated) {
1802 if (isScreenLock(wl.flags)) {
1803 result |= wl.minState;
1804 }
1805 }
1806 }
1807 return result;
1808 }
1809 }
1810
1811 void setPolicy(WindowManagerPolicy p) {
1812 synchronized (mLocks) {
1813 mPolicy = p;
1814 mLocks.notifyAll();
1815 }
1816 }
1817
1818 WindowManagerPolicy getPolicyLocked() {
1819 while (mPolicy == null || !mDoneBooting) {
1820 try {
1821 mLocks.wait();
1822 } catch (InterruptedException e) {
1823 // Ignore
1824 }
1825 }
1826 return mPolicy;
1827 }
1828
1829 void systemReady() {
1830 synchronized (mLocks) {
1831 Log.d(TAG, "system ready!");
1832 mDoneBooting = true;
1833 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
1834 updateWakeLockLocked();
1835 mLocks.notifyAll();
1836 }
1837 }
1838
1839 public void monitor() {
1840 synchronized (mLocks) { }
1841 }
1842}