blob: 16b581903873f5ad8464b6ef7eefcec302b690af [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 Project3001a032009-02-19 10:57:31 -0800249 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
250 MY_UID, mTag);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700251 }
252 }
253
254 public void release() {
255 if (!mRefCounted || --mCount == 0) {
256 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
257 }
258 if (mCount < 0) {
259 throw new RuntimeException("WakeLock under-locked " + mTag);
260 }
261 }
262
263 public String toString() {
264 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
265 + " mCount=" + mCount + ")";
266 }
267 }
268
269 private final class BatteryReceiver extends BroadcastReceiver {
270 @Override
271 public void onReceive(Context context, Intent intent) {
272 synchronized (mLocks) {
273 boolean wasPowered = mIsPowered;
274 mIsPowered = mBatteryService.isPowered();
275
276 if (mIsPowered != wasPowered) {
277 // update mStayOnWhilePluggedIn wake lock
278 updateWakeLockLocked();
279
280 // treat plugging and unplugging the devices as a user activity.
281 // users find it disconcerting when they unplug the device
282 // and it shuts off right away.
283 // temporarily set mUserActivityAllowed to true so this will work
284 // even when the keyguard is on.
285 synchronized (mLocks) {
286 boolean savedActivityAllowed = mUserActivityAllowed;
287 mUserActivityAllowed = true;
288 userActivity(SystemClock.uptimeMillis(), false);
289 mUserActivityAllowed = savedActivityAllowed;
290 }
291 }
292 }
293 }
294 }
295
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800296 /**
297 * Set the setting that determines whether the device stays on when plugged in.
298 * The argument is a bit string, with each bit specifying a power source that,
299 * when the device is connected to that source, causes the device to stay on.
300 * See {@link android.os.BatteryManager} for the list of power sources that
301 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
302 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
303 * @param val an {@code int} containing the bits that specify which power sources
304 * should cause the device to stay on.
305 */
306 public void setStayOnSetting(int val) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700307 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
308 Settings.System.putInt(mContext.getContentResolver(),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800309 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700310 }
311
312 private class SettingsObserver implements Observer {
313 private int getInt(String name) {
314 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
315 }
316
317 public void update(Observable o, Object arg) {
318 synchronized (mLocks) {
319 // STAY_ON_WHILE_PLUGGED_IN
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800320 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700321 updateWakeLockLocked();
322
323 // SCREEN_OFF_TIMEOUT
324 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
325
326 // DIM_SCREEN
327 //mDimScreen = getInt(DIM_SCREEN) != 0;
328
329 // recalculate everything
330 setScreenOffTimeoutsLocked();
331 }
332 }
333 }
334
335 PowerManagerService()
336 {
337 // Hack to get our uid... should have a func for this.
338 long token = Binder.clearCallingIdentity();
339 MY_UID = Binder.getCallingUid();
340 Binder.restoreCallingIdentity(token);
341
342 // XXX remove this when the kernel doesn't timeout wake locks
343 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
344
345 // assume nothing is on yet
346 mUserState = mPowerState = 0;
347
348 // Add ourself to the Watchdog monitors.
349 Watchdog.getInstance().addMonitor(this);
350 mScreenOnStartTime = SystemClock.elapsedRealtime();
351 }
352
353 private ContentQueryMap mSettings;
354
355 void init(Context context, IActivityManager activity, BatteryService battery) {
356 mContext = context;
357 mActivityService = activity;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800358 mBatteryStats = BatteryStatsService.getService();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700359 mBatteryService = battery;
360
361 mHandlerThread = new HandlerThread("PowerManagerService") {
362 @Override
363 protected void onLooperPrepared() {
364 super.onLooperPrepared();
365 initInThread();
366 }
367 };
368 mHandlerThread.start();
369
370 synchronized (mHandlerThread) {
371 while (!mInitComplete) {
372 try {
373 mHandlerThread.wait();
374 } catch (InterruptedException e) {
375 // Ignore
376 }
377 }
378 }
379 }
380
381 void initInThread() {
382 mHandler = new Handler();
383
384 mBroadcastWakeLock = new UnsynchronizedWakeLock(
385 PowerManager.PARTIAL_WAKE_LOCK, "sleep_notification", true);
386 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
387 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
388 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
389 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800390 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
391 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700392
393 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
394 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
395 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
396 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
397
398 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800399 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700400 "(" + Settings.System.NAME + "=?) or ("
401 + Settings.System.NAME + "=?) or ("
402 + Settings.System.NAME + "=?)",
403 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN},
404 null);
405 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
406 SettingsObserver settingsObserver = new SettingsObserver();
407 mSettings.addObserver(settingsObserver);
408
409 // pretend that the settings changed so we will get their initial state
410 settingsObserver.update(mSettings, null);
411
412 // register for the battery changed notifications
413 IntentFilter filter = new IntentFilter();
414 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
415 mContext.registerReceiver(new BatteryReceiver(), filter);
416
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800417 // Listen for Gservices changes
418 IntentFilter gservicesChangedFilter =
419 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
420 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
421 // And explicitly do the initial update of our cached settings
422 updateGservicesValues();
423
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700424 // turn everything on
425 setPowerState(ALL_BRIGHT);
426
427 synchronized (mHandlerThread) {
428 mInitComplete = true;
429 mHandlerThread.notifyAll();
430 }
431 }
432
433 private class WakeLock implements IBinder.DeathRecipient
434 {
435 WakeLock(int f, IBinder b, String t, int u) {
436 super();
437 flags = f;
438 binder = b;
439 tag = t;
440 uid = u == MY_UID ? Process.SYSTEM_UID : u;
441 if (u != MY_UID || (
442 !"KEEP_SCREEN_ON_FLAG".equals(tag)
443 && !"KeyInputQueue".equals(tag))) {
444 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
445 ? BatteryStats.WAKE_TYPE_PARTIAL
446 : BatteryStats.WAKE_TYPE_FULL;
447 } else {
448 monitorType = -1;
449 }
450 try {
451 b.linkToDeath(this, 0);
452 } catch (RemoteException e) {
453 binderDied();
454 }
455 }
456 public void binderDied() {
457 synchronized (mLocks) {
458 releaseWakeLockLocked(this.binder, true);
459 }
460 }
461 final int flags;
462 final IBinder binder;
463 final String tag;
464 final int uid;
465 final int monitorType;
466 boolean activated = true;
467 int minState;
468 }
469
470 private void updateWakeLockLocked() {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800471 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700472 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
473 mStayOnWhilePluggedInScreenDimLock.acquire();
474 mStayOnWhilePluggedInPartialLock.acquire();
475 } else {
476 mStayOnWhilePluggedInScreenDimLock.release();
477 mStayOnWhilePluggedInPartialLock.release();
478 }
479 }
480
481 private boolean isScreenLock(int flags)
482 {
483 int n = flags & LOCK_MASK;
484 return n == PowerManager.FULL_WAKE_LOCK
485 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
486 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
487 }
488
489 public void acquireWakeLock(int flags, IBinder lock, String tag) {
490 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
The Android Open Source Project3001a032009-02-19 10:57:31 -0800491 int uid = Binder.getCallingUid();
The Android Open Source Projectd24b8182009-02-10 15:44:00 -0800492 long ident = Binder.clearCallingIdentity();
493 try {
494 synchronized (mLocks) {
The Android Open Source Project3001a032009-02-19 10:57:31 -0800495 acquireWakeLockLocked(flags, lock, uid, tag);
The Android Open Source Projectd24b8182009-02-10 15:44:00 -0800496 }
497 } finally {
498 Binder.restoreCallingIdentity(ident);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700499 }
500 }
501
The Android Open Source Project3001a032009-02-19 10:57:31 -0800502 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700503 int acquireUid = -1;
504 String acquireName = null;
505 int acquireType = -1;
506
507 if (mSpew) {
508 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
509 }
510
511 int index = mLocks.getIndex(lock);
512 WakeLock wl;
513 boolean newlock;
514 if (index < 0) {
The Android Open Source Project3001a032009-02-19 10:57:31 -0800515 wl = new WakeLock(flags, lock, tag, uid);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700516 switch (wl.flags & LOCK_MASK)
517 {
518 case PowerManager.FULL_WAKE_LOCK:
519 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
520 break;
521 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
522 wl.minState = SCREEN_BRIGHT;
523 break;
524 case PowerManager.SCREEN_DIM_WAKE_LOCK:
525 wl.minState = SCREEN_DIM;
526 break;
527 case PowerManager.PARTIAL_WAKE_LOCK:
528 break;
529 default:
530 // just log and bail. we're in the server, so don't
531 // throw an exception.
532 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
533 + " flags=" + flags);
534 return;
535 }
536 mLocks.addLock(wl);
537 newlock = true;
538 } else {
539 wl = mLocks.get(index);
540 newlock = false;
541 }
542 if (isScreenLock(flags)) {
543 // if this causes a wakeup, we reactivate all of the locks and
544 // set it to whatever they want. otherwise, we modulate that
545 // by the current state so we never turn it more on than
546 // it already is.
547 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
548 reactivateWakeLocksLocked();
549 if (mSpew) {
550 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
551 + " mLocks.gatherState()=0x"
552 + Integer.toHexString(mLocks.gatherState())
553 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
554 }
555 mWakeLockState = mLocks.gatherState();
556 } else {
557 if (mSpew) {
558 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
559 + " mLocks.gatherState()=0x"
560 + Integer.toHexString(mLocks.gatherState())
561 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
562 }
563 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
564 }
565 setPowerState(mWakeLockState | mUserState);
566 }
567 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
568 if (newlock) {
569 mPartialCount++;
570 if (mPartialCount == 1) {
571 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
572 }
573 }
574 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
575 }
576 if (newlock) {
577 acquireUid = wl.uid;
578 acquireName = wl.tag;
579 acquireType = wl.monitorType;
580 }
581
582 if (acquireType >= 0) {
583 try {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700584 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700585 } catch (RemoteException e) {
586 // Ignore
587 }
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);
The Android Open Source Project3001a032009-02-19 10:57:31 -0800800 pw.println(" mPreventScreenOn=" + mPreventScreenOn
801 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700802 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
803 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
804 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
805 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800806 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700807 mScreenBrightness.dump(pw, " mScreenBrightness: ");
808 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
809 mButtonBrightness.dump(pw, " mButtonBrightness: ");
810
811 int N = mLocks.size();
812 pw.println();
813 pw.println("mLocks.size=" + N + ":");
814 for (int i=0; i<N; i++) {
815 WakeLock wl = mLocks.get(i);
816 String type = lockType(wl.flags & LOCK_MASK);
817 String acquireCausesWakeup = "";
818 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
819 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
820 }
821 String activated = "";
822 if (wl.activated) {
823 activated = " activated";
824 }
825 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
826 + activated + " (minState=" + wl.minState + ")");
827 }
828
829 pw.println();
830 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
831 for (PokeLock p: mPokeLocks.values()) {
832 pw.println(" poke lock '" + p.tag + "':"
833 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
834 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
835 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
836 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
837 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
838 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
839 }
840
841 pw.println();
842 }
843
844 private void setTimeoutLocked(long now, int nextState)
845 {
846 if (mDoneBooting) {
847 mHandler.removeCallbacks(mTimeoutTask);
848 mTimeoutTask.nextState = nextState;
849 long when = now;
850 switch (nextState)
851 {
852 case SCREEN_BRIGHT:
853 when += mKeylightDelay;
854 break;
855 case SCREEN_DIM:
856 if (mDimDelay >= 0) {
857 when += mDimDelay;
858 break;
859 } else {
860 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
861 }
862 case SCREEN_OFF:
863 synchronized (mLocks) {
864 when += mScreenOffDelay;
865 }
866 break;
867 }
868 if (mSpew) {
869 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
870 + " when=" + when);
871 }
872 mHandler.postAtTime(mTimeoutTask, when);
873 mNextTimeout = when; // for debugging
874 }
875 }
876
877 private void cancelTimerLocked()
878 {
879 mHandler.removeCallbacks(mTimeoutTask);
880 mTimeoutTask.nextState = -1;
881 }
882
883 private class TimeoutTask implements Runnable
884 {
885 int nextState; // access should be synchronized on mLocks
886 public void run()
887 {
888 synchronized (mLocks) {
889 if (mSpew) {
890 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
891 }
892
893 if (nextState == -1) {
894 return;
895 }
896
897 mUserState = this.nextState;
898 setPowerState(this.nextState | mWakeLockState);
899
900 long now = SystemClock.uptimeMillis();
901
902 switch (this.nextState)
903 {
904 case SCREEN_BRIGHT:
905 if (mDimDelay >= 0) {
906 setTimeoutLocked(now, SCREEN_DIM);
907 break;
908 }
909 case SCREEN_DIM:
910 setTimeoutLocked(now, SCREEN_OFF);
911 break;
912 }
913 }
914 }
915 }
916
917 private void sendNotificationLocked(boolean on, int why)
918 {
919
920 if (!on) {
921 mNotificationWhy = why;
922 }
923
924 int value = on ? 1 : 0;
925 if (mNotificationQueue == -1) {
926 // empty
927 // Acquire the broadcast wake lock before changing the power
928 // state. It will be release after the broadcast is sent.
929 mBroadcastWakeLock.acquire();
930 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
931 mNotificationQueue = value;
932 mHandler.post(mNotificationTask);
933 } else if (mNotificationQueue != value) {
934 // it's a pair, so cancel it
935 mNotificationQueue = -1;
936 mHandler.removeCallbacks(mNotificationTask);
937 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
938 mBroadcastWakeLock.release();
939 } else {
940 // else, same so do nothing -- maybe we should warn?
941 Log.w(TAG, "Duplicate notification: on=" + on + " why=" + why);
942 }
943 }
944
945 private Runnable mNotificationTask = new Runnable()
946 {
947 public void run()
948 {
949 int value;
950 int why;
951 WindowManagerPolicy policy;
952 synchronized (mLocks) {
953 policy = getPolicyLocked();
954 value = mNotificationQueue;
955 why = mNotificationWhy;
956 mNotificationQueue = -1;
957 }
958 if (value == 1) {
959 mScreenOnStart = SystemClock.uptimeMillis();
960
961 policy.screenTurnedOn();
962 try {
963 ActivityManagerNative.getDefault().wakingUp();
964 } catch (RemoteException e) {
965 // ignore it
966 }
967
968 if (mSpew) {
969 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
970 }
971 if (mContext != null) {
The Android Open Source Projectd24b8182009-02-10 15:44:00 -0800972 if (ActivityManagerNative.isSystemReady()) {
973 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
974 mScreenOnBroadcastDone, mHandler, 0, null, null);
975 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700976 } else {
977 synchronized (mLocks) {
978 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
979 mBroadcastWakeLock.mCount);
980 mBroadcastWakeLock.release();
981 }
982 }
983 }
984 else if (value == 0) {
985 mScreenOffStart = SystemClock.uptimeMillis();
986
987 policy.screenTurnedOff(why);
988 try {
989 ActivityManagerNative.getDefault().goingToSleep();
990 } catch (RemoteException e) {
991 // ignore it.
992 }
993
994 if (mContext != null) {
995 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
996 mScreenOffBroadcastDone, mHandler, 0, null, null);
997 } else {
998 synchronized (mLocks) {
999 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1000 mBroadcastWakeLock.mCount);
1001 mBroadcastWakeLock.release();
1002 }
1003 }
1004 }
1005 else {
The Android Open Source Projectda996f32009-02-13 12:57:50 -08001006 // If we're in this case, then this handler is running for a previous
1007 // paired transaction. mBroadcastWakeLock will already have been released
1008 // in sendNotificationLocked.
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001009 }
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) {
The Android Open Source Projectb7986892009-01-09 17:51:23 -08001082 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1083
1084 synchronized (mLocks) {
1085 if (prevent) {
1086 // First of all, grab a partial wake lock to
1087 // make sure the CPU stays on during the entire
1088 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1089 mPreventScreenOnPartialLock.acquire();
1090
1091 // Post a forceReenableScreen() call (for 5 seconds in the
1092 // future) to make sure the matching preventScreenOn(false) call
1093 // has happened by then.
1094 mHandler.removeCallbacks(mForceReenableScreenTask);
1095 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1096
1097 // Finally, set the flag that prevents the screen from turning on.
1098 // (Below, in setPowerState(), we'll check mPreventScreenOn and
1099 // we *won't* call Power.setScreenState(true) if it's set.)
1100 mPreventScreenOn = true;
1101 } else {
1102 // (Re)enable the screen.
1103 mPreventScreenOn = false;
1104
1105 // We're "undoing" a the prior preventScreenOn(true) call, so we
1106 // no longer need the 5-second safeguard.
1107 mHandler.removeCallbacks(mForceReenableScreenTask);
1108
1109 // Forcibly turn on the screen if it's supposed to be on. (This
1110 // handles the case where the screen is currently off because of
1111 // a prior preventScreenOn(true) call.)
1112 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1113 if (mSpew) {
1114 Log.d(TAG,
1115 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1116 }
1117 int err = Power.setScreenState(true);
1118 if (err != 0) {
1119 Log.w(TAG, "preventScreenOn: error from Power.setScreenState(): " + err);
1120 }
1121 }
1122
1123 // Release the partial wake lock that we held during the
1124 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1125 mPreventScreenOnPartialLock.release();
1126 }
1127 }
1128 }
1129
The Android Open Source Project3001a032009-02-19 10:57:31 -08001130 public void setScreenBrightnessOverride(int brightness) {
1131 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1132
1133 synchronized (mLocks) {
1134 if (mScreenBrightnessOverride != brightness) {
1135 mScreenBrightnessOverride = brightness;
1136 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1137 }
1138 }
1139 }
1140
The Android Open Source Projectb7986892009-01-09 17:51:23 -08001141 /**
1142 * Sanity-check that gets called 5 seconds after any call to
1143 * preventScreenOn(true). This ensures that the original call
1144 * is followed promptly by a call to preventScreenOn(false).
1145 */
1146 private void forceReenableScreen() {
1147 // We shouldn't get here at all if mPreventScreenOn is false, since
1148 // we should have already removed any existing
1149 // mForceReenableScreenTask messages...
1150 if (!mPreventScreenOn) {
1151 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1152 return;
1153 }
1154
1155 // Uh oh. It's been 5 seconds since a call to
1156 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1157 // This means the app that called preventScreenOn(true) is either
1158 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1159 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1160 // crashed before doing so.)
1161
1162 // Log a warning, and forcibly turn the screen back on.
1163 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1164 + "Forcing the screen back on...");
1165 preventScreenOn(false);
1166 }
1167
1168 private Runnable mForceReenableScreenTask = new Runnable() {
1169 public void run() {
1170 forceReenableScreen();
1171 }
1172 };
1173
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001174 private void setPowerState(int state)
1175 {
1176 setPowerState(state, false, false);
1177 }
1178
1179 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1180 {
1181 synchronized (mLocks) {
1182 int err;
1183
1184 if (mSpew) {
1185 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1186 + " newState=0x" + Integer.toHexString(newState)
1187 + " noChangeLights=" + noChangeLights);
1188 }
1189
1190 if (noChangeLights) {
1191 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1192 }
1193
1194 if (batteryIsLow()) {
1195 newState |= BATTERY_LOW_BIT;
1196 } else {
1197 newState &= ~BATTERY_LOW_BIT;
1198 }
1199 if (newState == mPowerState) {
1200 return;
1201 }
1202
1203 if (!mDoneBooting) {
1204 newState |= ALL_BRIGHT;
1205 }
1206
1207 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1208 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1209
1210 if (mSpew) {
1211 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1212 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1213 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1214 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1215 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1216 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1217 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1218 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1219 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1220 + " newScreenOn=" + newScreenOn);
1221 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1222 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1223 }
1224
1225 if (mPowerState != newState) {
The Android Open Source Project3001a032009-02-19 10:57:31 -08001226 err = updateLightsLocked(newState, 0);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001227 if (err != 0) {
1228 return;
1229 }
1230 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1231 }
1232
1233 if (oldScreenOn != newScreenOn) {
1234 if (newScreenOn) {
The Android Open Source Projectb7986892009-01-09 17:51:23 -08001235 // Turn on the screen UNLESS there was a prior
1236 // preventScreenOn(true) request. (Note that the lifetime
1237 // of a single preventScreenOn() request is limited to 5
1238 // seconds to prevent a buggy app from disabling the
1239 // screen forever; see forceReenableScreen().)
1240 boolean reallyTurnScreenOn = true;
1241 if (mSpew) {
1242 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1243 + mPreventScreenOn);
1244 }
1245
1246 if (mPreventScreenOn) {
1247 if (mSpew) {
1248 Log.d(TAG, "- PREVENTING screen from really turning on!");
1249 }
1250 reallyTurnScreenOn = false;
1251 }
1252 if (reallyTurnScreenOn) {
1253 err = Power.setScreenState(true);
The Android Open Source Projectd24b8182009-02-10 15:44:00 -08001254 long identity = Binder.clearCallingIdentity();
1255 try {
1256 mBatteryStats.noteScreenOn();
1257 } catch (RemoteException e) {
1258 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1259 } finally {
1260 Binder.restoreCallingIdentity(identity);
1261 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -08001262 } else {
1263 Power.setScreenState(false);
1264 // But continue as if we really did turn the screen on...
1265 err = 0;
1266 }
1267
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001268 mScreenOnStartTime = SystemClock.elapsedRealtime();
1269 mLastTouchDown = 0;
1270 mTotalTouchDownTime = 0;
1271 mTouchCycles = 0;
1272 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1273 mTotalTouchDownTime, mTouchCycles);
1274 if (err == 0) {
1275 mPowerState |= SCREEN_ON_BIT;
1276 sendNotificationLocked(true, -1);
1277 }
1278 } else {
1279 mScreenOffTime = SystemClock.elapsedRealtime();
The Android Open Source Projectd24b8182009-02-10 15:44:00 -08001280 long identity = Binder.clearCallingIdentity();
1281 try {
1282 mBatteryStats.noteScreenOff();
1283 } catch (RemoteException e) {
1284 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1285 } finally {
1286 Binder.restoreCallingIdentity(identity);
1287 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001288 if (!mScreenBrightness.animating) {
1289 err = turnScreenOffLocked(becauseOfUser);
1290 } else {
1291 mOffBecauseOfUser = becauseOfUser;
1292 err = 0;
1293 mLastTouchDown = 0;
1294 }
1295 }
1296 }
1297 }
1298 }
1299
1300 private int turnScreenOffLocked(boolean becauseOfUser) {
1301 if ((mPowerState&SCREEN_ON_BIT) != 0) {
1302 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1303 mTotalTouchDownTime, mTouchCycles);
1304 mLastTouchDown = 0;
1305 int err = Power.setScreenState(false);
1306 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1307 mScreenOnStartTime = 0;
1308 if (err == 0) {
The Android Open Source Project3001a032009-02-19 10:57:31 -08001309 //
1310 // FIXME(joeo)
1311 //
1312 // The problem that causes the screen not to come on is that this isn't
1313 // called until after the animation is done. It needs to be set right
1314 // away, and the anmiation's state needs to be recorded separately.
1315 //
1316 //
1317
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001318 mPowerState &= ~SCREEN_ON_BIT;
1319 int why = becauseOfUser
1320 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1321 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1322 sendNotificationLocked(false, why);
1323 }
1324 return err;
1325 }
1326 return 0;
1327 }
1328
1329 private boolean batteryIsLow() {
1330 return (!mIsPowered &&
1331 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1332 }
1333
The Android Open Source Project3001a032009-02-19 10:57:31 -08001334 private int updateLightsLocked(int newState, int forceState) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001335 int oldState = mPowerState;
The Android Open Source Project3001a032009-02-19 10:57:31 -08001336 int difference = (newState ^ oldState) | forceState;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001337 if (difference == 0) {
1338 return 0;
1339 }
1340
1341 int offMask = 0;
1342 int dimMask = 0;
1343 int onMask = 0;
1344
1345 int preferredBrightness = getPreferredBrightness();
1346 boolean startAnimation = false;
1347
1348 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1349 if (ANIMATE_KEYBOARD_LIGHTS) {
1350 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1351 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
1352 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS);
1353 } else {
1354 mKeyboardBrightness.setTargetLocked(preferredBrightness,
1355 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS);
1356 }
1357 startAnimation = true;
1358 } else {
1359 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1360 offMask |= Power.KEYBOARD_LIGHT;
1361 } else {
1362 onMask |= Power.KEYBOARD_LIGHT;
1363 }
1364 }
1365 }
1366
1367 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1368 if (ANIMATE_BUTTON_LIGHTS) {
1369 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1370 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
1371 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS);
1372 } else {
1373 mButtonBrightness.setTargetLocked(preferredBrightness,
1374 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS);
1375 }
1376 startAnimation = true;
1377 } else {
1378 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1379 offMask |= Power.BUTTON_LIGHT;
1380 } else {
1381 onMask |= Power.BUTTON_LIGHT;
1382 }
1383 }
1384 }
1385
1386 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1387 if (ANIMATE_SCREEN_LIGHTS) {
1388 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1389 // dim or turn off backlight, depending on if the screen is on
1390 // the scale is because the brightness ramp isn't linear and this biases
1391 // it so the later parts take longer.
1392 final float scale = 1.5f;
1393 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1394 if (ratio > 1.0f) ratio = 1.0f;
1395 if ((newState & SCREEN_ON_BIT) == 0) {
1396 int steps;
1397 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1398 // was bright
1399 steps = ANIM_STEPS;
1400 } else {
1401 // was dim
1402 steps = (int)(ANIM_STEPS*ratio*scale);
1403 }
1404 mScreenBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
1405 steps, INITIAL_SCREEN_BRIGHTNESS);
1406 } else {
1407 int steps;
1408 if ((oldState & SCREEN_ON_BIT) != 0) {
1409 // was bright
1410 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1411 } else {
1412 // was dim
1413 steps = (int)(ANIM_STEPS*ratio);
1414 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001415 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001416 // If the "stay on while plugged in" option is
1417 // turned on, then the screen will often not
1418 // automatically turn off while plugged in. To
1419 // still have a sense of when it is inactive, we
1420 // will then count going dim as turning off.
1421 mScreenOffTime = SystemClock.elapsedRealtime();
1422 }
1423 mScreenBrightness.setTargetLocked(Power.BRIGHTNESS_DIM,
1424 steps, INITIAL_SCREEN_BRIGHTNESS);
1425 }
1426 } else {
1427 mScreenBrightness.setTargetLocked(preferredBrightness,
1428 ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS);
1429 }
1430 startAnimation = true;
1431 } else {
1432 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1433 // dim or turn off backlight, depending on if the screen is on
1434 if ((newState & SCREEN_ON_BIT) == 0) {
1435 offMask |= Power.SCREEN_LIGHT;
1436 } else {
1437 dimMask |= Power.SCREEN_LIGHT;
1438 }
1439 } else {
1440 onMask |= Power.SCREEN_LIGHT;
1441 }
1442 }
1443 }
1444
1445 if (startAnimation) {
1446 if (mSpew) {
1447 Log.i(TAG, "Scheduling light animator!");
1448 }
1449 mHandler.removeCallbacks(mLightAnimator);
1450 mHandler.post(mLightAnimator);
1451 }
1452
1453 int err = 0;
1454 if (offMask != 0) {
1455 //Log.i(TAG, "Setting brightess off: " + offMask);
1456 err |= Power.setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
1457 }
1458 if (dimMask != 0) {
1459 int brightness = Power.BRIGHTNESS_DIM;
1460 if ((newState & BATTERY_LOW_BIT) != 0 &&
1461 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1462 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1463 }
1464 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
1465 err |= Power.setLightBrightness(dimMask, brightness);
1466 }
1467 if (onMask != 0) {
1468 int brightness = getPreferredBrightness();
1469 if ((newState & BATTERY_LOW_BIT) != 0 &&
1470 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1471 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1472 }
1473 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
1474 err |= Power.setLightBrightness(onMask, brightness);
1475 }
1476
1477 return err;
1478 }
1479
1480 class BrightnessState {
1481 final int mask;
1482
1483 boolean initialized;
1484 int targetValue;
1485 float curValue;
1486 float delta;
1487 boolean animating;
1488
1489 BrightnessState(int m) {
1490 mask = m;
1491 }
1492
1493 public void dump(PrintWriter pw, String prefix) {
1494 pw.println(prefix + "animating=" + animating
1495 + " targetValue=" + targetValue
1496 + " curValue=" + curValue
1497 + " delta=" + delta);
1498 }
1499
1500 void setTargetLocked(int target, int stepsToTarget, int initialValue) {
1501 if (!initialized) {
1502 initialized = true;
1503 curValue = (float)initialValue;
1504 }
1505 targetValue = target;
1506 delta = (targetValue-curValue) / stepsToTarget;
1507 if (mSpew) {
1508 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
1509 + " target=" + targetValue + " delta=" + delta);
1510 }
1511 animating = true;
1512 }
1513
1514 boolean stepLocked() {
1515 if (!animating) return false;
1516 if (false && mSpew) {
1517 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1518 + " target=" + targetValue + " delta=" + delta);
1519 }
1520 curValue += delta;
1521 int curIntValue = (int)curValue;
1522 boolean more = true;
1523 if (delta == 0) {
1524 more = false;
1525 } else if (delta > 0) {
1526 if (curIntValue >= targetValue) {
1527 curValue = curIntValue = targetValue;
1528 more = false;
1529 }
1530 } else {
1531 if (curIntValue <= targetValue) {
1532 curValue = curIntValue = targetValue;
1533 more = false;
1534 }
1535 }
1536 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
1537 Power.setLightBrightness(mask, curIntValue);
1538 animating = more;
1539 if (!more) {
1540 if (mask == Power.SCREEN_LIGHT && curIntValue == Power.BRIGHTNESS_OFF) {
1541 turnScreenOffLocked(mOffBecauseOfUser);
1542 }
1543 }
1544 return more;
1545 }
1546 }
1547
1548 private class LightAnimator implements Runnable {
1549 public void run() {
1550 synchronized (mLocks) {
1551 long now = SystemClock.uptimeMillis();
1552 boolean more = mScreenBrightness.stepLocked();
1553 if (mKeyboardBrightness.stepLocked()) {
1554 more = true;
1555 }
1556 if (mButtonBrightness.stepLocked()) {
1557 more = true;
1558 }
1559 if (more) {
1560 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1561 }
1562 }
1563 }
1564 }
1565
1566 private int getPreferredBrightness() {
1567 try {
The Android Open Source Project3001a032009-02-19 10:57:31 -08001568 if (mScreenBrightnessOverride >= 0) {
1569 return mScreenBrightnessOverride;
1570 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001571 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1572 SCREEN_BRIGHTNESS);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001573 // Don't let applications turn the screen all the way off
1574 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1575 } catch (SettingNotFoundException snfe) {
1576 return Power.BRIGHTNESS_ON;
1577 }
1578 }
1579
1580 boolean screenIsOn() {
1581 synchronized (mLocks) {
1582 return (mPowerState & SCREEN_ON_BIT) != 0;
1583 }
1584 }
1585
1586 boolean screenIsBright() {
1587 synchronized (mLocks) {
1588 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1589 }
1590 }
1591
1592 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1593 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1594 userActivity(time, noChangeLights, OTHER_EVENT, force);
1595 }
1596
1597 public void userActivity(long time, boolean noChangeLights) {
1598 userActivity(time, noChangeLights, OTHER_EVENT, false);
1599 }
1600
1601 public void userActivity(long time, boolean noChangeLights, int eventType) {
1602 userActivity(time, noChangeLights, eventType, false);
1603 }
1604
1605 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1606 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1607
1608 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
1609 && !((eventType == OTHER_EVENT) || (eventType == BUTTON_EVENT))) {
1610 if (false) {
1611 Log.d(TAG, "dropping mPokey=0x" + Integer.toHexString(mPokey));
1612 }
1613 return;
1614 }
1615
1616 if (false) {
1617 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1618 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1619 } else {
1620 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1621 }
1622 }
1623
1624 synchronized (mLocks) {
1625 if (mSpew) {
1626 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1627 + " mUserActivityAllowed=" + mUserActivityAllowed
1628 + " mUserState=0x" + Integer.toHexString(mUserState)
1629 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
1630 }
1631 if (mLastEventTime <= time || force) {
1632 mLastEventTime = time;
1633 if (mUserActivityAllowed || force) {
1634 // Only turn on button backlights if a button was pressed.
1635 if (eventType == BUTTON_EVENT) {
1636 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1637 } else {
1638 // don't clear button/keyboard backlights when the screen is touched.
1639 mUserState |= SCREEN_BRIGHT;
1640 }
1641
1642 reactivateWakeLocksLocked();
1643 mWakeLockState = mLocks.gatherState();
1644 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1645 setTimeoutLocked(time, SCREEN_BRIGHT);
1646 }
1647 }
1648 }
1649 }
1650
1651 /**
1652 * The user requested that we go to sleep (probably with the power button).
1653 * This overrides all wake locks that are held.
1654 */
1655 public void goToSleep(long time)
1656 {
1657 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1658 synchronized (mLocks) {
1659 goToSleepLocked(time);
1660 }
1661 }
1662
1663 /**
1664 * Returns the time the screen has been on since boot, in millis.
1665 * @return screen on time
1666 */
1667 public long getScreenOnTime() {
1668 synchronized (mLocks) {
1669 if (mScreenOnStartTime == 0) {
1670 return mScreenOnTime;
1671 } else {
1672 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
1673 }
1674 }
1675 }
1676
1677 private void goToSleepLocked(long time) {
1678
1679 if (mLastEventTime <= time) {
1680 mLastEventTime = time;
1681 // cancel all of the wake locks
1682 mWakeLockState = SCREEN_OFF;
1683 int N = mLocks.size();
1684 int numCleared = 0;
1685 for (int i=0; i<N; i++) {
1686 WakeLock wl = mLocks.get(i);
1687 if (isScreenLock(wl.flags)) {
1688 mLocks.get(i).activated = false;
1689 numCleared++;
1690 }
1691 }
1692 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
1693 mUserState = SCREEN_OFF;
1694 setPowerState(SCREEN_OFF, false, true);
1695 cancelTimerLocked();
1696 }
1697 }
1698
1699 public long timeSinceScreenOn() {
1700 synchronized (mLocks) {
1701 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1702 return 0;
1703 }
1704 return SystemClock.elapsedRealtime() - mScreenOffTime;
1705 }
1706 }
1707
1708 public void setKeyboardVisibility(boolean visible) {
1709 mKeyboardVisible = visible;
1710 }
1711
1712 /**
1713 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
1714 */
1715 public void enableUserActivity(boolean enabled) {
1716 synchronized (mLocks) {
1717 mUserActivityAllowed = enabled;
1718 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
1719 }
1720 }
1721
1722 /** Sets the screen off timeouts:
1723 * mKeylightDelay
1724 * mDimDelay
1725 * mScreenOffDelay
1726 * */
1727 private void setScreenOffTimeoutsLocked() {
1728 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001729 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001730 mDimDelay = -1;
1731 mScreenOffDelay = 0;
1732 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
1733 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
1734 mDimDelay = -1;
1735 mScreenOffDelay = 0;
1736 } else {
1737 int totalDelay = mTotalDelaySetting;
1738 mKeylightDelay = LONG_KEYLIGHT_DELAY;
1739 if (totalDelay < 0) {
1740 mScreenOffDelay = Integer.MAX_VALUE;
1741 } else if (mKeylightDelay < totalDelay) {
1742 // subtract the time that the keylight delay. This will give us the
1743 // remainder of the time that we need to sleep to get the accurate
1744 // screen off timeout.
1745 mScreenOffDelay = totalDelay - mKeylightDelay;
1746 } else {
1747 mScreenOffDelay = 0;
1748 }
1749 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
1750 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
1751 mScreenOffDelay = LONG_DIM_TIME;
1752 } else {
1753 mDimDelay = -1;
1754 }
1755 }
1756 if (mSpew) {
1757 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
1758 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
1759 + " mDimScreen=" + mDimScreen);
1760 }
1761 }
1762
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001763 /**
1764 * Refreshes cached Gservices settings. Called once on startup, and
1765 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
1766 * GservicesChangedReceiver).
1767 */
1768 private void updateGservicesValues() {
1769 mShortKeylightDelay = Settings.Gservices.getInt(
1770 mContext.getContentResolver(),
1771 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
1772 SHORT_KEYLIGHT_DELAY_DEFAULT);
1773 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
1774 }
1775
1776 /**
1777 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
1778 * which tells us we need to refresh our cached Gservices settings.
1779 */
1780 private class GservicesChangedReceiver extends BroadcastReceiver {
1781 @Override
1782 public void onReceive(Context context, Intent intent) {
1783 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
1784 updateGservicesValues();
1785 }
1786 }
1787
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001788 private class LockList extends ArrayList<WakeLock>
1789 {
1790 void addLock(WakeLock wl)
1791 {
1792 int index = getIndex(wl.binder);
1793 if (index < 0) {
1794 this.add(wl);
1795 }
1796 }
1797
1798 WakeLock removeLock(IBinder binder)
1799 {
1800 int index = getIndex(binder);
1801 if (index >= 0) {
1802 return this.remove(index);
1803 } else {
1804 return null;
1805 }
1806 }
1807
1808 int getIndex(IBinder binder)
1809 {
1810 int N = this.size();
1811 for (int i=0; i<N; i++) {
1812 if (this.get(i).binder == binder) {
1813 return i;
1814 }
1815 }
1816 return -1;
1817 }
1818
1819 int gatherState()
1820 {
1821 int result = 0;
1822 int N = this.size();
1823 for (int i=0; i<N; i++) {
1824 WakeLock wl = this.get(i);
1825 if (wl.activated) {
1826 if (isScreenLock(wl.flags)) {
1827 result |= wl.minState;
1828 }
1829 }
1830 }
1831 return result;
1832 }
1833 }
1834
1835 void setPolicy(WindowManagerPolicy p) {
1836 synchronized (mLocks) {
1837 mPolicy = p;
1838 mLocks.notifyAll();
1839 }
1840 }
1841
1842 WindowManagerPolicy getPolicyLocked() {
1843 while (mPolicy == null || !mDoneBooting) {
1844 try {
1845 mLocks.wait();
1846 } catch (InterruptedException e) {
1847 // Ignore
1848 }
1849 }
1850 return mPolicy;
1851 }
1852
1853 void systemReady() {
1854 synchronized (mLocks) {
1855 Log.d(TAG, "system ready!");
1856 mDoneBooting = true;
1857 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
1858 updateWakeLockLocked();
1859 mLocks.notifyAll();
1860 }
1861 }
1862
1863 public void monitor() {
1864 synchronized (mLocks) { }
1865 }
1866}