blob: 8a7c28fc1fc173c25b3b0335abd364845502cefb [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;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700215 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700216 private int[] mAutoBrightnessLevels;
217 private int[] mLcdBacklightValues;
218 private int[] mButtonBacklightValues;
219 private int[] mKeyboardBacklightValues;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220
Mike Lockwood9efd5232009-11-01 10:05:50 -0500221 /*
222 * WARNING - DO NOT USE THE HARDWARE AUTO-BRIGHTNESS FEATURE
223 * Hardware auto brightness support is deprecated and will be removed in the next release.
224 */
225 private boolean mUseHardwareAutoBrightness;
226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 // Used when logging number and duration of touch-down cycles
228 private long mTotalTouchDownTime;
229 private long mLastTouchDown;
230 private int mTouchCycles;
231
232 // could be either static or controllable at runtime
233 private static final boolean mSpew = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400234 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235
236 /*
237 static PrintStream mLog;
238 static {
239 try {
240 mLog = new PrintStream("/data/power.log");
241 }
242 catch (FileNotFoundException e) {
243 android.util.Log.e(TAG, "Life is hard", e);
244 }
245 }
246 static class Log {
247 static void d(String tag, String s) {
248 mLog.println(s);
249 android.util.Log.d(tag, s);
250 }
251 static void i(String tag, String s) {
252 mLog.println(s);
253 android.util.Log.i(tag, s);
254 }
255 static void w(String tag, String s) {
256 mLog.println(s);
257 android.util.Log.w(tag, s);
258 }
259 static void e(String tag, String s) {
260 mLog.println(s);
261 android.util.Log.e(tag, s);
262 }
263 }
264 */
265
266 /**
267 * This class works around a deadlock between the lock in PowerManager.WakeLock
268 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
269 * mToken object so it can be accessed from any thread, but it calls into here
270 * with its lock held. This class is essentially a reimplementation of
271 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
272 * only call it with our own locks held.
273 */
274 private class UnsynchronizedWakeLock {
275 int mFlags;
276 String mTag;
277 IBinder mToken;
278 int mCount = 0;
279 boolean mRefCounted;
280
281 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
282 mFlags = flags;
283 mTag = tag;
284 mToken = new Binder();
285 mRefCounted = refCounted;
286 }
287
288 public void acquire() {
289 if (!mRefCounted || mCount++ == 0) {
290 long ident = Binder.clearCallingIdentity();
291 try {
292 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
293 MY_UID, mTag);
294 } finally {
295 Binder.restoreCallingIdentity(ident);
296 }
297 }
298 }
299
300 public void release() {
301 if (!mRefCounted || --mCount == 0) {
302 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
303 }
304 if (mCount < 0) {
305 throw new RuntimeException("WakeLock under-locked " + mTag);
306 }
307 }
308
309 public String toString() {
310 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
311 + " mCount=" + mCount + ")";
312 }
313 }
314
315 private final class BatteryReceiver extends BroadcastReceiver {
316 @Override
317 public void onReceive(Context context, Intent intent) {
318 synchronized (mLocks) {
319 boolean wasPowered = mIsPowered;
320 mIsPowered = mBatteryService.isPowered();
321
322 if (mIsPowered != wasPowered) {
323 // update mStayOnWhilePluggedIn wake lock
324 updateWakeLockLocked();
325
326 // treat plugging and unplugging the devices as a user activity.
327 // users find it disconcerting when they unplug the device
328 // and it shuts off right away.
329 // temporarily set mUserActivityAllowed to true so this will work
330 // even when the keyguard is on.
331 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400332 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 }
334 }
335 }
336 }
337 }
338
339 /**
340 * Set the setting that determines whether the device stays on when plugged in.
341 * The argument is a bit string, with each bit specifying a power source that,
342 * when the device is connected to that source, causes the device to stay on.
343 * See {@link android.os.BatteryManager} for the list of power sources that
344 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
345 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
346 * @param val an {@code int} containing the bits that specify which power sources
347 * should cause the device to stay on.
348 */
349 public void setStayOnSetting(int val) {
350 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
351 Settings.System.putInt(mContext.getContentResolver(),
352 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
353 }
354
355 private class SettingsObserver implements Observer {
356 private int getInt(String name) {
357 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
358 }
359
360 public void update(Observable o, Object arg) {
361 synchronized (mLocks) {
362 // STAY_ON_WHILE_PLUGGED_IN
363 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
364 updateWakeLockLocked();
365
366 // SCREEN_OFF_TIMEOUT
367 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
368
369 // DIM_SCREEN
370 //mDimScreen = getInt(DIM_SCREEN) != 0;
371
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700372 // SCREEN_BRIGHTNESS_MODE
373 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 // recalculate everything
376 setScreenOffTimeoutsLocked();
377 }
378 }
379 }
380
381 PowerManagerService()
382 {
383 // Hack to get our uid... should have a func for this.
384 long token = Binder.clearCallingIdentity();
385 MY_UID = Binder.getCallingUid();
386 Binder.restoreCallingIdentity(token);
387
388 // XXX remove this when the kernel doesn't timeout wake locks
389 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
390
391 // assume nothing is on yet
392 mUserState = mPowerState = 0;
393
394 // Add ourself to the Watchdog monitors.
395 Watchdog.getInstance().addMonitor(this);
396 mScreenOnStartTime = SystemClock.elapsedRealtime();
397 }
398
399 private ContentQueryMap mSettings;
400
The Android Open Source Project10592532009-03-18 17:39:46 -0700401 void init(Context context, HardwareService hardware, IActivityManager activity,
402 BatteryService battery) {
403 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 mContext = context;
405 mActivityService = activity;
406 mBatteryStats = BatteryStatsService.getService();
407 mBatteryService = battery;
408
409 mHandlerThread = new HandlerThread("PowerManagerService") {
410 @Override
411 protected void onLooperPrepared() {
412 super.onLooperPrepared();
413 initInThread();
414 }
415 };
416 mHandlerThread.start();
417
418 synchronized (mHandlerThread) {
419 while (!mInitComplete) {
420 try {
421 mHandlerThread.wait();
422 } catch (InterruptedException e) {
423 // Ignore
424 }
425 }
426 }
427 }
428
429 void initInThread() {
430 mHandler = new Handler();
431
432 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700433 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
435 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
436 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
437 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
438 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
439 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
440
441 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
442 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
443 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
444 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
445
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700446 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400447
448 // read settings for auto-brightness
449 mUseSoftwareAutoBrightness = resources.getBoolean(
450 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwood9efd5232009-11-01 10:05:50 -0500451
452 /*
453 * WARNING - DO NOT USE THE HARDWARE AUTO-BRIGHTNESS FEATURE
454 * Hardware auto brightness support is deprecated and will be removed in the next release.
455 */
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400456 mUseHardwareAutoBrightness = resources.getBoolean(
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700457 com.android.internal.R.bool.config_hardware_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400458 if (mUseHardwareAutoBrightness) {
459 mUseSoftwareAutoBrightness = false;
460 }
Mike Lockwood9efd5232009-11-01 10:05:50 -0500461
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400462 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700463 mAutoBrightnessLevels = resources.getIntArray(
464 com.android.internal.R.array.config_autoBrightnessLevels);
465 mLcdBacklightValues = resources.getIntArray(
466 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
467 mButtonBacklightValues = resources.getIntArray(
468 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
469 mKeyboardBacklightValues = resources.getIntArray(
470 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
471 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700472
473 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
475 "(" + Settings.System.NAME + "=?) or ("
476 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700477 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700479 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
480 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 null);
482 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
483 SettingsObserver settingsObserver = new SettingsObserver();
484 mSettings.addObserver(settingsObserver);
485
486 // pretend that the settings changed so we will get their initial state
487 settingsObserver.update(mSettings, null);
488
489 // register for the battery changed notifications
490 IntentFilter filter = new IntentFilter();
491 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
492 mContext.registerReceiver(new BatteryReceiver(), filter);
493
494 // Listen for Gservices changes
495 IntentFilter gservicesChangedFilter =
496 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
497 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
498 // And explicitly do the initial update of our cached settings
499 updateGservicesValues();
500
Mike Lockwood4984e732009-11-01 08:16:33 -0500501 if (mUseSoftwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400502 // turn the screen on
503 setPowerState(SCREEN_BRIGHT);
504 } else {
505 // turn everything on
506 setPowerState(ALL_BRIGHT);
507 }
Dan Murphy951764b2009-08-27 14:59:03 -0500508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 synchronized (mHandlerThread) {
510 mInitComplete = true;
511 mHandlerThread.notifyAll();
512 }
513 }
514
515 private class WakeLock implements IBinder.DeathRecipient
516 {
517 WakeLock(int f, IBinder b, String t, int u) {
518 super();
519 flags = f;
520 binder = b;
521 tag = t;
522 uid = u == MY_UID ? Process.SYSTEM_UID : u;
523 if (u != MY_UID || (
524 !"KEEP_SCREEN_ON_FLAG".equals(tag)
525 && !"KeyInputQueue".equals(tag))) {
526 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
527 ? BatteryStats.WAKE_TYPE_PARTIAL
528 : BatteryStats.WAKE_TYPE_FULL;
529 } else {
530 monitorType = -1;
531 }
532 try {
533 b.linkToDeath(this, 0);
534 } catch (RemoteException e) {
535 binderDied();
536 }
537 }
538 public void binderDied() {
539 synchronized (mLocks) {
540 releaseWakeLockLocked(this.binder, true);
541 }
542 }
543 final int flags;
544 final IBinder binder;
545 final String tag;
546 final int uid;
547 final int monitorType;
548 boolean activated = true;
549 int minState;
550 }
551
552 private void updateWakeLockLocked() {
553 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
554 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
555 mStayOnWhilePluggedInScreenDimLock.acquire();
556 mStayOnWhilePluggedInPartialLock.acquire();
557 } else {
558 mStayOnWhilePluggedInScreenDimLock.release();
559 mStayOnWhilePluggedInPartialLock.release();
560 }
561 }
562
563 private boolean isScreenLock(int flags)
564 {
565 int n = flags & LOCK_MASK;
566 return n == PowerManager.FULL_WAKE_LOCK
567 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
568 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
569 }
570
571 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700573 if (uid != Process.myUid()) {
574 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 long ident = Binder.clearCallingIdentity();
577 try {
578 synchronized (mLocks) {
579 acquireWakeLockLocked(flags, lock, uid, tag);
580 }
581 } finally {
582 Binder.restoreCallingIdentity(ident);
583 }
584 }
585
586 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
587 int acquireUid = -1;
588 String acquireName = null;
589 int acquireType = -1;
590
591 if (mSpew) {
592 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
593 }
594
595 int index = mLocks.getIndex(lock);
596 WakeLock wl;
597 boolean newlock;
598 if (index < 0) {
599 wl = new WakeLock(flags, lock, tag, uid);
600 switch (wl.flags & LOCK_MASK)
601 {
602 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500603 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400604 wl.minState = SCREEN_BRIGHT;
605 } else {
606 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 break;
609 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
610 wl.minState = SCREEN_BRIGHT;
611 break;
612 case PowerManager.SCREEN_DIM_WAKE_LOCK:
613 wl.minState = SCREEN_DIM;
614 break;
615 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700616 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 break;
618 default:
619 // just log and bail. we're in the server, so don't
620 // throw an exception.
621 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
622 + " flags=" + flags);
623 return;
624 }
625 mLocks.addLock(wl);
626 newlock = true;
627 } else {
628 wl = mLocks.get(index);
629 newlock = false;
630 }
631 if (isScreenLock(flags)) {
632 // if this causes a wakeup, we reactivate all of the locks and
633 // set it to whatever they want. otherwise, we modulate that
634 // by the current state so we never turn it more on than
635 // it already is.
636 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700637 int oldWakeLockState = mWakeLockState;
638 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 if (mSpew) {
640 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700641 + " mWakeLockState=0x"
642 + Integer.toHexString(mWakeLockState)
643 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 } else {
646 if (mSpew) {
647 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
648 + " mLocks.gatherState()=0x"
649 + Integer.toHexString(mLocks.gatherState())
650 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
651 }
652 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
653 }
654 setPowerState(mWakeLockState | mUserState);
655 }
656 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
657 if (newlock) {
658 mPartialCount++;
659 if (mPartialCount == 1) {
660 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
661 }
662 }
663 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700664 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
665 mProximityCount++;
666 if (mProximityCount == 1) {
667 enableProximityLockLocked();
668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 }
670 if (newlock) {
671 acquireUid = wl.uid;
672 acquireName = wl.tag;
673 acquireType = wl.monitorType;
674 }
675
676 if (acquireType >= 0) {
677 try {
678 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
679 } catch (RemoteException e) {
680 // Ignore
681 }
682 }
683 }
684
685 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700686 int uid = Binder.getCallingUid();
687 if (uid != Process.myUid()) {
688 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690
691 synchronized (mLocks) {
692 releaseWakeLockLocked(lock, false);
693 }
694 }
695
696 private void releaseWakeLockLocked(IBinder lock, boolean death) {
697 int releaseUid;
698 String releaseName;
699 int releaseType;
700
701 WakeLock wl = mLocks.removeLock(lock);
702 if (wl == null) {
703 return;
704 }
705
706 if (mSpew) {
707 Log.d(TAG, "releaseWakeLock flags=0x"
708 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
709 }
710
711 if (isScreenLock(wl.flags)) {
712 mWakeLockState = mLocks.gatherState();
713 // goes in the middle to reduce flicker
714 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
715 userActivity(SystemClock.uptimeMillis(), false);
716 }
717 setPowerState(mWakeLockState | mUserState);
718 }
719 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
720 mPartialCount--;
721 if (mPartialCount == 0) {
722 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
723 Power.releaseWakeLock(PARTIAL_NAME);
724 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700725 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
726 mProximityCount--;
727 if (mProximityCount == 0) {
728 disableProximityLockLocked();
729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 }
731 // Unlink the lock from the binder.
732 wl.binder.unlinkToDeath(wl, 0);
733 releaseUid = wl.uid;
734 releaseName = wl.tag;
735 releaseType = wl.monitorType;
736
737 if (releaseType >= 0) {
738 long origId = Binder.clearCallingIdentity();
739 try {
740 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
741 } catch (RemoteException e) {
742 // Ignore
743 } finally {
744 Binder.restoreCallingIdentity(origId);
745 }
746 }
747 }
748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 private class PokeLock implements IBinder.DeathRecipient
750 {
751 PokeLock(int p, IBinder b, String t) {
752 super();
753 this.pokey = p;
754 this.binder = b;
755 this.tag = t;
756 try {
757 b.linkToDeath(this, 0);
758 } catch (RemoteException e) {
759 binderDied();
760 }
761 }
762 public void binderDied() {
763 setPokeLock(0, this.binder, this.tag);
764 }
765 int pokey;
766 IBinder binder;
767 String tag;
768 boolean awakeOnSet;
769 }
770
771 public void setPokeLock(int pokey, IBinder token, String tag) {
772 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
773 if (token == null) {
774 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
775 return;
776 }
777
778 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
779 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
780 + " and POKE_LOCK_MEDIUM_TIMEOUT");
781 }
782
783 synchronized (mLocks) {
784 if (pokey != 0) {
785 PokeLock p = mPokeLocks.get(token);
786 int oldPokey = 0;
787 if (p != null) {
788 oldPokey = p.pokey;
789 p.pokey = pokey;
790 } else {
791 p = new PokeLock(pokey, token, tag);
792 mPokeLocks.put(token, p);
793 }
794 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
795 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
796 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
797 p.awakeOnSet = true;
798 }
799 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700800 PokeLock rLock = mPokeLocks.remove(token);
801 if (rLock != null) {
802 token.unlinkToDeath(rLock, 0);
803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 }
805
806 int oldPokey = mPokey;
807 int cumulative = 0;
808 boolean oldAwakeOnSet = mPokeAwakeOnSet;
809 boolean awakeOnSet = false;
810 for (PokeLock p: mPokeLocks.values()) {
811 cumulative |= p.pokey;
812 if (p.awakeOnSet) {
813 awakeOnSet = true;
814 }
815 }
816 mPokey = cumulative;
817 mPokeAwakeOnSet = awakeOnSet;
818
819 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
820 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
821
822 if (oldCumulativeTimeout != newCumulativeTimeout) {
823 setScreenOffTimeoutsLocked();
824 // reset the countdown timer, but use the existing nextState so it doesn't
825 // change anything
826 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
827 }
828 }
829 }
830
831 private static String lockType(int type)
832 {
833 switch (type)
834 {
835 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700836 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700838 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700840 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700842 return "PARTIAL_WAKE_LOCK ";
843 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
844 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 default:
David Brown251faa62009-08-02 22:04:36 -0700846 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 }
848 }
849
850 private static String dumpPowerState(int state) {
851 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
852 ? "KEYBOARD_BRIGHT_BIT " : "")
853 + (((state & SCREEN_BRIGHT_BIT) != 0)
854 ? "SCREEN_BRIGHT_BIT " : "")
855 + (((state & SCREEN_ON_BIT) != 0)
856 ? "SCREEN_ON_BIT " : "")
857 + (((state & BATTERY_LOW_BIT) != 0)
858 ? "BATTERY_LOW_BIT " : "");
859 }
860
861 @Override
862 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
863 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
864 != PackageManager.PERMISSION_GRANTED) {
865 pw.println("Permission Denial: can't dump PowerManager from from pid="
866 + Binder.getCallingPid()
867 + ", uid=" + Binder.getCallingUid());
868 return;
869 }
870
871 long now = SystemClock.uptimeMillis();
872
873 pw.println("Power Manager State:");
874 pw.println(" mIsPowered=" + mIsPowered
875 + " mPowerState=" + mPowerState
876 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
877 + " ms");
878 pw.println(" mPartialCount=" + mPartialCount);
879 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
880 pw.println(" mUserState=" + dumpPowerState(mUserState));
881 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
882 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
883 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
884 + " " + ((mNextTimeout-now)/1000) + "s from now");
885 pw.println(" mDimScreen=" + mDimScreen
886 + " mStayOnConditions=" + mStayOnConditions);
887 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
888 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700889 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
890 + ',' + mBroadcastQueue[2] + "}");
891 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
892 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
894 pw.println(" mKeyboardVisible=" + mKeyboardVisible
895 + " mUserActivityAllowed=" + mUserActivityAllowed);
896 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
897 + " mScreenOffDelay=" + mScreenOffDelay);
898 pw.println(" mPreventScreenOn=" + mPreventScreenOn
899 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
900 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
901 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
902 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
903 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
904 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700905 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
906 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
907 pw.println(" mLightSensorValue=" + mLightSensorValue);
908 pw.println(" mLightSensorPendingValue=" + mLightSensorPendingValue);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400909 pw.println(" mUseHardwareAutoBrightness=" + mUseHardwareAutoBrightness);
910 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700911 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 mScreenBrightness.dump(pw, " mScreenBrightness: ");
913 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
914 mButtonBrightness.dump(pw, " mButtonBrightness: ");
915
916 int N = mLocks.size();
917 pw.println();
918 pw.println("mLocks.size=" + N + ":");
919 for (int i=0; i<N; i++) {
920 WakeLock wl = mLocks.get(i);
921 String type = lockType(wl.flags & LOCK_MASK);
922 String acquireCausesWakeup = "";
923 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
924 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
925 }
926 String activated = "";
927 if (wl.activated) {
928 activated = " activated";
929 }
930 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
931 + activated + " (minState=" + wl.minState + ")");
932 }
933
934 pw.println();
935 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
936 for (PokeLock p: mPokeLocks.values()) {
937 pw.println(" poke lock '" + p.tag + "':"
938 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
939 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700940 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
941 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
943 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
944 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
945 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
946 }
947
948 pw.println();
949 }
950
951 private void setTimeoutLocked(long now, int nextState)
952 {
953 if (mDoneBooting) {
954 mHandler.removeCallbacks(mTimeoutTask);
955 mTimeoutTask.nextState = nextState;
956 long when = now;
957 switch (nextState)
958 {
959 case SCREEN_BRIGHT:
960 when += mKeylightDelay;
961 break;
962 case SCREEN_DIM:
963 if (mDimDelay >= 0) {
964 when += mDimDelay;
965 break;
966 } else {
967 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
968 }
969 case SCREEN_OFF:
970 synchronized (mLocks) {
971 when += mScreenOffDelay;
972 }
973 break;
974 }
975 if (mSpew) {
976 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
977 + " when=" + when);
978 }
979 mHandler.postAtTime(mTimeoutTask, when);
980 mNextTimeout = when; // for debugging
981 }
982 }
983
984 private void cancelTimerLocked()
985 {
986 mHandler.removeCallbacks(mTimeoutTask);
987 mTimeoutTask.nextState = -1;
988 }
989
990 private class TimeoutTask implements Runnable
991 {
992 int nextState; // access should be synchronized on mLocks
993 public void run()
994 {
995 synchronized (mLocks) {
996 if (mSpew) {
997 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
998 }
999
1000 if (nextState == -1) {
1001 return;
1002 }
1003
1004 mUserState = this.nextState;
1005 setPowerState(this.nextState | mWakeLockState);
1006
1007 long now = SystemClock.uptimeMillis();
1008
1009 switch (this.nextState)
1010 {
1011 case SCREEN_BRIGHT:
1012 if (mDimDelay >= 0) {
1013 setTimeoutLocked(now, SCREEN_DIM);
1014 break;
1015 }
1016 case SCREEN_DIM:
1017 setTimeoutLocked(now, SCREEN_OFF);
1018 break;
1019 }
1020 }
1021 }
1022 }
1023
1024 private void sendNotificationLocked(boolean on, int why)
1025 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001026 if (!on) {
1027 mStillNeedSleepNotification = false;
1028 }
1029
Joe Onorato128e7292009-03-24 18:41:31 -07001030 // Add to the queue.
1031 int index = 0;
1032 while (mBroadcastQueue[index] != -1) {
1033 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 }
Joe Onorato128e7292009-03-24 18:41:31 -07001035 mBroadcastQueue[index] = on ? 1 : 0;
1036 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037
Joe Onorato128e7292009-03-24 18:41:31 -07001038 // If we added it position 2, then there is a pair that can be stripped.
1039 // If we added it position 1 and we're turning the screen off, we can strip
1040 // the pair and do nothing, because the screen is already off, and therefore
1041 // keyguard has already been enabled.
1042 // However, if we added it at position 1 and we're turning it on, then position
1043 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1044 // on, so have to run the queue then.
1045 if (index == 2) {
1046 // Also, while we're collapsing them, if it's going to be an "off," and one
1047 // is off because of user, then use that, regardless of whether it's the first
1048 // or second one.
1049 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
1050 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
1051 }
1052 mBroadcastQueue[0] = on ? 1 : 0;
1053 mBroadcastQueue[1] = -1;
1054 mBroadcastQueue[2] = -1;
1055 index = 0;
1056 }
1057 if (index == 1 && !on) {
1058 mBroadcastQueue[0] = -1;
1059 mBroadcastQueue[1] = -1;
1060 index = -1;
1061 // The wake lock was being held, but we're not actually going to do any
1062 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1064 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001065 }
1066
1067 // Now send the message.
1068 if (index >= 0) {
1069 // Acquire the broadcast wake lock before changing the power
1070 // state. It will be release after the broadcast is sent.
1071 // We always increment the ref count for each notification in the queue
1072 // and always decrement when that notification is handled.
1073 mBroadcastWakeLock.acquire();
1074 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1075 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 }
1077 }
1078
1079 private Runnable mNotificationTask = new Runnable()
1080 {
1081 public void run()
1082 {
Joe Onorato128e7292009-03-24 18:41:31 -07001083 while (true) {
1084 int value;
1085 int why;
1086 WindowManagerPolicy policy;
1087 synchronized (mLocks) {
1088 value = mBroadcastQueue[0];
1089 why = mBroadcastWhy[0];
1090 for (int i=0; i<2; i++) {
1091 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1092 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1093 }
1094 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 }
Joe Onorato128e7292009-03-24 18:41:31 -07001096 if (value == 1) {
1097 mScreenOnStart = SystemClock.uptimeMillis();
1098
1099 policy.screenTurnedOn();
1100 try {
1101 ActivityManagerNative.getDefault().wakingUp();
1102 } catch (RemoteException e) {
1103 // ignore it
1104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105
Joe Onorato128e7292009-03-24 18:41:31 -07001106 if (mSpew) {
1107 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1108 }
1109 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1110 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1111 mScreenOnBroadcastDone, mHandler, 0, null, null);
1112 } else {
1113 synchronized (mLocks) {
1114 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1115 mBroadcastWakeLock.mCount);
1116 mBroadcastWakeLock.release();
1117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 }
1119 }
Joe Onorato128e7292009-03-24 18:41:31 -07001120 else if (value == 0) {
1121 mScreenOffStart = SystemClock.uptimeMillis();
1122
1123 policy.screenTurnedOff(why);
1124 try {
1125 ActivityManagerNative.getDefault().goingToSleep();
1126 } catch (RemoteException e) {
1127 // ignore it.
1128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129
Joe Onorato128e7292009-03-24 18:41:31 -07001130 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1131 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1132 mScreenOffBroadcastDone, mHandler, 0, null, null);
1133 } else {
1134 synchronized (mLocks) {
1135 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1136 mBroadcastWakeLock.mCount);
1137 mBroadcastWakeLock.release();
1138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 }
1140 }
Joe Onorato128e7292009-03-24 18:41:31 -07001141 else {
1142 // If we're in this case, then this handler is running for a previous
1143 // paired transaction. mBroadcastWakeLock will already have been released.
1144 break;
1145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 }
1147 }
1148 };
1149
1150 long mScreenOnStart;
1151 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1152 public void onReceive(Context context, Intent intent) {
1153 synchronized (mLocks) {
1154 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1155 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1156 mBroadcastWakeLock.release();
1157 }
1158 }
1159 };
1160
1161 long mScreenOffStart;
1162 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1163 public void onReceive(Context context, Intent intent) {
1164 synchronized (mLocks) {
1165 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1166 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1167 mBroadcastWakeLock.release();
1168 }
1169 }
1170 };
1171
1172 void logPointerUpEvent() {
1173 if (LOG_TOUCH_DOWNS) {
1174 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1175 mLastTouchDown = 0;
1176 }
1177 }
1178
1179 void logPointerDownEvent() {
1180 if (LOG_TOUCH_DOWNS) {
1181 // If we are not already timing a down/up sequence
1182 if (mLastTouchDown == 0) {
1183 mLastTouchDown = SystemClock.elapsedRealtime();
1184 mTouchCycles++;
1185 }
1186 }
1187 }
1188
1189 /**
1190 * Prevents the screen from turning on even if it *should* turn on due
1191 * to a subsequent full wake lock being acquired.
1192 * <p>
1193 * This is a temporary hack that allows an activity to "cover up" any
1194 * display glitches that happen during the activity's startup
1195 * sequence. (Specifically, this API was added to work around a
1196 * cosmetic bug in the "incoming call" sequence, where the lock screen
1197 * would flicker briefly before the incoming call UI became visible.)
1198 * TODO: There ought to be a more elegant way of doing this,
1199 * probably by having the PowerManager and ActivityManager
1200 * work together to let apps specify that the screen on/off
1201 * state should be synchronized with the Activity lifecycle.
1202 * <p>
1203 * Note that calling preventScreenOn(true) will NOT turn the screen
1204 * off if it's currently on. (This API only affects *future*
1205 * acquisitions of full wake locks.)
1206 * But calling preventScreenOn(false) WILL turn the screen on if
1207 * it's currently off because of a prior preventScreenOn(true) call.
1208 * <p>
1209 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1210 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1211 * call doesn't occur within 5 seconds, we'll turn the screen back on
1212 * ourselves (and log a warning about it); this prevents a buggy app
1213 * from disabling the screen forever.)
1214 * <p>
1215 * TODO: this feature should really be controlled by a new type of poke
1216 * lock (rather than an IPowerManager call).
1217 */
1218 public void preventScreenOn(boolean prevent) {
1219 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1220
1221 synchronized (mLocks) {
1222 if (prevent) {
1223 // First of all, grab a partial wake lock to
1224 // make sure the CPU stays on during the entire
1225 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1226 mPreventScreenOnPartialLock.acquire();
1227
1228 // Post a forceReenableScreen() call (for 5 seconds in the
1229 // future) to make sure the matching preventScreenOn(false) call
1230 // has happened by then.
1231 mHandler.removeCallbacks(mForceReenableScreenTask);
1232 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1233
1234 // Finally, set the flag that prevents the screen from turning on.
1235 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001236 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 mPreventScreenOn = true;
1238 } else {
1239 // (Re)enable the screen.
1240 mPreventScreenOn = false;
1241
1242 // We're "undoing" a the prior preventScreenOn(true) call, so we
1243 // no longer need the 5-second safeguard.
1244 mHandler.removeCallbacks(mForceReenableScreenTask);
1245
1246 // Forcibly turn on the screen if it's supposed to be on. (This
1247 // handles the case where the screen is currently off because of
1248 // a prior preventScreenOn(true) call.)
1249 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1250 if (mSpew) {
1251 Log.d(TAG,
1252 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1253 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001254 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001256 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 }
1258 }
1259
1260 // Release the partial wake lock that we held during the
1261 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1262 mPreventScreenOnPartialLock.release();
1263 }
1264 }
1265 }
1266
1267 public void setScreenBrightnessOverride(int brightness) {
1268 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1269
1270 synchronized (mLocks) {
1271 if (mScreenBrightnessOverride != brightness) {
1272 mScreenBrightnessOverride = brightness;
1273 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1274 }
1275 }
1276 }
1277
1278 /**
1279 * Sanity-check that gets called 5 seconds after any call to
1280 * preventScreenOn(true). This ensures that the original call
1281 * is followed promptly by a call to preventScreenOn(false).
1282 */
1283 private void forceReenableScreen() {
1284 // We shouldn't get here at all if mPreventScreenOn is false, since
1285 // we should have already removed any existing
1286 // mForceReenableScreenTask messages...
1287 if (!mPreventScreenOn) {
1288 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1289 return;
1290 }
1291
1292 // Uh oh. It's been 5 seconds since a call to
1293 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1294 // This means the app that called preventScreenOn(true) is either
1295 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1296 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1297 // crashed before doing so.)
1298
1299 // Log a warning, and forcibly turn the screen back on.
1300 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1301 + "Forcing the screen back on...");
1302 preventScreenOn(false);
1303 }
1304
1305 private Runnable mForceReenableScreenTask = new Runnable() {
1306 public void run() {
1307 forceReenableScreen();
1308 }
1309 };
1310
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001311 private int setScreenStateLocked(boolean on) {
1312 int err = Power.setScreenState(on);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04001313 if (err == 0 && mUseSoftwareAutoBrightness) {
Mike Lockwood4984e732009-11-01 08:16:33 -05001314 enableLightSensor(on);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001315 if (!on) {
1316 // make sure button and key backlights are off too
1317 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, 0);
1318 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, 0);
Mike Lockwood6c97fca2009-10-20 08:10:00 -04001319 // clear current value so we will update based on the new conditions
1320 // when the sensor is reenabled.
1321 mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001322 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001323 }
1324 return err;
1325 }
1326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 private void setPowerState(int state)
1328 {
1329 setPowerState(state, false, false);
1330 }
1331
1332 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1333 {
1334 synchronized (mLocks) {
1335 int err;
1336
1337 if (mSpew) {
1338 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1339 + " newState=0x" + Integer.toHexString(newState)
1340 + " noChangeLights=" + noChangeLights);
1341 }
1342
1343 if (noChangeLights) {
1344 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1345 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001346 if (mProximitySensorActive) {
1347 // don't turn on the screen when the proximity sensor lock is held
1348 newState = (newState & ~SCREEN_BRIGHT);
1349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350
1351 if (batteryIsLow()) {
1352 newState |= BATTERY_LOW_BIT;
1353 } else {
1354 newState &= ~BATTERY_LOW_BIT;
1355 }
1356 if (newState == mPowerState) {
1357 return;
1358 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001359
Mike Lockwood4984e732009-11-01 08:16:33 -05001360 if (!mDoneBooting && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 newState |= ALL_BRIGHT;
1362 }
1363
1364 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1365 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1366
1367 if (mSpew) {
1368 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1369 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1370 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1371 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1372 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1373 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1374 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1375 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1376 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1377 + " newScreenOn=" + newScreenOn);
1378 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1379 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1380 }
1381
1382 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001383 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1385 }
1386
1387 if (oldScreenOn != newScreenOn) {
1388 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001389 // When the user presses the power button, we need to always send out the
1390 // notification that it's going to sleep so the keyguard goes on. But
1391 // we can't do that until the screen fades out, so we don't show the keyguard
1392 // too early.
1393 if (mStillNeedSleepNotification) {
1394 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1395 }
1396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 // Turn on the screen UNLESS there was a prior
1398 // preventScreenOn(true) request. (Note that the lifetime
1399 // of a single preventScreenOn() request is limited to 5
1400 // seconds to prevent a buggy app from disabling the
1401 // screen forever; see forceReenableScreen().)
1402 boolean reallyTurnScreenOn = true;
1403 if (mSpew) {
1404 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1405 + mPreventScreenOn);
1406 }
1407
1408 if (mPreventScreenOn) {
1409 if (mSpew) {
1410 Log.d(TAG, "- PREVENTING screen from really turning on!");
1411 }
1412 reallyTurnScreenOn = false;
1413 }
1414 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001415 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 long identity = Binder.clearCallingIdentity();
1417 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001418 mBatteryStats.noteScreenBrightness(
1419 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 mBatteryStats.noteScreenOn();
1421 } catch (RemoteException e) {
1422 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1423 } finally {
1424 Binder.restoreCallingIdentity(identity);
1425 }
1426 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001427 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 // But continue as if we really did turn the screen on...
1429 err = 0;
1430 }
1431
1432 mScreenOnStartTime = SystemClock.elapsedRealtime();
1433 mLastTouchDown = 0;
1434 mTotalTouchDownTime = 0;
1435 mTouchCycles = 0;
1436 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1437 mTotalTouchDownTime, mTouchCycles);
1438 if (err == 0) {
1439 mPowerState |= SCREEN_ON_BIT;
1440 sendNotificationLocked(true, -1);
1441 }
1442 } else {
1443 mScreenOffTime = SystemClock.elapsedRealtime();
1444 long identity = Binder.clearCallingIdentity();
1445 try {
1446 mBatteryStats.noteScreenOff();
1447 } catch (RemoteException e) {
1448 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1449 } finally {
1450 Binder.restoreCallingIdentity(identity);
1451 }
1452 mPowerState &= ~SCREEN_ON_BIT;
1453 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001454 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 } else {
1456 mOffBecauseOfUser = becauseOfUser;
1457 err = 0;
1458 mLastTouchDown = 0;
1459 }
1460 }
1461 }
1462 }
1463 }
1464
Joe Onorato128e7292009-03-24 18:41:31 -07001465 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 // I don't think we need to check the current state here because all of these
1467 // Power.setScreenState and sendNotificationLocked can both handle being
1468 // called multiple times in the same state. -joeo
1469 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1470 mTotalTouchDownTime, mTouchCycles);
1471 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001472 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 if (mScreenOnStartTime != 0) {
1474 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1475 mScreenOnStartTime = 0;
1476 }
1477 if (err == 0) {
1478 int why = becauseOfUser
1479 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1480 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1481 sendNotificationLocked(false, why);
1482 }
1483 return err;
1484 }
1485
1486 private boolean batteryIsLow() {
1487 return (!mIsPowered &&
1488 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1489 }
1490
The Android Open Source Project10592532009-03-18 17:39:46 -07001491 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001492 final int oldState = mPowerState;
1493 final int realDifference = (newState ^ oldState);
1494 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001496 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 }
1498
1499 int offMask = 0;
1500 int dimMask = 0;
1501 int onMask = 0;
1502
1503 int preferredBrightness = getPreferredBrightness();
1504 boolean startAnimation = false;
1505
1506 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1507 if (ANIMATE_KEYBOARD_LIGHTS) {
1508 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1509 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001510 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1511 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 } else {
1513 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001514 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1515 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
1517 startAnimation = true;
1518 } else {
1519 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001520 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001522 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 }
1524 }
1525 }
1526
1527 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1528 if (ANIMATE_BUTTON_LIGHTS) {
1529 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1530 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001531 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1532 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 } else {
1534 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001535 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1536 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 }
1538 startAnimation = true;
1539 } else {
1540 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001541 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001543 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
1545 }
1546 }
1547
1548 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1549 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001550 int nominalCurrentValue = -1;
1551 // If there was an actual difference in the light state, then
1552 // figure out the "ideal" current value based on the previous
1553 // state. Otherwise, this is a change due to the brightness
1554 // override, so we want to animate from whatever the current
1555 // value is.
1556 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1557 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1558 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1559 nominalCurrentValue = preferredBrightness;
1560 break;
1561 case SCREEN_ON_BIT:
1562 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1563 break;
1564 case 0:
1565 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1566 break;
1567 case SCREEN_BRIGHT_BIT:
1568 default:
1569 // not possible
1570 nominalCurrentValue = (int)mScreenBrightness.curValue;
1571 break;
1572 }
Joe Onorato128e7292009-03-24 18:41:31 -07001573 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001574 int brightness = preferredBrightness;
1575 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1577 // dim or turn off backlight, depending on if the screen is on
1578 // the scale is because the brightness ramp isn't linear and this biases
1579 // it so the later parts take longer.
1580 final float scale = 1.5f;
1581 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1582 if (ratio > 1.0f) ratio = 1.0f;
1583 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1585 // was bright
1586 steps = ANIM_STEPS;
1587 } else {
1588 // was dim
1589 steps = (int)(ANIM_STEPS*ratio*scale);
1590 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001591 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 if ((oldState & SCREEN_ON_BIT) != 0) {
1594 // was bright
1595 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1596 } else {
1597 // was dim
1598 steps = (int)(ANIM_STEPS*ratio);
1599 }
1600 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1601 // If the "stay on while plugged in" option is
1602 // turned on, then the screen will often not
1603 // automatically turn off while plugged in. To
1604 // still have a sense of when it is inactive, we
1605 // will then count going dim as turning off.
1606 mScreenOffTime = SystemClock.elapsedRealtime();
1607 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001608 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001611 long identity = Binder.clearCallingIdentity();
1612 try {
1613 mBatteryStats.noteScreenBrightness(brightness);
1614 } catch (RemoteException e) {
1615 // Nothing interesting to do.
1616 } finally {
1617 Binder.restoreCallingIdentity(identity);
1618 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001619 if (mScreenBrightness.setTargetLocked(brightness,
1620 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1621 startAnimation = true;
1622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 } else {
1624 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1625 // dim or turn off backlight, depending on if the screen is on
1626 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001627 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001629 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 }
1631 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001632 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
1634 }
1635 }
1636
1637 if (startAnimation) {
1638 if (mSpew) {
1639 Log.i(TAG, "Scheduling light animator!");
1640 }
1641 mHandler.removeCallbacks(mLightAnimator);
1642 mHandler.post(mLightAnimator);
1643 }
1644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 if (offMask != 0) {
1646 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001647 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 if (dimMask != 0) {
1650 int brightness = Power.BRIGHTNESS_DIM;
1651 if ((newState & BATTERY_LOW_BIT) != 0 &&
1652 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1653 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1654 }
1655 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001656 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 }
1658 if (onMask != 0) {
1659 int brightness = getPreferredBrightness();
1660 if ((newState & BATTERY_LOW_BIT) != 0 &&
1661 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1662 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1663 }
1664 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001665 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668
The Android Open Source Project10592532009-03-18 17:39:46 -07001669 private void setLightBrightness(int mask, int value) {
1670 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1671 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1672 }
1673 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1674 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1675 }
1676 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1677 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 }
1680
1681 class BrightnessState {
1682 final int mask;
1683
1684 boolean initialized;
1685 int targetValue;
1686 float curValue;
1687 float delta;
1688 boolean animating;
1689
1690 BrightnessState(int m) {
1691 mask = m;
1692 }
1693
1694 public void dump(PrintWriter pw, String prefix) {
1695 pw.println(prefix + "animating=" + animating
1696 + " targetValue=" + targetValue
1697 + " curValue=" + curValue
1698 + " delta=" + delta);
1699 }
1700
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001701 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001702 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 if (!initialized) {
1704 initialized = true;
1705 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001706 } else if (targetValue == target) {
1707 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 }
1709 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001710 delta = (targetValue -
1711 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1712 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001714 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001716 + " target=" + targetValue + " delta=" + delta
1717 + " nominalCurrentValue=" + nominalCurrentValue
1718 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 }
1720 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001721 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 }
1723
1724 boolean stepLocked() {
1725 if (!animating) return false;
1726 if (false && mSpew) {
1727 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1728 + " target=" + targetValue + " delta=" + delta);
1729 }
1730 curValue += delta;
1731 int curIntValue = (int)curValue;
1732 boolean more = true;
1733 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001734 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 more = false;
1736 } else if (delta > 0) {
1737 if (curIntValue >= targetValue) {
1738 curValue = curIntValue = targetValue;
1739 more = false;
1740 }
1741 } else {
1742 if (curIntValue <= targetValue) {
1743 curValue = curIntValue = targetValue;
1744 more = false;
1745 }
1746 }
1747 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001748 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 animating = more;
1750 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001751 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001752 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 }
1754 }
1755 return more;
1756 }
1757 }
1758
1759 private class LightAnimator implements Runnable {
1760 public void run() {
1761 synchronized (mLocks) {
1762 long now = SystemClock.uptimeMillis();
1763 boolean more = mScreenBrightness.stepLocked();
1764 if (mKeyboardBrightness.stepLocked()) {
1765 more = true;
1766 }
1767 if (mButtonBrightness.stepLocked()) {
1768 more = true;
1769 }
1770 if (more) {
1771 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1772 }
1773 }
1774 }
1775 }
1776
1777 private int getPreferredBrightness() {
1778 try {
1779 if (mScreenBrightnessOverride >= 0) {
1780 return mScreenBrightnessOverride;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04001781 } else if (mLightSensorBrightness >= 0 && mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001782 return mLightSensorBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 }
1784 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1785 SCREEN_BRIGHTNESS);
1786 // Don't let applications turn the screen all the way off
1787 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1788 } catch (SettingNotFoundException snfe) {
1789 return Power.BRIGHTNESS_ON;
1790 }
1791 }
1792
1793 boolean screenIsOn() {
1794 synchronized (mLocks) {
1795 return (mPowerState & SCREEN_ON_BIT) != 0;
1796 }
1797 }
1798
1799 boolean screenIsBright() {
1800 synchronized (mLocks) {
1801 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1802 }
1803 }
1804
Mike Lockwood200b30b2009-09-20 00:23:59 -04001805 private void forceUserActivityLocked() {
Mike Lockwood952211b2009-11-02 14:17:57 -05001806 // cancel animation so userActivity will succeed
1807 mScreenBrightness.animating = false;
Mike Lockwood200b30b2009-09-20 00:23:59 -04001808 boolean savedActivityAllowed = mUserActivityAllowed;
1809 mUserActivityAllowed = true;
1810 userActivity(SystemClock.uptimeMillis(), false);
1811 mUserActivityAllowed = savedActivityAllowed;
1812 }
1813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1815 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1816 userActivity(time, noChangeLights, OTHER_EVENT, force);
1817 }
1818
1819 public void userActivity(long time, boolean noChangeLights) {
1820 userActivity(time, noChangeLights, OTHER_EVENT, false);
1821 }
1822
1823 public void userActivity(long time, boolean noChangeLights, int eventType) {
1824 userActivity(time, noChangeLights, eventType, false);
1825 }
1826
1827 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1828 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1829
1830 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001831 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001833 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 }
1835 return;
1836 }
1837
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001838 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1839 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1840 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1841 if (false) {
1842 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1843 }
1844 return;
1845 }
1846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 if (false) {
1848 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1849 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1850 } else {
1851 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1852 }
1853 }
1854
1855 synchronized (mLocks) {
1856 if (mSpew) {
1857 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1858 + " mUserActivityAllowed=" + mUserActivityAllowed
1859 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001860 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1861 + " mProximitySensorActive=" + mProximitySensorActive
1862 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 }
Mike Lockwood05067122009-10-27 23:07:25 -04001864 // ignore user activity if we are in the process of turning off the screen
1865 if (mScreenBrightness.animating && mScreenBrightness.targetValue == 0) {
1866 Log.d(TAG, "ignoring user activity while turning off screen");
1867 return;
1868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 if (mLastEventTime <= time || force) {
1870 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001871 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001872 // Only turn on button backlights if a button was pressed
1873 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05001874 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1876 } else {
1877 // don't clear button/keyboard backlights when the screen is touched.
1878 mUserState |= SCREEN_BRIGHT;
1879 }
1880
Dianne Hackborn617f8772009-03-31 15:04:46 -07001881 int uid = Binder.getCallingUid();
1882 long ident = Binder.clearCallingIdentity();
1883 try {
1884 mBatteryStats.noteUserActivity(uid, eventType);
1885 } catch (RemoteException e) {
1886 // Ignore
1887 } finally {
1888 Binder.restoreCallingIdentity(ident);
1889 }
1890
Michael Chane96440f2009-05-06 10:27:36 -07001891 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1893 setTimeoutLocked(time, SCREEN_BRIGHT);
1894 }
1895 }
1896 }
1897 }
1898
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001899 private int getAutoBrightnessValue(int sensorValue, int[] values) {
1900 try {
1901 int i;
1902 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
1903 if (sensorValue < mAutoBrightnessLevels[i]) {
1904 break;
1905 }
1906 }
1907 return values[i];
1908 } catch (Exception e) {
1909 // guard against null pointer or index out of bounds errors
1910 Log.e(TAG, "getAutoBrightnessValue", e);
1911 return 255;
1912 }
1913 }
1914
1915 private Runnable mAutoBrightnessTask = new Runnable() {
1916 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04001917 synchronized (mLocks) {
1918 int value = (int)mLightSensorPendingValue;
1919 if (value >= 0) {
1920 mLightSensorPendingValue = -1;
1921 lightSensorChangedLocked(value);
1922 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001923 }
1924 }
1925 };
1926
1927 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001928 if (mDebugLightSensor) {
1929 Log.d(TAG, "lightSensorChangedLocked " + value);
1930 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001931
1932 if (mLightSensorValue != value) {
1933 mLightSensorValue = value;
1934 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
1935 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
1936 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04001937 int keyboardValue;
1938 if (mKeyboardVisible) {
1939 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
1940 } else {
1941 keyboardValue = 0;
1942 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001943 mLightSensorBrightness = lcdValue;
1944
1945 if (mDebugLightSensor) {
1946 Log.d(TAG, "lcdValue " + lcdValue);
1947 Log.d(TAG, "buttonValue " + buttonValue);
1948 Log.d(TAG, "keyboardValue " + keyboardValue);
1949 }
1950
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001951 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05001952 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001953 if (ANIMATE_SCREEN_LIGHTS) {
1954 if (mScreenBrightness.setTargetLocked(lcdValue,
1955 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
1956 (int)mScreenBrightness.curValue)) {
1957 startAnimation = true;
1958 }
1959 } else {
1960 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT,
1961 lcdValue);
1962 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001963 }
1964 if (ANIMATE_BUTTON_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001965 if (mButtonBrightness.setTargetLocked(buttonValue,
1966 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1967 (int)mButtonBrightness.curValue)) {
1968 startAnimation = true;
1969 }
1970 } else {
1971 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS,
1972 buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001973 }
1974 if (ANIMATE_KEYBOARD_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001975 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
1976 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1977 (int)mKeyboardBrightness.curValue)) {
1978 startAnimation = true;
1979 }
1980 } else {
1981 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
1982 keyboardValue);
1983 }
1984 if (startAnimation) {
1985 if (mDebugLightSensor) {
1986 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
1987 }
1988 mHandler.removeCallbacks(mLightAnimator);
1989 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001990 }
1991 }
1992 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001993 }
1994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 /**
1996 * The user requested that we go to sleep (probably with the power button).
1997 * This overrides all wake locks that are held.
1998 */
1999 public void goToSleep(long time)
2000 {
2001 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2002 synchronized (mLocks) {
2003 goToSleepLocked(time);
2004 }
2005 }
2006
2007 /**
2008 * Returns the time the screen has been on since boot, in millis.
2009 * @return screen on time
2010 */
2011 public long getScreenOnTime() {
2012 synchronized (mLocks) {
2013 if (mScreenOnStartTime == 0) {
2014 return mScreenOnTime;
2015 } else {
2016 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
2017 }
2018 }
2019 }
2020
2021 private void goToSleepLocked(long time) {
2022
2023 if (mLastEventTime <= time) {
2024 mLastEventTime = time;
2025 // cancel all of the wake locks
2026 mWakeLockState = SCREEN_OFF;
2027 int N = mLocks.size();
2028 int numCleared = 0;
2029 for (int i=0; i<N; i++) {
2030 WakeLock wl = mLocks.get(i);
2031 if (isScreenLock(wl.flags)) {
2032 mLocks.get(i).activated = false;
2033 numCleared++;
2034 }
2035 }
2036 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002037 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 mUserState = SCREEN_OFF;
2039 setPowerState(SCREEN_OFF, false, true);
2040 cancelTimerLocked();
2041 }
2042 }
2043
2044 public long timeSinceScreenOn() {
2045 synchronized (mLocks) {
2046 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2047 return 0;
2048 }
2049 return SystemClock.elapsedRealtime() - mScreenOffTime;
2050 }
2051 }
2052
2053 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002054 synchronized (mLocks) {
2055 if (mSpew) {
2056 Log.d(TAG, "setKeyboardVisibility: " + visible);
2057 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002058 if (mKeyboardVisible != visible) {
2059 mKeyboardVisible = visible;
2060 // don't signal user activity if the screen is off; other code
2061 // will take care of turning on due to a true change to the lid
2062 // switch and synchronized with the lock screen.
2063 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002064 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002065 // force recompute of backlight values
2066 if (mLightSensorValue >= 0) {
2067 int value = (int)mLightSensorValue;
2068 mLightSensorValue = -1;
2069 lightSensorChangedLocked(value);
2070 }
2071 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002072 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2073 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002074 }
2075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 }
2077
2078 /**
2079 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
2080 */
2081 public void enableUserActivity(boolean enabled) {
2082 synchronized (mLocks) {
2083 mUserActivityAllowed = enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 }
2085 }
2086
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002087 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002088 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2089 if (mAutoBrightessEnabled != enabled) {
2090 mAutoBrightessEnabled = enabled;
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002091
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002092 if (mUseHardwareAutoBrightness) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002093 // When setting auto-brightness, must reset the brightness afterwards
2094 mHardware.setAutoBrightness_UNCHECKED(enabled);
2095 if (screenIsOn()) {
2096 setBacklightBrightness((int)mScreenBrightness.curValue);
2097 }
Mike Lockwood4984e732009-11-01 08:16:33 -05002098 } else if (mUseSoftwareAutoBrightness && screenIsOn()) {
2099 // force recompute of backlight values
2100 if (mLightSensorValue >= 0) {
2101 int value = (int)mLightSensorValue;
2102 mLightSensorValue = -1;
2103 lightSensorChangedLocked(value);
2104 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002105 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002106 }
2107 }
2108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 /** Sets the screen off timeouts:
2110 * mKeylightDelay
2111 * mDimDelay
2112 * mScreenOffDelay
2113 * */
2114 private void setScreenOffTimeoutsLocked() {
2115 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
2116 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
2117 mDimDelay = -1;
2118 mScreenOffDelay = 0;
2119 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2120 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2121 mDimDelay = -1;
2122 mScreenOffDelay = 0;
2123 } else {
2124 int totalDelay = mTotalDelaySetting;
2125 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2126 if (totalDelay < 0) {
2127 mScreenOffDelay = Integer.MAX_VALUE;
2128 } else if (mKeylightDelay < totalDelay) {
2129 // subtract the time that the keylight delay. This will give us the
2130 // remainder of the time that we need to sleep to get the accurate
2131 // screen off timeout.
2132 mScreenOffDelay = totalDelay - mKeylightDelay;
2133 } else {
2134 mScreenOffDelay = 0;
2135 }
2136 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2137 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2138 mScreenOffDelay = LONG_DIM_TIME;
2139 } else {
2140 mDimDelay = -1;
2141 }
2142 }
2143 if (mSpew) {
2144 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2145 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2146 + " mDimScreen=" + mDimScreen);
2147 }
2148 }
2149
2150 /**
2151 * Refreshes cached Gservices settings. Called once on startup, and
2152 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
2153 * GservicesChangedReceiver).
2154 */
2155 private void updateGservicesValues() {
2156 mShortKeylightDelay = Settings.Gservices.getInt(
2157 mContext.getContentResolver(),
2158 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
2159 SHORT_KEYLIGHT_DELAY_DEFAULT);
2160 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
2161 }
2162
2163 /**
2164 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
2165 * which tells us we need to refresh our cached Gservices settings.
2166 */
2167 private class GservicesChangedReceiver extends BroadcastReceiver {
2168 @Override
2169 public void onReceive(Context context, Intent intent) {
2170 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
2171 updateGservicesValues();
2172 }
2173 }
2174
2175 private class LockList extends ArrayList<WakeLock>
2176 {
2177 void addLock(WakeLock wl)
2178 {
2179 int index = getIndex(wl.binder);
2180 if (index < 0) {
2181 this.add(wl);
2182 }
2183 }
2184
2185 WakeLock removeLock(IBinder binder)
2186 {
2187 int index = getIndex(binder);
2188 if (index >= 0) {
2189 return this.remove(index);
2190 } else {
2191 return null;
2192 }
2193 }
2194
2195 int getIndex(IBinder binder)
2196 {
2197 int N = this.size();
2198 for (int i=0; i<N; i++) {
2199 if (this.get(i).binder == binder) {
2200 return i;
2201 }
2202 }
2203 return -1;
2204 }
2205
2206 int gatherState()
2207 {
2208 int result = 0;
2209 int N = this.size();
2210 for (int i=0; i<N; i++) {
2211 WakeLock wl = this.get(i);
2212 if (wl.activated) {
2213 if (isScreenLock(wl.flags)) {
2214 result |= wl.minState;
2215 }
2216 }
2217 }
2218 return result;
2219 }
Michael Chane96440f2009-05-06 10:27:36 -07002220
2221 int reactivateScreenLocksLocked()
2222 {
2223 int result = 0;
2224 int N = this.size();
2225 for (int i=0; i<N; i++) {
2226 WakeLock wl = this.get(i);
2227 if (isScreenLock(wl.flags)) {
2228 wl.activated = true;
2229 result |= wl.minState;
2230 }
2231 }
2232 return result;
2233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 }
2235
2236 void setPolicy(WindowManagerPolicy p) {
2237 synchronized (mLocks) {
2238 mPolicy = p;
2239 mLocks.notifyAll();
2240 }
2241 }
2242
2243 WindowManagerPolicy getPolicyLocked() {
2244 while (mPolicy == null || !mDoneBooting) {
2245 try {
2246 mLocks.wait();
2247 } catch (InterruptedException e) {
2248 // Ignore
2249 }
2250 }
2251 return mPolicy;
2252 }
2253
2254 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002255 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2256 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2257 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002258 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002259 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002260 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002261 }
2262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 synchronized (mLocks) {
2264 Log.d(TAG, "system ready!");
2265 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002266 long identity = Binder.clearCallingIdentity();
2267 try {
2268 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2269 mBatteryStats.noteScreenOn();
2270 } catch (RemoteException e) {
2271 // Nothing interesting to do.
2272 } finally {
2273 Binder.restoreCallingIdentity(identity);
2274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2276 updateWakeLockLocked();
2277 mLocks.notifyAll();
2278 }
2279 }
2280
2281 public void monitor() {
2282 synchronized (mLocks) { }
2283 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002284
2285 public int getSupportedWakeLockFlags() {
2286 int result = PowerManager.PARTIAL_WAKE_LOCK
2287 | PowerManager.FULL_WAKE_LOCK
2288 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2289
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002290 if (mProximitySensor != null) {
2291 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2292 }
2293
2294 return result;
2295 }
2296
Mike Lockwood237a2992009-09-15 14:42:16 -04002297 public void setBacklightBrightness(int brightness) {
2298 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2299 // Don't let applications turn the screen all the way off
2300 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2301 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness);
Mike Lockwooddf024922009-10-29 21:29:15 -04002302 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
2303 (mKeyboardVisible ? brightness : 0));
Mike Lockwood237a2992009-09-15 14:42:16 -04002304 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness);
2305 long identity = Binder.clearCallingIdentity();
2306 try {
2307 mBatteryStats.noteScreenBrightness(brightness);
2308 } catch (RemoteException e) {
2309 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2310 } finally {
2311 Binder.restoreCallingIdentity(identity);
2312 }
2313
2314 // update our animation state
2315 if (ANIMATE_SCREEN_LIGHTS) {
2316 mScreenBrightness.curValue = brightness;
2317 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002318 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002319 }
2320 if (ANIMATE_KEYBOARD_LIGHTS) {
2321 mKeyboardBrightness.curValue = brightness;
2322 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002323 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002324 }
2325 if (ANIMATE_BUTTON_LIGHTS) {
2326 mButtonBrightness.curValue = brightness;
2327 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002328 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002329 }
2330 }
2331
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002332 private void enableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002333 if (mSpew) {
2334 Log.d(TAG, "enableProximityLockLocked");
2335 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002336 // clear calling identity so sensor manager battery stats are accurate
2337 long identity = Binder.clearCallingIdentity();
2338 try {
2339 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2340 SensorManager.SENSOR_DELAY_NORMAL);
2341 } finally {
2342 Binder.restoreCallingIdentity(identity);
2343 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002344 }
2345
2346 private void disableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002347 if (mSpew) {
2348 Log.d(TAG, "disableProximityLockLocked");
2349 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002350 // clear calling identity so sensor manager battery stats are accurate
2351 long identity = Binder.clearCallingIdentity();
2352 try {
2353 mSensorManager.unregisterListener(mProximityListener);
2354 } finally {
2355 Binder.restoreCallingIdentity(identity);
2356 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002357 synchronized (mLocks) {
2358 if (mProximitySensorActive) {
2359 mProximitySensorActive = false;
2360 forceUserActivityLocked();
2361 }
2362 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002363 }
2364
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002365 private void enableLightSensor(boolean enable) {
2366 if (mDebugLightSensor) {
2367 Log.d(TAG, "enableLightSensor " + enable);
2368 }
2369 if (mSensorManager != null && mLightSensorEnabled != enable) {
2370 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002371 // clear calling identity so sensor manager battery stats are accurate
2372 long identity = Binder.clearCallingIdentity();
2373 try {
2374 if (enable) {
2375 mSensorManager.registerListener(mLightListener, mLightSensor,
2376 SensorManager.SENSOR_DELAY_NORMAL);
2377 } else {
2378 mSensorManager.unregisterListener(mLightListener);
2379 mHandler.removeCallbacks(mAutoBrightnessTask);
2380 }
2381 } finally {
2382 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002383 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002384 }
2385 }
2386
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002387 SensorEventListener mProximityListener = new SensorEventListener() {
2388 public void onSensorChanged(SensorEvent event) {
2389 long milliseconds = event.timestamp / 1000000;
2390 synchronized (mLocks) {
2391 float distance = event.values[0];
2392 // compare against getMaximumRange to support sensors that only return 0 or 1
2393 if (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2394 distance < mProximitySensor.getMaximumRange()) {
2395 if (mSpew) {
2396 Log.d(TAG, "onSensorChanged: proximity active, distance: " + distance);
2397 }
2398 goToSleepLocked(milliseconds);
2399 mProximitySensorActive = true;
2400 } else {
2401 // proximity sensor negative events trigger as user activity.
2402 // temporarily set mUserActivityAllowed to true so this will work
2403 // even when the keyguard is on.
2404 if (mSpew) {
2405 Log.d(TAG, "onSensorChanged: proximity inactive, distance: " + distance);
2406 }
2407 mProximitySensorActive = false;
2408 forceUserActivityLocked();
2409 }
2410 }
2411 }
2412
2413 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2414 // ignore
2415 }
2416 };
2417
2418 SensorEventListener mLightListener = new SensorEventListener() {
2419 public void onSensorChanged(SensorEvent event) {
2420 synchronized (mLocks) {
2421 int value = (int)event.values[0];
2422 if (mDebugLightSensor) {
2423 Log.d(TAG, "onSensorChanged: light value: " + value);
2424 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002425 mHandler.removeCallbacks(mAutoBrightnessTask);
2426 if (mLightSensorValue != value) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002427 if (mLightSensorValue == -1) {
2428 // process the value immediately
2429 lightSensorChangedLocked(value);
2430 } else {
2431 // delay processing to debounce the sensor
2432 mLightSensorPendingValue = value;
2433 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2434 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002435 } else {
2436 mLightSensorPendingValue = -1;
2437 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002438 }
2439 }
2440
2441 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2442 // ignore
2443 }
2444 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445}