blob: 7c111d3d8c8baa0e9c0e25f62d1e721f944860dd [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 {
1004 synchronized (mLocks) {
1005 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 4,
1006 mBroadcastWakeLock.mCount);
1007 mBroadcastWakeLock.release();
1008 }
1009 }
1010 }
1011 };
1012
1013 long mScreenOnStart;
1014 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1015 public void onReceive(Context context, Intent intent) {
1016 synchronized (mLocks) {
1017 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1018 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1019 mBroadcastWakeLock.release();
1020 }
1021 }
1022 };
1023
1024 long mScreenOffStart;
1025 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1026 public void onReceive(Context context, Intent intent) {
1027 synchronized (mLocks) {
1028 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1029 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1030 mBroadcastWakeLock.release();
1031 }
1032 }
1033 };
1034
1035 void logPointerUpEvent() {
1036 if (LOG_TOUCH_DOWNS) {
1037 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1038 mLastTouchDown = 0;
1039 }
1040 }
1041
1042 void logPointerDownEvent() {
1043 if (LOG_TOUCH_DOWNS) {
1044 // If we are not already timing a down/up sequence
1045 if (mLastTouchDown == 0) {
1046 mLastTouchDown = SystemClock.elapsedRealtime();
1047 mTouchCycles++;
1048 }
1049 }
1050 }
1051
The Android Open Source Projectb7986892009-01-09 17:51:23 -08001052 /**
1053 * Prevents the screen from turning on even if it *should* turn on due
1054 * to a subsequent full wake lock being acquired.
1055 * <p>
1056 * This is a temporary hack that allows an activity to "cover up" any
1057 * display glitches that happen during the activity's startup
1058 * sequence. (Specifically, this API was added to work around a
1059 * cosmetic bug in the "incoming call" sequence, where the lock screen
1060 * would flicker briefly before the incoming call UI became visible.)
1061 * TODO: There ought to be a more elegant way of doing this,
1062 * probably by having the PowerManager and ActivityManager
1063 * work together to let apps specify that the screen on/off
1064 * state should be synchronized with the Activity lifecycle.
1065 * <p>
1066 * Note that calling preventScreenOn(true) will NOT turn the screen
1067 * off if it's currently on. (This API only affects *future*
1068 * acquisitions of full wake locks.)
1069 * But calling preventScreenOn(false) WILL turn the screen on if
1070 * it's currently off because of a prior preventScreenOn(true) call.
1071 * <p>
1072 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1073 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1074 * call doesn't occur within 5 seconds, we'll turn the screen back on
1075 * ourselves (and log a warning about it); this prevents a buggy app
1076 * from disabling the screen forever.)
1077 * <p>
1078 * TODO: this feature should really be controlled by a new type of poke
1079 * lock (rather than an IPowerManager call).
1080 */
1081 public void preventScreenOn(boolean prevent) {
1082 // TODO: use a totally new permission (separate from DEVICE_POWER) for this?
1083 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1084
1085 synchronized (mLocks) {
1086 if (prevent) {
1087 // First of all, grab a partial wake lock to
1088 // make sure the CPU stays on during the entire
1089 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1090 mPreventScreenOnPartialLock.acquire();
1091
1092 // Post a forceReenableScreen() call (for 5 seconds in the
1093 // future) to make sure the matching preventScreenOn(false) call
1094 // has happened by then.
1095 mHandler.removeCallbacks(mForceReenableScreenTask);
1096 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1097
1098 // Finally, set the flag that prevents the screen from turning on.
1099 // (Below, in setPowerState(), we'll check mPreventScreenOn and
1100 // we *won't* call Power.setScreenState(true) if it's set.)
1101 mPreventScreenOn = true;
1102 } else {
1103 // (Re)enable the screen.
1104 mPreventScreenOn = false;
1105
1106 // We're "undoing" a the prior preventScreenOn(true) call, so we
1107 // no longer need the 5-second safeguard.
1108 mHandler.removeCallbacks(mForceReenableScreenTask);
1109
1110 // Forcibly turn on the screen if it's supposed to be on. (This
1111 // handles the case where the screen is currently off because of
1112 // a prior preventScreenOn(true) call.)
1113 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1114 if (mSpew) {
1115 Log.d(TAG,
1116 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1117 }
1118 int err = Power.setScreenState(true);
1119 if (err != 0) {
1120 Log.w(TAG, "preventScreenOn: error from Power.setScreenState(): " + err);
1121 }
1122 }
1123
1124 // Release the partial wake lock that we held during the
1125 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1126 mPreventScreenOnPartialLock.release();
1127 }
1128 }
1129 }
1130
1131 /**
1132 * Sanity-check that gets called 5 seconds after any call to
1133 * preventScreenOn(true). This ensures that the original call
1134 * is followed promptly by a call to preventScreenOn(false).
1135 */
1136 private void forceReenableScreen() {
1137 // We shouldn't get here at all if mPreventScreenOn is false, since
1138 // we should have already removed any existing
1139 // mForceReenableScreenTask messages...
1140 if (!mPreventScreenOn) {
1141 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1142 return;
1143 }
1144
1145 // Uh oh. It's been 5 seconds since a call to
1146 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1147 // This means the app that called preventScreenOn(true) is either
1148 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1149 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1150 // crashed before doing so.)
1151
1152 // Log a warning, and forcibly turn the screen back on.
1153 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1154 + "Forcing the screen back on...");
1155 preventScreenOn(false);
1156 }
1157
1158 private Runnable mForceReenableScreenTask = new Runnable() {
1159 public void run() {
1160 forceReenableScreen();
1161 }
1162 };
1163
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001164 private void setPowerState(int state)
1165 {
1166 setPowerState(state, false, false);
1167 }
1168
1169 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1170 {
1171 synchronized (mLocks) {
1172 int err;
1173
1174 if (mSpew) {
1175 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1176 + " newState=0x" + Integer.toHexString(newState)
1177 + " noChangeLights=" + noChangeLights);
1178 }
1179
1180 if (noChangeLights) {
1181 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1182 }
1183
1184 if (batteryIsLow()) {
1185 newState |= BATTERY_LOW_BIT;
1186 } else {
1187 newState &= ~BATTERY_LOW_BIT;
1188 }
1189 if (newState == mPowerState) {
1190 return;
1191 }
1192
1193 if (!mDoneBooting) {
1194 newState |= ALL_BRIGHT;
1195 }
1196
1197 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1198 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1199
1200 if (mSpew) {
1201 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1202 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1203 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1204 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1205 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1206 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1207 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1208 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1209 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1210 + " newScreenOn=" + newScreenOn);
1211 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1212 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1213 }
1214
1215 if (mPowerState != newState) {
1216 err = updateLightsLocked(newState, becauseOfUser);
1217 if (err != 0) {
1218 return;
1219 }
1220 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1221 }
1222
1223 if (oldScreenOn != newScreenOn) {
1224 if (newScreenOn) {
The Android Open Source Projectb7986892009-01-09 17:51:23 -08001225 // Turn on the screen UNLESS there was a prior
1226 // preventScreenOn(true) request. (Note that the lifetime
1227 // of a single preventScreenOn() request is limited to 5
1228 // seconds to prevent a buggy app from disabling the
1229 // screen forever; see forceReenableScreen().)
1230 boolean reallyTurnScreenOn = true;
1231 if (mSpew) {
1232 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1233 + mPreventScreenOn);
1234 }
1235
1236 if (mPreventScreenOn) {
1237 if (mSpew) {
1238 Log.d(TAG, "- PREVENTING screen from really turning on!");
1239 }
1240 reallyTurnScreenOn = false;
1241 }
1242 if (reallyTurnScreenOn) {
1243 err = Power.setScreenState(true);
The Android Open Source Projectd24b8182009-02-10 15:44:00 -08001244 long identity = Binder.clearCallingIdentity();
1245 try {
1246 mBatteryStats.noteScreenOn();
1247 } catch (RemoteException e) {
1248 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1249 } finally {
1250 Binder.restoreCallingIdentity(identity);
1251 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -08001252 } else {
1253 Power.setScreenState(false);
1254 // But continue as if we really did turn the screen on...
1255 err = 0;
1256 }
1257
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001258 mScreenOnStartTime = SystemClock.elapsedRealtime();
1259 mLastTouchDown = 0;
1260 mTotalTouchDownTime = 0;
1261 mTouchCycles = 0;
1262 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1263 mTotalTouchDownTime, mTouchCycles);
1264 if (err == 0) {
1265 mPowerState |= SCREEN_ON_BIT;
1266 sendNotificationLocked(true, -1);
1267 }
1268 } else {
1269 mScreenOffTime = SystemClock.elapsedRealtime();
The Android Open Source Projectd24b8182009-02-10 15:44:00 -08001270 long identity = Binder.clearCallingIdentity();
1271 try {
1272 mBatteryStats.noteScreenOff();
1273 } catch (RemoteException e) {
1274 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1275 } finally {
1276 Binder.restoreCallingIdentity(identity);
1277 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001278 if (!mScreenBrightness.animating) {
1279 err = turnScreenOffLocked(becauseOfUser);
1280 } else {
1281 mOffBecauseOfUser = becauseOfUser;
1282 err = 0;
1283 mLastTouchDown = 0;
1284 }
1285 }
1286 }
1287 }
1288 }
1289
1290 private int turnScreenOffLocked(boolean becauseOfUser) {
1291 if ((mPowerState&SCREEN_ON_BIT) != 0) {
1292 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1293 mTotalTouchDownTime, mTouchCycles);
1294 mLastTouchDown = 0;
1295 int err = Power.setScreenState(false);
1296 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1297 mScreenOnStartTime = 0;
1298 if (err == 0) {
1299 mPowerState &= ~SCREEN_ON_BIT;
1300 int why = becauseOfUser
1301 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1302 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1303 sendNotificationLocked(false, why);
1304 }
1305 return err;
1306 }
1307 return 0;
1308 }
1309
1310 private boolean batteryIsLow() {
1311 return (!mIsPowered &&
1312 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1313 }
1314
1315 private int updateLightsLocked(int newState, boolean becauseOfUser) {
1316 int oldState = mPowerState;
1317 int difference = newState ^ oldState;
1318 if (difference == 0) {
1319 return 0;
1320 }
1321
1322 int offMask = 0;
1323 int dimMask = 0;
1324 int onMask = 0;
1325
1326 int preferredBrightness = getPreferredBrightness();
1327 boolean startAnimation = false;
1328
1329 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1330 if (ANIMATE_KEYBOARD_LIGHTS) {
1331 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1332 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
1333 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS);
1334 } else {
1335 mKeyboardBrightness.setTargetLocked(preferredBrightness,
1336 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS);
1337 }
1338 startAnimation = true;
1339 } else {
1340 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1341 offMask |= Power.KEYBOARD_LIGHT;
1342 } else {
1343 onMask |= Power.KEYBOARD_LIGHT;
1344 }
1345 }
1346 }
1347
1348 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1349 if (ANIMATE_BUTTON_LIGHTS) {
1350 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1351 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
1352 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS);
1353 } else {
1354 mButtonBrightness.setTargetLocked(preferredBrightness,
1355 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS);
1356 }
1357 startAnimation = true;
1358 } else {
1359 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1360 offMask |= Power.BUTTON_LIGHT;
1361 } else {
1362 onMask |= Power.BUTTON_LIGHT;
1363 }
1364 }
1365 }
1366
1367 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1368 if (ANIMATE_SCREEN_LIGHTS) {
1369 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1370 // dim or turn off backlight, depending on if the screen is on
1371 // the scale is because the brightness ramp isn't linear and this biases
1372 // it so the later parts take longer.
1373 final float scale = 1.5f;
1374 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1375 if (ratio > 1.0f) ratio = 1.0f;
1376 if ((newState & SCREEN_ON_BIT) == 0) {
1377 int steps;
1378 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1379 // was bright
1380 steps = ANIM_STEPS;
1381 } else {
1382 // was dim
1383 steps = (int)(ANIM_STEPS*ratio*scale);
1384 }
1385 mScreenBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
1386 steps, INITIAL_SCREEN_BRIGHTNESS);
1387 } else {
1388 int steps;
1389 if ((oldState & SCREEN_ON_BIT) != 0) {
1390 // was bright
1391 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1392 } else {
1393 // was dim
1394 steps = (int)(ANIM_STEPS*ratio);
1395 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001396 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001397 // If the "stay on while plugged in" option is
1398 // turned on, then the screen will often not
1399 // automatically turn off while plugged in. To
1400 // still have a sense of when it is inactive, we
1401 // will then count going dim as turning off.
1402 mScreenOffTime = SystemClock.elapsedRealtime();
1403 }
1404 mScreenBrightness.setTargetLocked(Power.BRIGHTNESS_DIM,
1405 steps, INITIAL_SCREEN_BRIGHTNESS);
1406 }
1407 } else {
1408 mScreenBrightness.setTargetLocked(preferredBrightness,
1409 ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS);
1410 }
1411 startAnimation = true;
1412 } else {
1413 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1414 // dim or turn off backlight, depending on if the screen is on
1415 if ((newState & SCREEN_ON_BIT) == 0) {
1416 offMask |= Power.SCREEN_LIGHT;
1417 } else {
1418 dimMask |= Power.SCREEN_LIGHT;
1419 }
1420 } else {
1421 onMask |= Power.SCREEN_LIGHT;
1422 }
1423 }
1424 }
1425
1426 if (startAnimation) {
1427 if (mSpew) {
1428 Log.i(TAG, "Scheduling light animator!");
1429 }
1430 mHandler.removeCallbacks(mLightAnimator);
1431 mHandler.post(mLightAnimator);
1432 }
1433
1434 int err = 0;
1435 if (offMask != 0) {
1436 //Log.i(TAG, "Setting brightess off: " + offMask);
1437 err |= Power.setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
1438 }
1439 if (dimMask != 0) {
1440 int brightness = Power.BRIGHTNESS_DIM;
1441 if ((newState & BATTERY_LOW_BIT) != 0 &&
1442 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1443 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1444 }
1445 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
1446 err |= Power.setLightBrightness(dimMask, brightness);
1447 }
1448 if (onMask != 0) {
1449 int brightness = getPreferredBrightness();
1450 if ((newState & BATTERY_LOW_BIT) != 0 &&
1451 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1452 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1453 }
1454 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
1455 err |= Power.setLightBrightness(onMask, brightness);
1456 }
1457
1458 return err;
1459 }
1460
1461 class BrightnessState {
1462 final int mask;
1463
1464 boolean initialized;
1465 int targetValue;
1466 float curValue;
1467 float delta;
1468 boolean animating;
1469
1470 BrightnessState(int m) {
1471 mask = m;
1472 }
1473
1474 public void dump(PrintWriter pw, String prefix) {
1475 pw.println(prefix + "animating=" + animating
1476 + " targetValue=" + targetValue
1477 + " curValue=" + curValue
1478 + " delta=" + delta);
1479 }
1480
1481 void setTargetLocked(int target, int stepsToTarget, int initialValue) {
1482 if (!initialized) {
1483 initialized = true;
1484 curValue = (float)initialValue;
1485 }
1486 targetValue = target;
1487 delta = (targetValue-curValue) / stepsToTarget;
1488 if (mSpew) {
1489 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
1490 + " target=" + targetValue + " delta=" + delta);
1491 }
1492 animating = true;
1493 }
1494
1495 boolean stepLocked() {
1496 if (!animating) return false;
1497 if (false && mSpew) {
1498 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1499 + " target=" + targetValue + " delta=" + delta);
1500 }
1501 curValue += delta;
1502 int curIntValue = (int)curValue;
1503 boolean more = true;
1504 if (delta == 0) {
1505 more = false;
1506 } else if (delta > 0) {
1507 if (curIntValue >= targetValue) {
1508 curValue = curIntValue = targetValue;
1509 more = false;
1510 }
1511 } else {
1512 if (curIntValue <= targetValue) {
1513 curValue = curIntValue = targetValue;
1514 more = false;
1515 }
1516 }
1517 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
1518 Power.setLightBrightness(mask, curIntValue);
1519 animating = more;
1520 if (!more) {
1521 if (mask == Power.SCREEN_LIGHT && curIntValue == Power.BRIGHTNESS_OFF) {
1522 turnScreenOffLocked(mOffBecauseOfUser);
1523 }
1524 }
1525 return more;
1526 }
1527 }
1528
1529 private class LightAnimator implements Runnable {
1530 public void run() {
1531 synchronized (mLocks) {
1532 long now = SystemClock.uptimeMillis();
1533 boolean more = mScreenBrightness.stepLocked();
1534 if (mKeyboardBrightness.stepLocked()) {
1535 more = true;
1536 }
1537 if (mButtonBrightness.stepLocked()) {
1538 more = true;
1539 }
1540 if (more) {
1541 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1542 }
1543 }
1544 }
1545 }
1546
1547 private int getPreferredBrightness() {
1548 try {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001549 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1550 SCREEN_BRIGHTNESS);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001551 // Don't let applications turn the screen all the way off
1552 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1553 } catch (SettingNotFoundException snfe) {
1554 return Power.BRIGHTNESS_ON;
1555 }
1556 }
1557
1558 boolean screenIsOn() {
1559 synchronized (mLocks) {
1560 return (mPowerState & SCREEN_ON_BIT) != 0;
1561 }
1562 }
1563
1564 boolean screenIsBright() {
1565 synchronized (mLocks) {
1566 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1567 }
1568 }
1569
1570 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1571 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1572 userActivity(time, noChangeLights, OTHER_EVENT, force);
1573 }
1574
1575 public void userActivity(long time, boolean noChangeLights) {
1576 userActivity(time, noChangeLights, OTHER_EVENT, false);
1577 }
1578
1579 public void userActivity(long time, boolean noChangeLights, int eventType) {
1580 userActivity(time, noChangeLights, eventType, false);
1581 }
1582
1583 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1584 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1585
1586 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
1587 && !((eventType == OTHER_EVENT) || (eventType == BUTTON_EVENT))) {
1588 if (false) {
1589 Log.d(TAG, "dropping mPokey=0x" + Integer.toHexString(mPokey));
1590 }
1591 return;
1592 }
1593
1594 if (false) {
1595 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1596 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1597 } else {
1598 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1599 }
1600 }
1601
1602 synchronized (mLocks) {
1603 if (mSpew) {
1604 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1605 + " mUserActivityAllowed=" + mUserActivityAllowed
1606 + " mUserState=0x" + Integer.toHexString(mUserState)
1607 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
1608 }
1609 if (mLastEventTime <= time || force) {
1610 mLastEventTime = time;
1611 if (mUserActivityAllowed || force) {
1612 // Only turn on button backlights if a button was pressed.
1613 if (eventType == BUTTON_EVENT) {
1614 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1615 } else {
1616 // don't clear button/keyboard backlights when the screen is touched.
1617 mUserState |= SCREEN_BRIGHT;
1618 }
1619
1620 reactivateWakeLocksLocked();
1621 mWakeLockState = mLocks.gatherState();
1622 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1623 setTimeoutLocked(time, SCREEN_BRIGHT);
1624 }
1625 }
1626 }
1627 }
1628
1629 /**
1630 * The user requested that we go to sleep (probably with the power button).
1631 * This overrides all wake locks that are held.
1632 */
1633 public void goToSleep(long time)
1634 {
1635 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1636 synchronized (mLocks) {
1637 goToSleepLocked(time);
1638 }
1639 }
1640
1641 /**
1642 * Returns the time the screen has been on since boot, in millis.
1643 * @return screen on time
1644 */
1645 public long getScreenOnTime() {
1646 synchronized (mLocks) {
1647 if (mScreenOnStartTime == 0) {
1648 return mScreenOnTime;
1649 } else {
1650 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1651 }
1652 }
1653 }
1654
1655 private void goToSleepLocked(long time) {
1656
1657 if (mLastEventTime <= time) {
1658 mLastEventTime = time;
1659 // cancel all of the wake locks
1660 mWakeLockState = SCREEN_OFF;
1661 int N = mLocks.size();
1662 int numCleared = 0;
1663 for (int i=0; i<N; i++) {
1664 WakeLock wl = mLocks.get(i);
1665 if (isScreenLock(wl.flags)) {
1666 mLocks.get(i).activated = false;
1667 numCleared++;
1668 }
1669 }
1670 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
1671 mUserState = SCREEN_OFF;
1672 setPowerState(SCREEN_OFF, false, true);
1673 cancelTimerLocked();
1674 }
1675 }
1676
1677 public long timeSinceScreenOn() {
1678 synchronized (mLocks) {
1679 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1680 return 0;
1681 }
1682 return SystemClock.elapsedRealtime() - mScreenOffTime;
1683 }
1684 }
1685
1686 public void setKeyboardVisibility(boolean visible) {
1687 mKeyboardVisible = visible;
1688 }
1689
1690 /**
1691 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
1692 */
1693 public void enableUserActivity(boolean enabled) {
1694 synchronized (mLocks) {
1695 mUserActivityAllowed = enabled;
1696 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
1697 }
1698 }
1699
1700 /** Sets the screen off timeouts:
1701 * mKeylightDelay
1702 * mDimDelay
1703 * mScreenOffDelay
1704 * */
1705 private void setScreenOffTimeoutsLocked() {
1706 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001707 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001708 mDimDelay = -1;
1709 mScreenOffDelay = 0;
1710 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
1711 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
1712 mDimDelay = -1;
1713 mScreenOffDelay = 0;
1714 } else {
1715 int totalDelay = mTotalDelaySetting;
1716 mKeylightDelay = LONG_KEYLIGHT_DELAY;
1717 if (totalDelay < 0) {
1718 mScreenOffDelay = Integer.MAX_VALUE;
1719 } else if (mKeylightDelay < totalDelay) {
1720 // subtract the time that the keylight delay. This will give us the
1721 // remainder of the time that we need to sleep to get the accurate
1722 // screen off timeout.
1723 mScreenOffDelay = totalDelay - mKeylightDelay;
1724 } else {
1725 mScreenOffDelay = 0;
1726 }
1727 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
1728 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
1729 mScreenOffDelay = LONG_DIM_TIME;
1730 } else {
1731 mDimDelay = -1;
1732 }
1733 }
1734 if (mSpew) {
1735 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
1736 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
1737 + " mDimScreen=" + mDimScreen);
1738 }
1739 }
1740
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001741 /**
1742 * Refreshes cached Gservices settings. Called once on startup, and
1743 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
1744 * GservicesChangedReceiver).
1745 */
1746 private void updateGservicesValues() {
1747 mShortKeylightDelay = Settings.Gservices.getInt(
1748 mContext.getContentResolver(),
1749 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
1750 SHORT_KEYLIGHT_DELAY_DEFAULT);
1751 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
1752 }
1753
1754 /**
1755 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
1756 * which tells us we need to refresh our cached Gservices settings.
1757 */
1758 private class GservicesChangedReceiver extends BroadcastReceiver {
1759 @Override
1760 public void onReceive(Context context, Intent intent) {
1761 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
1762 updateGservicesValues();
1763 }
1764 }
1765
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001766 private class LockList extends ArrayList<WakeLock>
1767 {
1768 void addLock(WakeLock wl)
1769 {
1770 int index = getIndex(wl.binder);
1771 if (index < 0) {
1772 this.add(wl);
1773 }
1774 }
1775
1776 WakeLock removeLock(IBinder binder)
1777 {
1778 int index = getIndex(binder);
1779 if (index >= 0) {
1780 return this.remove(index);
1781 } else {
1782 return null;
1783 }
1784 }
1785
1786 int getIndex(IBinder binder)
1787 {
1788 int N = this.size();
1789 for (int i=0; i<N; i++) {
1790 if (this.get(i).binder == binder) {
1791 return i;
1792 }
1793 }
1794 return -1;
1795 }
1796
1797 int gatherState()
1798 {
1799 int result = 0;
1800 int N = this.size();
1801 for (int i=0; i<N; i++) {
1802 WakeLock wl = this.get(i);
1803 if (wl.activated) {
1804 if (isScreenLock(wl.flags)) {
1805 result |= wl.minState;
1806 }
1807 }
1808 }
1809 return result;
1810 }
1811 }
1812
1813 void setPolicy(WindowManagerPolicy p) {
1814 synchronized (mLocks) {
1815 mPolicy = p;
1816 mLocks.notifyAll();
1817 }
1818 }
1819
1820 WindowManagerPolicy getPolicyLocked() {
1821 while (mPolicy == null || !mDoneBooting) {
1822 try {
1823 mLocks.wait();
1824 } catch (InterruptedException e) {
1825 // Ignore
1826 }
1827 }
1828 return mPolicy;
1829 }
1830
1831 void systemReady() {
1832 synchronized (mLocks) {
1833 Log.d(TAG, "system ready!");
1834 mDoneBooting = true;
1835 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
1836 updateWakeLockLocked();
1837 mLocks.notifyAll();
1838 }
1839 }
1840
1841 public void monitor() {
1842 synchronized (mLocks) { }
1843 }
1844}