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