blob: be1e8a5e372f618726e043a04e53d71d77f9c3b2 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import com.android.internal.app.IBatteryStats;
20import com.android.server.am.BatteryStatsService;
21
22import android.app.ActivityManagerNative;
23import android.app.IActivityManager;
24import android.content.BroadcastReceiver;
25import android.content.ContentQueryMap;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070031import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070033import android.hardware.Sensor;
34import android.hardware.SensorEvent;
35import android.hardware.SensorEventListener;
36import android.hardware.SensorManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.BatteryStats;
38import android.os.Binder;
39import android.os.Handler;
40import android.os.HandlerThread;
41import android.os.IBinder;
42import android.os.IPowerManager;
43import android.os.LocalPowerManager;
44import android.os.Power;
45import android.os.PowerManager;
46import android.os.Process;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.provider.Settings.SettingNotFoundException;
50import android.provider.Settings;
51import android.util.EventLog;
52import android.util.Log;
53import android.view.WindowManagerPolicy;
54import static android.provider.Settings.System.DIM_SCREEN;
55import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050056import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070057import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
59import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
60
61import java.io.FileDescriptor;
62import java.io.PrintWriter;
63import java.util.ArrayList;
64import java.util.HashMap;
65import java.util.Observable;
66import java.util.Observer;
67
Mike Lockwoodbc706a02009-07-27 13:50:57 -070068class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040069 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070
71 private static final String TAG = "PowerManagerService";
72 static final String PARTIAL_NAME = "PowerManagerService";
73
74 private static final boolean LOG_PARTIAL_WL = false;
75
76 // Indicates whether touch-down cycles should be logged as part of the
77 // LOG_POWER_SCREEN_STATE log events
78 private static final boolean LOG_TOUCH_DOWNS = true;
79
80 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
81 | PowerManager.SCREEN_DIM_WAKE_LOCK
82 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070083 | PowerManager.FULL_WAKE_LOCK
84 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
86 // time since last state: time since last event:
87 // The short keylight delay comes from Gservices; this is the default.
88 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
89 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
90 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
91 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
92
Mike Lockwoodd7786b42009-10-15 17:09:16 -070093 // How long to wait to debounce light sensor changes.
94 private static final int LIGHT_SENSOR_DELAY = 1000;
95
Mike Lockwoodd20ea362009-09-15 00:13:38 -040096 // trigger proximity if distance is less than 5 cm
97 private static final float PROXIMITY_THRESHOLD = 5.0f;
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 // Cached Gservices settings; see updateGservicesValues()
100 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
101
102 // flags for setPowerState
103 private static final int SCREEN_ON_BIT = 0x00000001;
104 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
105 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
106 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
107 private static final int BATTERY_LOW_BIT = 0x00000010;
108
109 // values for setPowerState
110
111 // SCREEN_OFF == everything off
112 private static final int SCREEN_OFF = 0x00000000;
113
114 // SCREEN_DIM == screen on, screen backlight dim
115 private static final int SCREEN_DIM = SCREEN_ON_BIT;
116
117 // SCREEN_BRIGHT == screen on, screen backlight bright
118 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
119
120 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
121 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
122
123 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
124 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
125
126 // used for noChangeLights in setPowerState()
127 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
128
129 static final boolean ANIMATE_SCREEN_LIGHTS = true;
130 static final boolean ANIMATE_BUTTON_LIGHTS = false;
131 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
132
133 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400134 // Slower animation for autobrightness changes
135 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136
137 // These magic numbers are the initial state of the LEDs at boot. Ideally
138 // we should read them from the driver, but our current hardware returns 0
139 // for the initial value. Oops!
140 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
141 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
142 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
143
144 static final int LOG_POWER_SLEEP_REQUESTED = 2724;
145 static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
146 static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
147 static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
148 static final int LOG_POWER_SCREEN_STATE = 2728;
149 static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
150
151 private final int MY_UID;
152
153 private boolean mDoneBooting = false;
154 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700155 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
156 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private int mPartialCount = 0;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700158 private int mProximityCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private int mPowerState;
160 private boolean mOffBecauseOfUser;
161 private int mUserState;
162 private boolean mKeyboardVisible = false;
163 private boolean mUserActivityAllowed = true;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700164 private boolean mProximitySensorActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 private int mTotalDelaySetting;
166 private int mKeylightDelay;
167 private int mDimDelay;
168 private int mScreenOffDelay;
169 private int mWakeLockState;
170 private long mLastEventTime = 0;
171 private long mScreenOffTime;
172 private volatile WindowManagerPolicy mPolicy;
173 private final LockList mLocks = new LockList();
174 private Intent mScreenOffIntent;
175 private Intent mScreenOnIntent;
The Android Open Source Project10592532009-03-18 17:39:46 -0700176 private HardwareService mHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 private Context mContext;
178 private UnsynchronizedWakeLock mBroadcastWakeLock;
179 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
180 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
181 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
182 private HandlerThread mHandlerThread;
183 private Handler mHandler;
184 private TimeoutTask mTimeoutTask = new TimeoutTask();
185 private LightAnimator mLightAnimator = new LightAnimator();
186 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700187 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700189 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700191 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700192 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private boolean mIsPowered = false;
194 private IActivityManager mActivityService;
195 private IBatteryStats mBatteryStats;
196 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700197 private SensorManager mSensorManager;
198 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400199 private Sensor mLightSensor;
200 private boolean mLightSensorEnabled;
201 private float mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700202 private float mLightSensorPendingValue = -1;
203 private int mLightSensorBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 private boolean mDimScreen = true;
205 private long mNextTimeout;
206 private volatile int mPokey = 0;
207 private volatile boolean mPokeAwakeOnSet = false;
208 private volatile boolean mInitComplete = false;
209 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
210 private long mScreenOnTime;
211 private long mScreenOnStartTime;
212 private boolean mPreventScreenOn;
213 private int mScreenBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400214 private boolean mUseSoftwareAutoBrightness;
215 private boolean mUseHardwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700216 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700217 private int[] mAutoBrightnessLevels;
218 private int[] mLcdBacklightValues;
219 private int[] mButtonBacklightValues;
220 private int[] mKeyboardBacklightValues;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
222 // Used when logging number and duration of touch-down cycles
223 private long mTotalTouchDownTime;
224 private long mLastTouchDown;
225 private int mTouchCycles;
226
227 // could be either static or controllable at runtime
228 private static final boolean mSpew = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400229 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230
231 /*
232 static PrintStream mLog;
233 static {
234 try {
235 mLog = new PrintStream("/data/power.log");
236 }
237 catch (FileNotFoundException e) {
238 android.util.Log.e(TAG, "Life is hard", e);
239 }
240 }
241 static class Log {
242 static void d(String tag, String s) {
243 mLog.println(s);
244 android.util.Log.d(tag, s);
245 }
246 static void i(String tag, String s) {
247 mLog.println(s);
248 android.util.Log.i(tag, s);
249 }
250 static void w(String tag, String s) {
251 mLog.println(s);
252 android.util.Log.w(tag, s);
253 }
254 static void e(String tag, String s) {
255 mLog.println(s);
256 android.util.Log.e(tag, s);
257 }
258 }
259 */
260
261 /**
262 * This class works around a deadlock between the lock in PowerManager.WakeLock
263 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
264 * mToken object so it can be accessed from any thread, but it calls into here
265 * with its lock held. This class is essentially a reimplementation of
266 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
267 * only call it with our own locks held.
268 */
269 private class UnsynchronizedWakeLock {
270 int mFlags;
271 String mTag;
272 IBinder mToken;
273 int mCount = 0;
274 boolean mRefCounted;
275
276 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
277 mFlags = flags;
278 mTag = tag;
279 mToken = new Binder();
280 mRefCounted = refCounted;
281 }
282
283 public void acquire() {
284 if (!mRefCounted || mCount++ == 0) {
285 long ident = Binder.clearCallingIdentity();
286 try {
287 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
288 MY_UID, mTag);
289 } finally {
290 Binder.restoreCallingIdentity(ident);
291 }
292 }
293 }
294
295 public void release() {
296 if (!mRefCounted || --mCount == 0) {
297 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
298 }
299 if (mCount < 0) {
300 throw new RuntimeException("WakeLock under-locked " + mTag);
301 }
302 }
303
304 public String toString() {
305 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
306 + " mCount=" + mCount + ")";
307 }
308 }
309
310 private final class BatteryReceiver extends BroadcastReceiver {
311 @Override
312 public void onReceive(Context context, Intent intent) {
313 synchronized (mLocks) {
314 boolean wasPowered = mIsPowered;
315 mIsPowered = mBatteryService.isPowered();
316
317 if (mIsPowered != wasPowered) {
318 // update mStayOnWhilePluggedIn wake lock
319 updateWakeLockLocked();
320
321 // treat plugging and unplugging the devices as a user activity.
322 // users find it disconcerting when they unplug the device
323 // and it shuts off right away.
324 // temporarily set mUserActivityAllowed to true so this will work
325 // even when the keyguard is on.
326 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400327 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 }
329 }
330 }
331 }
332 }
333
334 /**
335 * Set the setting that determines whether the device stays on when plugged in.
336 * The argument is a bit string, with each bit specifying a power source that,
337 * when the device is connected to that source, causes the device to stay on.
338 * See {@link android.os.BatteryManager} for the list of power sources that
339 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
340 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
341 * @param val an {@code int} containing the bits that specify which power sources
342 * should cause the device to stay on.
343 */
344 public void setStayOnSetting(int val) {
345 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
346 Settings.System.putInt(mContext.getContentResolver(),
347 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
348 }
349
350 private class SettingsObserver implements Observer {
351 private int getInt(String name) {
352 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
353 }
354
355 public void update(Observable o, Object arg) {
356 synchronized (mLocks) {
357 // STAY_ON_WHILE_PLUGGED_IN
358 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
359 updateWakeLockLocked();
360
361 // SCREEN_OFF_TIMEOUT
362 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
363
364 // DIM_SCREEN
365 //mDimScreen = getInt(DIM_SCREEN) != 0;
366
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700367 // SCREEN_BRIGHTNESS_MODE
368 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 // recalculate everything
371 setScreenOffTimeoutsLocked();
372 }
373 }
374 }
375
376 PowerManagerService()
377 {
378 // Hack to get our uid... should have a func for this.
379 long token = Binder.clearCallingIdentity();
380 MY_UID = Binder.getCallingUid();
381 Binder.restoreCallingIdentity(token);
382
383 // XXX remove this when the kernel doesn't timeout wake locks
384 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
385
386 // assume nothing is on yet
387 mUserState = mPowerState = 0;
388
389 // Add ourself to the Watchdog monitors.
390 Watchdog.getInstance().addMonitor(this);
391 mScreenOnStartTime = SystemClock.elapsedRealtime();
392 }
393
394 private ContentQueryMap mSettings;
395
The Android Open Source Project10592532009-03-18 17:39:46 -0700396 void init(Context context, HardwareService hardware, IActivityManager activity,
397 BatteryService battery) {
398 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 mContext = context;
400 mActivityService = activity;
401 mBatteryStats = BatteryStatsService.getService();
402 mBatteryService = battery;
403
404 mHandlerThread = new HandlerThread("PowerManagerService") {
405 @Override
406 protected void onLooperPrepared() {
407 super.onLooperPrepared();
408 initInThread();
409 }
410 };
411 mHandlerThread.start();
412
413 synchronized (mHandlerThread) {
414 while (!mInitComplete) {
415 try {
416 mHandlerThread.wait();
417 } catch (InterruptedException e) {
418 // Ignore
419 }
420 }
421 }
422 }
423
424 void initInThread() {
425 mHandler = new Handler();
426
427 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700428 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
430 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
431 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
432 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
433 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
434 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
435
436 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
437 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
438 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
439 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
440
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700441 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400442
443 // read settings for auto-brightness
444 mUseSoftwareAutoBrightness = resources.getBoolean(
445 com.android.internal.R.bool.config_automatic_brightness_available);
446 mUseHardwareAutoBrightness = resources.getBoolean(
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700447 com.android.internal.R.bool.config_hardware_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400448 if (mUseHardwareAutoBrightness) {
449 mUseSoftwareAutoBrightness = false;
450 }
451 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700452 mAutoBrightnessLevels = resources.getIntArray(
453 com.android.internal.R.array.config_autoBrightnessLevels);
454 mLcdBacklightValues = resources.getIntArray(
455 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
456 mButtonBacklightValues = resources.getIntArray(
457 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
458 mKeyboardBacklightValues = resources.getIntArray(
459 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
460 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700461
462 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
464 "(" + Settings.System.NAME + "=?) or ("
465 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700466 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700468 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
469 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800470 null);
471 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
472 SettingsObserver settingsObserver = new SettingsObserver();
473 mSettings.addObserver(settingsObserver);
474
475 // pretend that the settings changed so we will get their initial state
476 settingsObserver.update(mSettings, null);
477
478 // register for the battery changed notifications
479 IntentFilter filter = new IntentFilter();
480 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
481 mContext.registerReceiver(new BatteryReceiver(), filter);
482
483 // Listen for Gservices changes
484 IntentFilter gservicesChangedFilter =
485 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
486 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
487 // And explicitly do the initial update of our cached settings
488 updateGservicesValues();
489
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400490 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400491 // turn the screen on
492 setPowerState(SCREEN_BRIGHT);
493 } else {
494 // turn everything on
495 setPowerState(ALL_BRIGHT);
496 }
Dan Murphy951764b2009-08-27 14:59:03 -0500497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 synchronized (mHandlerThread) {
499 mInitComplete = true;
500 mHandlerThread.notifyAll();
501 }
502 }
503
504 private class WakeLock implements IBinder.DeathRecipient
505 {
506 WakeLock(int f, IBinder b, String t, int u) {
507 super();
508 flags = f;
509 binder = b;
510 tag = t;
511 uid = u == MY_UID ? Process.SYSTEM_UID : u;
512 if (u != MY_UID || (
513 !"KEEP_SCREEN_ON_FLAG".equals(tag)
514 && !"KeyInputQueue".equals(tag))) {
515 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
516 ? BatteryStats.WAKE_TYPE_PARTIAL
517 : BatteryStats.WAKE_TYPE_FULL;
518 } else {
519 monitorType = -1;
520 }
521 try {
522 b.linkToDeath(this, 0);
523 } catch (RemoteException e) {
524 binderDied();
525 }
526 }
527 public void binderDied() {
528 synchronized (mLocks) {
529 releaseWakeLockLocked(this.binder, true);
530 }
531 }
532 final int flags;
533 final IBinder binder;
534 final String tag;
535 final int uid;
536 final int monitorType;
537 boolean activated = true;
538 int minState;
539 }
540
541 private void updateWakeLockLocked() {
542 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
543 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
544 mStayOnWhilePluggedInScreenDimLock.acquire();
545 mStayOnWhilePluggedInPartialLock.acquire();
546 } else {
547 mStayOnWhilePluggedInScreenDimLock.release();
548 mStayOnWhilePluggedInPartialLock.release();
549 }
550 }
551
552 private boolean isScreenLock(int flags)
553 {
554 int n = flags & LOCK_MASK;
555 return n == PowerManager.FULL_WAKE_LOCK
556 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
557 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
558 }
559
560 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700562 if (uid != Process.myUid()) {
563 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 long ident = Binder.clearCallingIdentity();
566 try {
567 synchronized (mLocks) {
568 acquireWakeLockLocked(flags, lock, uid, tag);
569 }
570 } finally {
571 Binder.restoreCallingIdentity(ident);
572 }
573 }
574
575 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
576 int acquireUid = -1;
577 String acquireName = null;
578 int acquireType = -1;
579
580 if (mSpew) {
581 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
582 }
583
584 int index = mLocks.getIndex(lock);
585 WakeLock wl;
586 boolean newlock;
587 if (index < 0) {
588 wl = new WakeLock(flags, lock, tag, uid);
589 switch (wl.flags & LOCK_MASK)
590 {
591 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400592 if (mAutoBrightessEnabled && mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400593 wl.minState = SCREEN_BRIGHT;
594 } else {
595 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 break;
598 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
599 wl.minState = SCREEN_BRIGHT;
600 break;
601 case PowerManager.SCREEN_DIM_WAKE_LOCK:
602 wl.minState = SCREEN_DIM;
603 break;
604 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700605 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 break;
607 default:
608 // just log and bail. we're in the server, so don't
609 // throw an exception.
610 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
611 + " flags=" + flags);
612 return;
613 }
614 mLocks.addLock(wl);
615 newlock = true;
616 } else {
617 wl = mLocks.get(index);
618 newlock = false;
619 }
620 if (isScreenLock(flags)) {
621 // if this causes a wakeup, we reactivate all of the locks and
622 // set it to whatever they want. otherwise, we modulate that
623 // by the current state so we never turn it more on than
624 // it already is.
625 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700626 int oldWakeLockState = mWakeLockState;
627 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 if (mSpew) {
629 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700630 + " mWakeLockState=0x"
631 + Integer.toHexString(mWakeLockState)
632 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 } else {
635 if (mSpew) {
636 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
637 + " mLocks.gatherState()=0x"
638 + Integer.toHexString(mLocks.gatherState())
639 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
640 }
641 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
642 }
643 setPowerState(mWakeLockState | mUserState);
644 }
645 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
646 if (newlock) {
647 mPartialCount++;
648 if (mPartialCount == 1) {
649 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
650 }
651 }
652 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700653 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
654 mProximityCount++;
655 if (mProximityCount == 1) {
656 enableProximityLockLocked();
657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 }
659 if (newlock) {
660 acquireUid = wl.uid;
661 acquireName = wl.tag;
662 acquireType = wl.monitorType;
663 }
664
665 if (acquireType >= 0) {
666 try {
667 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
668 } catch (RemoteException e) {
669 // Ignore
670 }
671 }
672 }
673
674 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700675 int uid = Binder.getCallingUid();
676 if (uid != Process.myUid()) {
677 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679
680 synchronized (mLocks) {
681 releaseWakeLockLocked(lock, false);
682 }
683 }
684
685 private void releaseWakeLockLocked(IBinder lock, boolean death) {
686 int releaseUid;
687 String releaseName;
688 int releaseType;
689
690 WakeLock wl = mLocks.removeLock(lock);
691 if (wl == null) {
692 return;
693 }
694
695 if (mSpew) {
696 Log.d(TAG, "releaseWakeLock flags=0x"
697 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
698 }
699
700 if (isScreenLock(wl.flags)) {
701 mWakeLockState = mLocks.gatherState();
702 // goes in the middle to reduce flicker
703 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
704 userActivity(SystemClock.uptimeMillis(), false);
705 }
706 setPowerState(mWakeLockState | mUserState);
707 }
708 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
709 mPartialCount--;
710 if (mPartialCount == 0) {
711 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
712 Power.releaseWakeLock(PARTIAL_NAME);
713 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700714 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
715 mProximityCount--;
716 if (mProximityCount == 0) {
717 disableProximityLockLocked();
718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 }
720 // Unlink the lock from the binder.
721 wl.binder.unlinkToDeath(wl, 0);
722 releaseUid = wl.uid;
723 releaseName = wl.tag;
724 releaseType = wl.monitorType;
725
726 if (releaseType >= 0) {
727 long origId = Binder.clearCallingIdentity();
728 try {
729 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
730 } catch (RemoteException e) {
731 // Ignore
732 } finally {
733 Binder.restoreCallingIdentity(origId);
734 }
735 }
736 }
737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 private class PokeLock implements IBinder.DeathRecipient
739 {
740 PokeLock(int p, IBinder b, String t) {
741 super();
742 this.pokey = p;
743 this.binder = b;
744 this.tag = t;
745 try {
746 b.linkToDeath(this, 0);
747 } catch (RemoteException e) {
748 binderDied();
749 }
750 }
751 public void binderDied() {
752 setPokeLock(0, this.binder, this.tag);
753 }
754 int pokey;
755 IBinder binder;
756 String tag;
757 boolean awakeOnSet;
758 }
759
760 public void setPokeLock(int pokey, IBinder token, String tag) {
761 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
762 if (token == null) {
763 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
764 return;
765 }
766
767 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
768 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
769 + " and POKE_LOCK_MEDIUM_TIMEOUT");
770 }
771
772 synchronized (mLocks) {
773 if (pokey != 0) {
774 PokeLock p = mPokeLocks.get(token);
775 int oldPokey = 0;
776 if (p != null) {
777 oldPokey = p.pokey;
778 p.pokey = pokey;
779 } else {
780 p = new PokeLock(pokey, token, tag);
781 mPokeLocks.put(token, p);
782 }
783 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
784 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
785 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
786 p.awakeOnSet = true;
787 }
788 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700789 PokeLock rLock = mPokeLocks.remove(token);
790 if (rLock != null) {
791 token.unlinkToDeath(rLock, 0);
792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 }
794
795 int oldPokey = mPokey;
796 int cumulative = 0;
797 boolean oldAwakeOnSet = mPokeAwakeOnSet;
798 boolean awakeOnSet = false;
799 for (PokeLock p: mPokeLocks.values()) {
800 cumulative |= p.pokey;
801 if (p.awakeOnSet) {
802 awakeOnSet = true;
803 }
804 }
805 mPokey = cumulative;
806 mPokeAwakeOnSet = awakeOnSet;
807
808 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
809 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
810
811 if (oldCumulativeTimeout != newCumulativeTimeout) {
812 setScreenOffTimeoutsLocked();
813 // reset the countdown timer, but use the existing nextState so it doesn't
814 // change anything
815 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
816 }
817 }
818 }
819
820 private static String lockType(int type)
821 {
822 switch (type)
823 {
824 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700825 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700827 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700829 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700831 return "PARTIAL_WAKE_LOCK ";
832 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
833 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 default:
David Brown251faa62009-08-02 22:04:36 -0700835 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 }
837 }
838
839 private static String dumpPowerState(int state) {
840 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
841 ? "KEYBOARD_BRIGHT_BIT " : "")
842 + (((state & SCREEN_BRIGHT_BIT) != 0)
843 ? "SCREEN_BRIGHT_BIT " : "")
844 + (((state & SCREEN_ON_BIT) != 0)
845 ? "SCREEN_ON_BIT " : "")
846 + (((state & BATTERY_LOW_BIT) != 0)
847 ? "BATTERY_LOW_BIT " : "");
848 }
849
850 @Override
851 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
852 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
853 != PackageManager.PERMISSION_GRANTED) {
854 pw.println("Permission Denial: can't dump PowerManager from from pid="
855 + Binder.getCallingPid()
856 + ", uid=" + Binder.getCallingUid());
857 return;
858 }
859
860 long now = SystemClock.uptimeMillis();
861
862 pw.println("Power Manager State:");
863 pw.println(" mIsPowered=" + mIsPowered
864 + " mPowerState=" + mPowerState
865 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
866 + " ms");
867 pw.println(" mPartialCount=" + mPartialCount);
868 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
869 pw.println(" mUserState=" + dumpPowerState(mUserState));
870 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
871 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
872 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
873 + " " + ((mNextTimeout-now)/1000) + "s from now");
874 pw.println(" mDimScreen=" + mDimScreen
875 + " mStayOnConditions=" + mStayOnConditions);
876 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
877 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700878 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
879 + ',' + mBroadcastQueue[2] + "}");
880 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
881 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
883 pw.println(" mKeyboardVisible=" + mKeyboardVisible
884 + " mUserActivityAllowed=" + mUserActivityAllowed);
885 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
886 + " mScreenOffDelay=" + mScreenOffDelay);
887 pw.println(" mPreventScreenOn=" + mPreventScreenOn
888 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
889 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
890 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
891 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
892 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
893 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700894 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
895 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
896 pw.println(" mLightSensorValue=" + mLightSensorValue);
897 pw.println(" mLightSensorPendingValue=" + mLightSensorPendingValue);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400898 pw.println(" mUseHardwareAutoBrightness=" + mUseHardwareAutoBrightness);
899 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700900 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 mScreenBrightness.dump(pw, " mScreenBrightness: ");
902 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
903 mButtonBrightness.dump(pw, " mButtonBrightness: ");
904
905 int N = mLocks.size();
906 pw.println();
907 pw.println("mLocks.size=" + N + ":");
908 for (int i=0; i<N; i++) {
909 WakeLock wl = mLocks.get(i);
910 String type = lockType(wl.flags & LOCK_MASK);
911 String acquireCausesWakeup = "";
912 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
913 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
914 }
915 String activated = "";
916 if (wl.activated) {
917 activated = " activated";
918 }
919 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
920 + activated + " (minState=" + wl.minState + ")");
921 }
922
923 pw.println();
924 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
925 for (PokeLock p: mPokeLocks.values()) {
926 pw.println(" poke lock '" + p.tag + "':"
927 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
928 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700929 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
930 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
932 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
933 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
934 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
935 }
936
937 pw.println();
938 }
939
940 private void setTimeoutLocked(long now, int nextState)
941 {
942 if (mDoneBooting) {
943 mHandler.removeCallbacks(mTimeoutTask);
944 mTimeoutTask.nextState = nextState;
945 long when = now;
946 switch (nextState)
947 {
948 case SCREEN_BRIGHT:
949 when += mKeylightDelay;
950 break;
951 case SCREEN_DIM:
952 if (mDimDelay >= 0) {
953 when += mDimDelay;
954 break;
955 } else {
956 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
957 }
958 case SCREEN_OFF:
959 synchronized (mLocks) {
960 when += mScreenOffDelay;
961 }
962 break;
963 }
964 if (mSpew) {
965 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
966 + " when=" + when);
967 }
968 mHandler.postAtTime(mTimeoutTask, when);
969 mNextTimeout = when; // for debugging
970 }
971 }
972
973 private void cancelTimerLocked()
974 {
975 mHandler.removeCallbacks(mTimeoutTask);
976 mTimeoutTask.nextState = -1;
977 }
978
979 private class TimeoutTask implements Runnable
980 {
981 int nextState; // access should be synchronized on mLocks
982 public void run()
983 {
984 synchronized (mLocks) {
985 if (mSpew) {
986 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
987 }
988
989 if (nextState == -1) {
990 return;
991 }
992
993 mUserState = this.nextState;
994 setPowerState(this.nextState | mWakeLockState);
995
996 long now = SystemClock.uptimeMillis();
997
998 switch (this.nextState)
999 {
1000 case SCREEN_BRIGHT:
1001 if (mDimDelay >= 0) {
1002 setTimeoutLocked(now, SCREEN_DIM);
1003 break;
1004 }
1005 case SCREEN_DIM:
1006 setTimeoutLocked(now, SCREEN_OFF);
1007 break;
1008 }
1009 }
1010 }
1011 }
1012
1013 private void sendNotificationLocked(boolean on, int why)
1014 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001015 if (!on) {
1016 mStillNeedSleepNotification = false;
1017 }
1018
Joe Onorato128e7292009-03-24 18:41:31 -07001019 // Add to the queue.
1020 int index = 0;
1021 while (mBroadcastQueue[index] != -1) {
1022 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 }
Joe Onorato128e7292009-03-24 18:41:31 -07001024 mBroadcastQueue[index] = on ? 1 : 0;
1025 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026
Joe Onorato128e7292009-03-24 18:41:31 -07001027 // If we added it position 2, then there is a pair that can be stripped.
1028 // If we added it position 1 and we're turning the screen off, we can strip
1029 // the pair and do nothing, because the screen is already off, and therefore
1030 // keyguard has already been enabled.
1031 // However, if we added it at position 1 and we're turning it on, then position
1032 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1033 // on, so have to run the queue then.
1034 if (index == 2) {
1035 // Also, while we're collapsing them, if it's going to be an "off," and one
1036 // is off because of user, then use that, regardless of whether it's the first
1037 // or second one.
1038 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
1039 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
1040 }
1041 mBroadcastQueue[0] = on ? 1 : 0;
1042 mBroadcastQueue[1] = -1;
1043 mBroadcastQueue[2] = -1;
1044 index = 0;
1045 }
1046 if (index == 1 && !on) {
1047 mBroadcastQueue[0] = -1;
1048 mBroadcastQueue[1] = -1;
1049 index = -1;
1050 // The wake lock was being held, but we're not actually going to do any
1051 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1053 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001054 }
1055
1056 // Now send the message.
1057 if (index >= 0) {
1058 // Acquire the broadcast wake lock before changing the power
1059 // state. It will be release after the broadcast is sent.
1060 // We always increment the ref count for each notification in the queue
1061 // and always decrement when that notification is handled.
1062 mBroadcastWakeLock.acquire();
1063 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1064 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 }
1066 }
1067
1068 private Runnable mNotificationTask = new Runnable()
1069 {
1070 public void run()
1071 {
Joe Onorato128e7292009-03-24 18:41:31 -07001072 while (true) {
1073 int value;
1074 int why;
1075 WindowManagerPolicy policy;
1076 synchronized (mLocks) {
1077 value = mBroadcastQueue[0];
1078 why = mBroadcastWhy[0];
1079 for (int i=0; i<2; i++) {
1080 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1081 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1082 }
1083 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 }
Joe Onorato128e7292009-03-24 18:41:31 -07001085 if (value == 1) {
1086 mScreenOnStart = SystemClock.uptimeMillis();
1087
1088 policy.screenTurnedOn();
1089 try {
1090 ActivityManagerNative.getDefault().wakingUp();
1091 } catch (RemoteException e) {
1092 // ignore it
1093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094
Joe Onorato128e7292009-03-24 18:41:31 -07001095 if (mSpew) {
1096 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1097 }
1098 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1099 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1100 mScreenOnBroadcastDone, mHandler, 0, null, null);
1101 } else {
1102 synchronized (mLocks) {
1103 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1104 mBroadcastWakeLock.mCount);
1105 mBroadcastWakeLock.release();
1106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 }
1108 }
Joe Onorato128e7292009-03-24 18:41:31 -07001109 else if (value == 0) {
1110 mScreenOffStart = SystemClock.uptimeMillis();
1111
1112 policy.screenTurnedOff(why);
1113 try {
1114 ActivityManagerNative.getDefault().goingToSleep();
1115 } catch (RemoteException e) {
1116 // ignore it.
1117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118
Joe Onorato128e7292009-03-24 18:41:31 -07001119 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1120 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1121 mScreenOffBroadcastDone, mHandler, 0, null, null);
1122 } else {
1123 synchronized (mLocks) {
1124 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1125 mBroadcastWakeLock.mCount);
1126 mBroadcastWakeLock.release();
1127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 }
1129 }
Joe Onorato128e7292009-03-24 18:41:31 -07001130 else {
1131 // If we're in this case, then this handler is running for a previous
1132 // paired transaction. mBroadcastWakeLock will already have been released.
1133 break;
1134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 }
1136 }
1137 };
1138
1139 long mScreenOnStart;
1140 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1141 public void onReceive(Context context, Intent intent) {
1142 synchronized (mLocks) {
1143 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1144 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1145 mBroadcastWakeLock.release();
1146 }
1147 }
1148 };
1149
1150 long mScreenOffStart;
1151 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1152 public void onReceive(Context context, Intent intent) {
1153 synchronized (mLocks) {
1154 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1155 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1156 mBroadcastWakeLock.release();
1157 }
1158 }
1159 };
1160
1161 void logPointerUpEvent() {
1162 if (LOG_TOUCH_DOWNS) {
1163 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1164 mLastTouchDown = 0;
1165 }
1166 }
1167
1168 void logPointerDownEvent() {
1169 if (LOG_TOUCH_DOWNS) {
1170 // If we are not already timing a down/up sequence
1171 if (mLastTouchDown == 0) {
1172 mLastTouchDown = SystemClock.elapsedRealtime();
1173 mTouchCycles++;
1174 }
1175 }
1176 }
1177
1178 /**
1179 * Prevents the screen from turning on even if it *should* turn on due
1180 * to a subsequent full wake lock being acquired.
1181 * <p>
1182 * This is a temporary hack that allows an activity to "cover up" any
1183 * display glitches that happen during the activity's startup
1184 * sequence. (Specifically, this API was added to work around a
1185 * cosmetic bug in the "incoming call" sequence, where the lock screen
1186 * would flicker briefly before the incoming call UI became visible.)
1187 * TODO: There ought to be a more elegant way of doing this,
1188 * probably by having the PowerManager and ActivityManager
1189 * work together to let apps specify that the screen on/off
1190 * state should be synchronized with the Activity lifecycle.
1191 * <p>
1192 * Note that calling preventScreenOn(true) will NOT turn the screen
1193 * off if it's currently on. (This API only affects *future*
1194 * acquisitions of full wake locks.)
1195 * But calling preventScreenOn(false) WILL turn the screen on if
1196 * it's currently off because of a prior preventScreenOn(true) call.
1197 * <p>
1198 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1199 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1200 * call doesn't occur within 5 seconds, we'll turn the screen back on
1201 * ourselves (and log a warning about it); this prevents a buggy app
1202 * from disabling the screen forever.)
1203 * <p>
1204 * TODO: this feature should really be controlled by a new type of poke
1205 * lock (rather than an IPowerManager call).
1206 */
1207 public void preventScreenOn(boolean prevent) {
1208 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1209
1210 synchronized (mLocks) {
1211 if (prevent) {
1212 // First of all, grab a partial wake lock to
1213 // make sure the CPU stays on during the entire
1214 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1215 mPreventScreenOnPartialLock.acquire();
1216
1217 // Post a forceReenableScreen() call (for 5 seconds in the
1218 // future) to make sure the matching preventScreenOn(false) call
1219 // has happened by then.
1220 mHandler.removeCallbacks(mForceReenableScreenTask);
1221 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1222
1223 // Finally, set the flag that prevents the screen from turning on.
1224 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001225 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 mPreventScreenOn = true;
1227 } else {
1228 // (Re)enable the screen.
1229 mPreventScreenOn = false;
1230
1231 // We're "undoing" a the prior preventScreenOn(true) call, so we
1232 // no longer need the 5-second safeguard.
1233 mHandler.removeCallbacks(mForceReenableScreenTask);
1234
1235 // Forcibly turn on the screen if it's supposed to be on. (This
1236 // handles the case where the screen is currently off because of
1237 // a prior preventScreenOn(true) call.)
1238 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1239 if (mSpew) {
1240 Log.d(TAG,
1241 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1242 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001243 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001245 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 }
1247 }
1248
1249 // Release the partial wake lock that we held during the
1250 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1251 mPreventScreenOnPartialLock.release();
1252 }
1253 }
1254 }
1255
1256 public void setScreenBrightnessOverride(int brightness) {
1257 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1258
1259 synchronized (mLocks) {
1260 if (mScreenBrightnessOverride != brightness) {
1261 mScreenBrightnessOverride = brightness;
1262 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1263 }
1264 }
1265 }
1266
1267 /**
1268 * Sanity-check that gets called 5 seconds after any call to
1269 * preventScreenOn(true). This ensures that the original call
1270 * is followed promptly by a call to preventScreenOn(false).
1271 */
1272 private void forceReenableScreen() {
1273 // We shouldn't get here at all if mPreventScreenOn is false, since
1274 // we should have already removed any existing
1275 // mForceReenableScreenTask messages...
1276 if (!mPreventScreenOn) {
1277 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1278 return;
1279 }
1280
1281 // Uh oh. It's been 5 seconds since a call to
1282 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1283 // This means the app that called preventScreenOn(true) is either
1284 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1285 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1286 // crashed before doing so.)
1287
1288 // Log a warning, and forcibly turn the screen back on.
1289 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1290 + "Forcing the screen back on...");
1291 preventScreenOn(false);
1292 }
1293
1294 private Runnable mForceReenableScreenTask = new Runnable() {
1295 public void run() {
1296 forceReenableScreen();
1297 }
1298 };
1299
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001300 private int setScreenStateLocked(boolean on) {
1301 int err = Power.setScreenState(on);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04001302 if (err == 0 && mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001303 enableLightSensor(on && mAutoBrightessEnabled);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001304 if (!on) {
1305 // make sure button and key backlights are off too
1306 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, 0);
1307 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, 0);
Mike Lockwood6c97fca2009-10-20 08:10:00 -04001308 // clear current value so we will update based on the new conditions
1309 // when the sensor is reenabled.
1310 mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001311 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001312 }
1313 return err;
1314 }
1315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 private void setPowerState(int state)
1317 {
1318 setPowerState(state, false, false);
1319 }
1320
1321 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1322 {
1323 synchronized (mLocks) {
1324 int err;
1325
1326 if (mSpew) {
1327 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1328 + " newState=0x" + Integer.toHexString(newState)
1329 + " noChangeLights=" + noChangeLights);
1330 }
1331
1332 if (noChangeLights) {
1333 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1334 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001335 if (mProximitySensorActive) {
1336 // don't turn on the screen when the proximity sensor lock is held
1337 newState = (newState & ~SCREEN_BRIGHT);
1338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339
1340 if (batteryIsLow()) {
1341 newState |= BATTERY_LOW_BIT;
1342 } else {
1343 newState &= ~BATTERY_LOW_BIT;
1344 }
1345 if (newState == mPowerState) {
1346 return;
1347 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001348
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04001349 if (!mDoneBooting && !(mAutoBrightessEnabled && mUseSoftwareAutoBrightness)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 newState |= ALL_BRIGHT;
1351 }
1352
1353 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1354 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1355
1356 if (mSpew) {
1357 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1358 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1359 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1360 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1361 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1362 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1363 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1364 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1365 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1366 + " newScreenOn=" + newScreenOn);
1367 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1368 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1369 }
1370
1371 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001372 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1374 }
1375
1376 if (oldScreenOn != newScreenOn) {
1377 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001378 // When the user presses the power button, we need to always send out the
1379 // notification that it's going to sleep so the keyguard goes on. But
1380 // we can't do that until the screen fades out, so we don't show the keyguard
1381 // too early.
1382 if (mStillNeedSleepNotification) {
1383 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1384 }
1385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 // Turn on the screen UNLESS there was a prior
1387 // preventScreenOn(true) request. (Note that the lifetime
1388 // of a single preventScreenOn() request is limited to 5
1389 // seconds to prevent a buggy app from disabling the
1390 // screen forever; see forceReenableScreen().)
1391 boolean reallyTurnScreenOn = true;
1392 if (mSpew) {
1393 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1394 + mPreventScreenOn);
1395 }
1396
1397 if (mPreventScreenOn) {
1398 if (mSpew) {
1399 Log.d(TAG, "- PREVENTING screen from really turning on!");
1400 }
1401 reallyTurnScreenOn = false;
1402 }
1403 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001404 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 long identity = Binder.clearCallingIdentity();
1406 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001407 mBatteryStats.noteScreenBrightness(
1408 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 mBatteryStats.noteScreenOn();
1410 } catch (RemoteException e) {
1411 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1412 } finally {
1413 Binder.restoreCallingIdentity(identity);
1414 }
1415 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001416 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 // But continue as if we really did turn the screen on...
1418 err = 0;
1419 }
1420
1421 mScreenOnStartTime = SystemClock.elapsedRealtime();
1422 mLastTouchDown = 0;
1423 mTotalTouchDownTime = 0;
1424 mTouchCycles = 0;
1425 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1426 mTotalTouchDownTime, mTouchCycles);
1427 if (err == 0) {
1428 mPowerState |= SCREEN_ON_BIT;
1429 sendNotificationLocked(true, -1);
1430 }
1431 } else {
1432 mScreenOffTime = SystemClock.elapsedRealtime();
1433 long identity = Binder.clearCallingIdentity();
1434 try {
1435 mBatteryStats.noteScreenOff();
1436 } catch (RemoteException e) {
1437 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1438 } finally {
1439 Binder.restoreCallingIdentity(identity);
1440 }
1441 mPowerState &= ~SCREEN_ON_BIT;
1442 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001443 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 } else {
1445 mOffBecauseOfUser = becauseOfUser;
1446 err = 0;
1447 mLastTouchDown = 0;
1448 }
1449 }
1450 }
1451 }
1452 }
1453
Joe Onorato128e7292009-03-24 18:41:31 -07001454 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 // I don't think we need to check the current state here because all of these
1456 // Power.setScreenState and sendNotificationLocked can both handle being
1457 // called multiple times in the same state. -joeo
1458 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1459 mTotalTouchDownTime, mTouchCycles);
1460 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001461 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 if (mScreenOnStartTime != 0) {
1463 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1464 mScreenOnStartTime = 0;
1465 }
1466 if (err == 0) {
1467 int why = becauseOfUser
1468 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1469 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1470 sendNotificationLocked(false, why);
1471 }
1472 return err;
1473 }
1474
1475 private boolean batteryIsLow() {
1476 return (!mIsPowered &&
1477 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1478 }
1479
The Android Open Source Project10592532009-03-18 17:39:46 -07001480 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001481 final int oldState = mPowerState;
1482 final int realDifference = (newState ^ oldState);
1483 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001485 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 }
1487
1488 int offMask = 0;
1489 int dimMask = 0;
1490 int onMask = 0;
1491
1492 int preferredBrightness = getPreferredBrightness();
1493 boolean startAnimation = false;
1494
1495 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1496 if (ANIMATE_KEYBOARD_LIGHTS) {
1497 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1498 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001499 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1500 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 } else {
1502 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001503 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1504 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 }
1506 startAnimation = true;
1507 } else {
1508 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001509 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001511 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
1513 }
1514 }
1515
1516 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1517 if (ANIMATE_BUTTON_LIGHTS) {
1518 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1519 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001520 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1521 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 } else {
1523 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001524 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1525 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 }
1527 startAnimation = true;
1528 } else {
1529 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001530 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001532 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 }
1534 }
1535 }
1536
1537 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1538 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001539 int nominalCurrentValue = -1;
1540 // If there was an actual difference in the light state, then
1541 // figure out the "ideal" current value based on the previous
1542 // state. Otherwise, this is a change due to the brightness
1543 // override, so we want to animate from whatever the current
1544 // value is.
1545 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1546 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1547 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1548 nominalCurrentValue = preferredBrightness;
1549 break;
1550 case SCREEN_ON_BIT:
1551 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1552 break;
1553 case 0:
1554 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1555 break;
1556 case SCREEN_BRIGHT_BIT:
1557 default:
1558 // not possible
1559 nominalCurrentValue = (int)mScreenBrightness.curValue;
1560 break;
1561 }
Joe Onorato128e7292009-03-24 18:41:31 -07001562 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001563 int brightness = preferredBrightness;
1564 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1566 // dim or turn off backlight, depending on if the screen is on
1567 // the scale is because the brightness ramp isn't linear and this biases
1568 // it so the later parts take longer.
1569 final float scale = 1.5f;
1570 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1571 if (ratio > 1.0f) ratio = 1.0f;
1572 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1574 // was bright
1575 steps = ANIM_STEPS;
1576 } else {
1577 // was dim
1578 steps = (int)(ANIM_STEPS*ratio*scale);
1579 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001580 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 if ((oldState & SCREEN_ON_BIT) != 0) {
1583 // was bright
1584 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1585 } else {
1586 // was dim
1587 steps = (int)(ANIM_STEPS*ratio);
1588 }
1589 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1590 // If the "stay on while plugged in" option is
1591 // turned on, then the screen will often not
1592 // automatically turn off while plugged in. To
1593 // still have a sense of when it is inactive, we
1594 // will then count going dim as turning off.
1595 mScreenOffTime = SystemClock.elapsedRealtime();
1596 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001597 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001600 long identity = Binder.clearCallingIdentity();
1601 try {
1602 mBatteryStats.noteScreenBrightness(brightness);
1603 } catch (RemoteException e) {
1604 // Nothing interesting to do.
1605 } finally {
1606 Binder.restoreCallingIdentity(identity);
1607 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001608 if (mScreenBrightness.setTargetLocked(brightness,
1609 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1610 startAnimation = true;
1611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 } else {
1613 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1614 // dim or turn off backlight, depending on if the screen is on
1615 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001616 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001618 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 }
1620 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001621 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 }
1623 }
1624 }
1625
1626 if (startAnimation) {
1627 if (mSpew) {
1628 Log.i(TAG, "Scheduling light animator!");
1629 }
1630 mHandler.removeCallbacks(mLightAnimator);
1631 mHandler.post(mLightAnimator);
1632 }
1633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 if (offMask != 0) {
1635 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001636 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
1638 if (dimMask != 0) {
1639 int brightness = Power.BRIGHTNESS_DIM;
1640 if ((newState & BATTERY_LOW_BIT) != 0 &&
1641 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1642 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1643 }
1644 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001645 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 }
1647 if (onMask != 0) {
1648 int brightness = getPreferredBrightness();
1649 if ((newState & BATTERY_LOW_BIT) != 0 &&
1650 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1651 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1652 }
1653 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001654 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657
The Android Open Source Project10592532009-03-18 17:39:46 -07001658 private void setLightBrightness(int mask, int value) {
1659 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1660 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1661 }
1662 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1663 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1664 }
1665 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1666 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 }
1669
1670 class BrightnessState {
1671 final int mask;
1672
1673 boolean initialized;
1674 int targetValue;
1675 float curValue;
1676 float delta;
1677 boolean animating;
1678
1679 BrightnessState(int m) {
1680 mask = m;
1681 }
1682
1683 public void dump(PrintWriter pw, String prefix) {
1684 pw.println(prefix + "animating=" + animating
1685 + " targetValue=" + targetValue
1686 + " curValue=" + curValue
1687 + " delta=" + delta);
1688 }
1689
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001690 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001691 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 if (!initialized) {
1693 initialized = true;
1694 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001695 } else if (targetValue == target) {
1696 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 }
1698 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001699 delta = (targetValue -
1700 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1701 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001703 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001705 + " target=" + targetValue + " delta=" + delta
1706 + " nominalCurrentValue=" + nominalCurrentValue
1707 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 }
1709 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001710 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 }
1712
1713 boolean stepLocked() {
1714 if (!animating) return false;
1715 if (false && mSpew) {
1716 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1717 + " target=" + targetValue + " delta=" + delta);
1718 }
1719 curValue += delta;
1720 int curIntValue = (int)curValue;
1721 boolean more = true;
1722 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001723 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 more = false;
1725 } else if (delta > 0) {
1726 if (curIntValue >= targetValue) {
1727 curValue = curIntValue = targetValue;
1728 more = false;
1729 }
1730 } else {
1731 if (curIntValue <= targetValue) {
1732 curValue = curIntValue = targetValue;
1733 more = false;
1734 }
1735 }
1736 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001737 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 animating = more;
1739 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001740 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001741 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 }
1743 }
1744 return more;
1745 }
1746 }
1747
1748 private class LightAnimator implements Runnable {
1749 public void run() {
1750 synchronized (mLocks) {
1751 long now = SystemClock.uptimeMillis();
1752 boolean more = mScreenBrightness.stepLocked();
1753 if (mKeyboardBrightness.stepLocked()) {
1754 more = true;
1755 }
1756 if (mButtonBrightness.stepLocked()) {
1757 more = true;
1758 }
1759 if (more) {
1760 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1761 }
1762 }
1763 }
1764 }
1765
1766 private int getPreferredBrightness() {
1767 try {
1768 if (mScreenBrightnessOverride >= 0) {
1769 return mScreenBrightnessOverride;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04001770 } else if (mLightSensorBrightness >= 0 && mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001771 return mLightSensorBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 }
1773 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1774 SCREEN_BRIGHTNESS);
1775 // Don't let applications turn the screen all the way off
1776 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1777 } catch (SettingNotFoundException snfe) {
1778 return Power.BRIGHTNESS_ON;
1779 }
1780 }
1781
1782 boolean screenIsOn() {
1783 synchronized (mLocks) {
1784 return (mPowerState & SCREEN_ON_BIT) != 0;
1785 }
1786 }
1787
1788 boolean screenIsBright() {
1789 synchronized (mLocks) {
1790 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1791 }
1792 }
1793
Mike Lockwood200b30b2009-09-20 00:23:59 -04001794 private void forceUserActivityLocked() {
1795 boolean savedActivityAllowed = mUserActivityAllowed;
1796 mUserActivityAllowed = true;
1797 userActivity(SystemClock.uptimeMillis(), false);
1798 mUserActivityAllowed = savedActivityAllowed;
1799 }
1800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1802 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1803 userActivity(time, noChangeLights, OTHER_EVENT, force);
1804 }
1805
1806 public void userActivity(long time, boolean noChangeLights) {
1807 userActivity(time, noChangeLights, OTHER_EVENT, false);
1808 }
1809
1810 public void userActivity(long time, boolean noChangeLights, int eventType) {
1811 userActivity(time, noChangeLights, eventType, false);
1812 }
1813
1814 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1815 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1816
1817 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001818 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001820 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 }
1822 return;
1823 }
1824
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001825 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1826 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1827 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1828 if (false) {
1829 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1830 }
1831 return;
1832 }
1833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 if (false) {
1835 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1836 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1837 } else {
1838 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1839 }
1840 }
1841
1842 synchronized (mLocks) {
1843 if (mSpew) {
1844 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1845 + " mUserActivityAllowed=" + mUserActivityAllowed
1846 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001847 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1848 + " mProximitySensorActive=" + mProximitySensorActive
1849 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 }
Mike Lockwood05067122009-10-27 23:07:25 -04001851 // ignore user activity if we are in the process of turning off the screen
1852 if (mScreenBrightness.animating && mScreenBrightness.targetValue == 0) {
1853 Log.d(TAG, "ignoring user activity while turning off screen");
1854 return;
1855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 if (mLastEventTime <= time || force) {
1857 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001858 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001859 // Only turn on button backlights if a button was pressed
1860 // and auto brightness is disabled
Mike Lockwood3333fa42009-10-26 14:50:42 -04001861 if (eventType == BUTTON_EVENT &&
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04001862 !(mAutoBrightessEnabled && mUseSoftwareAutoBrightness)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1864 } else {
1865 // don't clear button/keyboard backlights when the screen is touched.
1866 mUserState |= SCREEN_BRIGHT;
1867 }
1868
Dianne Hackborn617f8772009-03-31 15:04:46 -07001869 int uid = Binder.getCallingUid();
1870 long ident = Binder.clearCallingIdentity();
1871 try {
1872 mBatteryStats.noteUserActivity(uid, eventType);
1873 } catch (RemoteException e) {
1874 // Ignore
1875 } finally {
1876 Binder.restoreCallingIdentity(ident);
1877 }
1878
Michael Chane96440f2009-05-06 10:27:36 -07001879 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1881 setTimeoutLocked(time, SCREEN_BRIGHT);
1882 }
1883 }
1884 }
1885 }
1886
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001887 private int getAutoBrightnessValue(int sensorValue, int[] values) {
1888 try {
1889 int i;
1890 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
1891 if (sensorValue < mAutoBrightnessLevels[i]) {
1892 break;
1893 }
1894 }
1895 return values[i];
1896 } catch (Exception e) {
1897 // guard against null pointer or index out of bounds errors
1898 Log.e(TAG, "getAutoBrightnessValue", e);
1899 return 255;
1900 }
1901 }
1902
1903 private Runnable mAutoBrightnessTask = new Runnable() {
1904 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04001905 synchronized (mLocks) {
1906 int value = (int)mLightSensorPendingValue;
1907 if (value >= 0) {
1908 mLightSensorPendingValue = -1;
1909 lightSensorChangedLocked(value);
1910 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001911 }
1912 }
1913 };
1914
1915 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001916 if (mDebugLightSensor) {
1917 Log.d(TAG, "lightSensorChangedLocked " + value);
1918 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001919
1920 if (mLightSensorValue != value) {
1921 mLightSensorValue = value;
1922 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
1923 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
1924 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
1925 int keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
1926 mLightSensorBrightness = lcdValue;
1927
1928 if (mDebugLightSensor) {
1929 Log.d(TAG, "lcdValue " + lcdValue);
1930 Log.d(TAG, "buttonValue " + buttonValue);
1931 Log.d(TAG, "keyboardValue " + keyboardValue);
1932 }
1933
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001934 boolean startAnimation = false;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001935 if (mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001936 if (ANIMATE_SCREEN_LIGHTS) {
1937 if (mScreenBrightness.setTargetLocked(lcdValue,
1938 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
1939 (int)mScreenBrightness.curValue)) {
1940 startAnimation = true;
1941 }
1942 } else {
1943 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT,
1944 lcdValue);
1945 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001946 }
1947 if (ANIMATE_BUTTON_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001948 if (mButtonBrightness.setTargetLocked(buttonValue,
1949 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1950 (int)mButtonBrightness.curValue)) {
1951 startAnimation = true;
1952 }
1953 } else {
1954 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS,
1955 buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001956 }
1957 if (ANIMATE_KEYBOARD_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001958 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
1959 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1960 (int)mKeyboardBrightness.curValue)) {
1961 startAnimation = true;
1962 }
1963 } else {
1964 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
1965 keyboardValue);
1966 }
1967 if (startAnimation) {
1968 if (mDebugLightSensor) {
1969 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
1970 }
1971 mHandler.removeCallbacks(mLightAnimator);
1972 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001973 }
1974 }
1975 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001976 }
1977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 /**
1979 * The user requested that we go to sleep (probably with the power button).
1980 * This overrides all wake locks that are held.
1981 */
1982 public void goToSleep(long time)
1983 {
1984 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1985 synchronized (mLocks) {
1986 goToSleepLocked(time);
1987 }
1988 }
1989
1990 /**
1991 * Returns the time the screen has been on since boot, in millis.
1992 * @return screen on time
1993 */
1994 public long getScreenOnTime() {
1995 synchronized (mLocks) {
1996 if (mScreenOnStartTime == 0) {
1997 return mScreenOnTime;
1998 } else {
1999 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
2000 }
2001 }
2002 }
2003
2004 private void goToSleepLocked(long time) {
2005
2006 if (mLastEventTime <= time) {
2007 mLastEventTime = time;
2008 // cancel all of the wake locks
2009 mWakeLockState = SCREEN_OFF;
2010 int N = mLocks.size();
2011 int numCleared = 0;
2012 for (int i=0; i<N; i++) {
2013 WakeLock wl = mLocks.get(i);
2014 if (isScreenLock(wl.flags)) {
2015 mLocks.get(i).activated = false;
2016 numCleared++;
2017 }
2018 }
2019 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002020 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 mUserState = SCREEN_OFF;
2022 setPowerState(SCREEN_OFF, false, true);
2023 cancelTimerLocked();
2024 }
2025 }
2026
2027 public long timeSinceScreenOn() {
2028 synchronized (mLocks) {
2029 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2030 return 0;
2031 }
2032 return SystemClock.elapsedRealtime() - mScreenOffTime;
2033 }
2034 }
2035
2036 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002037 synchronized (mLocks) {
2038 if (mSpew) {
2039 Log.d(TAG, "setKeyboardVisibility: " + visible);
2040 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002041 if (mKeyboardVisible != visible) {
2042 mKeyboardVisible = visible;
2043 // don't signal user activity if the screen is off; other code
2044 // will take care of turning on due to a true change to the lid
2045 // switch and synchronized with the lock screen.
2046 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2047 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2048 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002049 }
2050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 }
2052
2053 /**
2054 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
2055 */
2056 public void enableUserActivity(boolean enabled) {
2057 synchronized (mLocks) {
2058 mUserActivityAllowed = enabled;
2059 mLastEventTime = SystemClock.uptimeMillis(); // we might need to pass this in
2060 }
2061 }
2062
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002063 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002064 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2065 if (mAutoBrightessEnabled != enabled) {
2066 mAutoBrightessEnabled = enabled;
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002067
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002068 if (mUseHardwareAutoBrightness) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002069 // When setting auto-brightness, must reset the brightness afterwards
2070 mHardware.setAutoBrightness_UNCHECKED(enabled);
2071 if (screenIsOn()) {
2072 setBacklightBrightness((int)mScreenBrightness.curValue);
2073 }
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002074 } else if (mUseSoftwareAutoBrightness) {
2075 // reset computed brightness
2076 mLightSensorValue = -1;
2077 mLightSensorBrightness = -1;
Mike Lockwood2d155d22009-10-27 09:32:30 -04002078 enableLightSensor(screenIsOn() && enabled);
2079 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002080 }
2081 }
2082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 /** Sets the screen off timeouts:
2084 * mKeylightDelay
2085 * mDimDelay
2086 * mScreenOffDelay
2087 * */
2088 private void setScreenOffTimeoutsLocked() {
2089 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
2090 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
2091 mDimDelay = -1;
2092 mScreenOffDelay = 0;
2093 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2094 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2095 mDimDelay = -1;
2096 mScreenOffDelay = 0;
2097 } else {
2098 int totalDelay = mTotalDelaySetting;
2099 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2100 if (totalDelay < 0) {
2101 mScreenOffDelay = Integer.MAX_VALUE;
2102 } else if (mKeylightDelay < totalDelay) {
2103 // subtract the time that the keylight delay. This will give us the
2104 // remainder of the time that we need to sleep to get the accurate
2105 // screen off timeout.
2106 mScreenOffDelay = totalDelay - mKeylightDelay;
2107 } else {
2108 mScreenOffDelay = 0;
2109 }
2110 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2111 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2112 mScreenOffDelay = LONG_DIM_TIME;
2113 } else {
2114 mDimDelay = -1;
2115 }
2116 }
2117 if (mSpew) {
2118 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2119 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2120 + " mDimScreen=" + mDimScreen);
2121 }
2122 }
2123
2124 /**
2125 * Refreshes cached Gservices settings. Called once on startup, and
2126 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
2127 * GservicesChangedReceiver).
2128 */
2129 private void updateGservicesValues() {
2130 mShortKeylightDelay = Settings.Gservices.getInt(
2131 mContext.getContentResolver(),
2132 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
2133 SHORT_KEYLIGHT_DELAY_DEFAULT);
2134 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
2135 }
2136
2137 /**
2138 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
2139 * which tells us we need to refresh our cached Gservices settings.
2140 */
2141 private class GservicesChangedReceiver extends BroadcastReceiver {
2142 @Override
2143 public void onReceive(Context context, Intent intent) {
2144 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
2145 updateGservicesValues();
2146 }
2147 }
2148
2149 private class LockList extends ArrayList<WakeLock>
2150 {
2151 void addLock(WakeLock wl)
2152 {
2153 int index = getIndex(wl.binder);
2154 if (index < 0) {
2155 this.add(wl);
2156 }
2157 }
2158
2159 WakeLock removeLock(IBinder binder)
2160 {
2161 int index = getIndex(binder);
2162 if (index >= 0) {
2163 return this.remove(index);
2164 } else {
2165 return null;
2166 }
2167 }
2168
2169 int getIndex(IBinder binder)
2170 {
2171 int N = this.size();
2172 for (int i=0; i<N; i++) {
2173 if (this.get(i).binder == binder) {
2174 return i;
2175 }
2176 }
2177 return -1;
2178 }
2179
2180 int gatherState()
2181 {
2182 int result = 0;
2183 int N = this.size();
2184 for (int i=0; i<N; i++) {
2185 WakeLock wl = this.get(i);
2186 if (wl.activated) {
2187 if (isScreenLock(wl.flags)) {
2188 result |= wl.minState;
2189 }
2190 }
2191 }
2192 return result;
2193 }
Michael Chane96440f2009-05-06 10:27:36 -07002194
2195 int reactivateScreenLocksLocked()
2196 {
2197 int result = 0;
2198 int N = this.size();
2199 for (int i=0; i<N; i++) {
2200 WakeLock wl = this.get(i);
2201 if (isScreenLock(wl.flags)) {
2202 wl.activated = true;
2203 result |= wl.minState;
2204 }
2205 }
2206 return result;
2207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 }
2209
2210 void setPolicy(WindowManagerPolicy p) {
2211 synchronized (mLocks) {
2212 mPolicy = p;
2213 mLocks.notifyAll();
2214 }
2215 }
2216
2217 WindowManagerPolicy getPolicyLocked() {
2218 while (mPolicy == null || !mDoneBooting) {
2219 try {
2220 mLocks.wait();
2221 } catch (InterruptedException e) {
2222 // Ignore
2223 }
2224 }
2225 return mPolicy;
2226 }
2227
2228 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002229 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2230 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2231 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002232 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002233 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
2234 enableLightSensor(mAutoBrightessEnabled);
2235 }
2236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 synchronized (mLocks) {
2238 Log.d(TAG, "system ready!");
2239 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002240 long identity = Binder.clearCallingIdentity();
2241 try {
2242 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2243 mBatteryStats.noteScreenOn();
2244 } catch (RemoteException e) {
2245 // Nothing interesting to do.
2246 } finally {
2247 Binder.restoreCallingIdentity(identity);
2248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2250 updateWakeLockLocked();
2251 mLocks.notifyAll();
2252 }
2253 }
2254
2255 public void monitor() {
2256 synchronized (mLocks) { }
2257 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002258
2259 public int getSupportedWakeLockFlags() {
2260 int result = PowerManager.PARTIAL_WAKE_LOCK
2261 | PowerManager.FULL_WAKE_LOCK
2262 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2263
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002264 if (mProximitySensor != null) {
2265 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2266 }
2267
2268 return result;
2269 }
2270
Mike Lockwood237a2992009-09-15 14:42:16 -04002271 public void setBacklightBrightness(int brightness) {
2272 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2273 // Don't let applications turn the screen all the way off
2274 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2275 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness);
2276 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, brightness);
2277 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness);
2278 long identity = Binder.clearCallingIdentity();
2279 try {
2280 mBatteryStats.noteScreenBrightness(brightness);
2281 } catch (RemoteException e) {
2282 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2283 } finally {
2284 Binder.restoreCallingIdentity(identity);
2285 }
2286
2287 // update our animation state
2288 if (ANIMATE_SCREEN_LIGHTS) {
2289 mScreenBrightness.curValue = brightness;
2290 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002291 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002292 }
2293 if (ANIMATE_KEYBOARD_LIGHTS) {
2294 mKeyboardBrightness.curValue = brightness;
2295 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002296 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002297 }
2298 if (ANIMATE_BUTTON_LIGHTS) {
2299 mButtonBrightness.curValue = brightness;
2300 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002301 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002302 }
2303 }
2304
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002305 private void enableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002306 if (mSpew) {
2307 Log.d(TAG, "enableProximityLockLocked");
2308 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002309 // clear calling identity so sensor manager battery stats are accurate
2310 long identity = Binder.clearCallingIdentity();
2311 try {
2312 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2313 SensorManager.SENSOR_DELAY_NORMAL);
2314 } finally {
2315 Binder.restoreCallingIdentity(identity);
2316 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002317 }
2318
2319 private void disableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002320 if (mSpew) {
2321 Log.d(TAG, "disableProximityLockLocked");
2322 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002323 // clear calling identity so sensor manager battery stats are accurate
2324 long identity = Binder.clearCallingIdentity();
2325 try {
2326 mSensorManager.unregisterListener(mProximityListener);
2327 } finally {
2328 Binder.restoreCallingIdentity(identity);
2329 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002330 synchronized (mLocks) {
2331 if (mProximitySensorActive) {
2332 mProximitySensorActive = false;
2333 forceUserActivityLocked();
2334 }
2335 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002336 }
2337
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002338 private void enableLightSensor(boolean enable) {
2339 if (mDebugLightSensor) {
2340 Log.d(TAG, "enableLightSensor " + enable);
2341 }
2342 if (mSensorManager != null && mLightSensorEnabled != enable) {
2343 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002344 // clear calling identity so sensor manager battery stats are accurate
2345 long identity = Binder.clearCallingIdentity();
2346 try {
2347 if (enable) {
2348 mSensorManager.registerListener(mLightListener, mLightSensor,
2349 SensorManager.SENSOR_DELAY_NORMAL);
2350 } else {
2351 mSensorManager.unregisterListener(mLightListener);
2352 mHandler.removeCallbacks(mAutoBrightnessTask);
2353 }
2354 } finally {
2355 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002356 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002357 }
2358 }
2359
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002360 SensorEventListener mProximityListener = new SensorEventListener() {
2361 public void onSensorChanged(SensorEvent event) {
2362 long milliseconds = event.timestamp / 1000000;
2363 synchronized (mLocks) {
2364 float distance = event.values[0];
2365 // compare against getMaximumRange to support sensors that only return 0 or 1
2366 if (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2367 distance < mProximitySensor.getMaximumRange()) {
2368 if (mSpew) {
2369 Log.d(TAG, "onSensorChanged: proximity active, distance: " + distance);
2370 }
2371 goToSleepLocked(milliseconds);
2372 mProximitySensorActive = true;
2373 } else {
2374 // proximity sensor negative events trigger as user activity.
2375 // temporarily set mUserActivityAllowed to true so this will work
2376 // even when the keyguard is on.
2377 if (mSpew) {
2378 Log.d(TAG, "onSensorChanged: proximity inactive, distance: " + distance);
2379 }
2380 mProximitySensorActive = false;
2381 forceUserActivityLocked();
2382 }
2383 }
2384 }
2385
2386 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2387 // ignore
2388 }
2389 };
2390
2391 SensorEventListener mLightListener = new SensorEventListener() {
2392 public void onSensorChanged(SensorEvent event) {
2393 synchronized (mLocks) {
2394 int value = (int)event.values[0];
2395 if (mDebugLightSensor) {
2396 Log.d(TAG, "onSensorChanged: light value: " + value);
2397 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002398 mHandler.removeCallbacks(mAutoBrightnessTask);
2399 if (mLightSensorValue != value) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002400 if (mLightSensorValue == -1) {
2401 // process the value immediately
2402 lightSensorChangedLocked(value);
2403 } else {
2404 // delay processing to debounce the sensor
2405 mLightSensorPendingValue = value;
2406 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2407 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002408 } else {
2409 mLightSensorPendingValue = -1;
2410 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002411 }
2412 }
2413
2414 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2415 // ignore
2416 }
2417 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418}