blob: 73527b75da1f5c6b448575c9e181cfaab8108d2c [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.
Mike Lockwood9b8136922009-11-06 15:53:59 -050094 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070095
Mike Lockwood20f87d72009-11-05 16:08:51 -050096 // For debouncing the proximity sensor.
97 private static final int PROXIMITY_SENSOR_DELAY = 1000;
98
Mike Lockwoodd20ea362009-09-15 00:13:38 -040099 // trigger proximity if distance is less than 5 cm
100 private static final float PROXIMITY_THRESHOLD = 5.0f;
101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 // Cached Gservices settings; see updateGservicesValues()
103 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
104
105 // flags for setPowerState
106 private static final int SCREEN_ON_BIT = 0x00000001;
107 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
108 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
109 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
110 private static final int BATTERY_LOW_BIT = 0x00000010;
111
112 // values for setPowerState
113
114 // SCREEN_OFF == everything off
115 private static final int SCREEN_OFF = 0x00000000;
116
117 // SCREEN_DIM == screen on, screen backlight dim
118 private static final int SCREEN_DIM = SCREEN_ON_BIT;
119
120 // SCREEN_BRIGHT == screen on, screen backlight bright
121 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
122
123 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
124 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
125
126 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
127 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
128
129 // used for noChangeLights in setPowerState()
130 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
131
132 static final boolean ANIMATE_SCREEN_LIGHTS = true;
133 static final boolean ANIMATE_BUTTON_LIGHTS = false;
134 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
135
136 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400137 // Slower animation for autobrightness changes
138 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139
140 // These magic numbers are the initial state of the LEDs at boot. Ideally
141 // we should read them from the driver, but our current hardware returns 0
142 // for the initial value. Oops!
143 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
144 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
145 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
146
147 static final int LOG_POWER_SLEEP_REQUESTED = 2724;
148 static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
149 static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
150 static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
151 static final int LOG_POWER_SCREEN_STATE = 2728;
152 static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
153
154 private final int MY_UID;
155
156 private boolean mDoneBooting = false;
157 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700158 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
159 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private int mPartialCount = 0;
161 private int mPowerState;
162 private boolean mOffBecauseOfUser;
163 private int mUserState;
164 private boolean mKeyboardVisible = false;
165 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500166 private int mProximityWakeLockCount = 0;
167 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700168 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500169 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
170 private long mLastProximityEventTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 private int mTotalDelaySetting;
172 private int mKeylightDelay;
173 private int mDimDelay;
174 private int mScreenOffDelay;
175 private int mWakeLockState;
176 private long mLastEventTime = 0;
177 private long mScreenOffTime;
178 private volatile WindowManagerPolicy mPolicy;
179 private final LockList mLocks = new LockList();
180 private Intent mScreenOffIntent;
181 private Intent mScreenOnIntent;
The Android Open Source Project10592532009-03-18 17:39:46 -0700182 private HardwareService mHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 private Context mContext;
184 private UnsynchronizedWakeLock mBroadcastWakeLock;
185 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
186 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
187 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500188 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 private HandlerThread mHandlerThread;
190 private Handler mHandler;
191 private TimeoutTask mTimeoutTask = new TimeoutTask();
192 private LightAnimator mLightAnimator = new LightAnimator();
193 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700194 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700196 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700198 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700199 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 private boolean mIsPowered = false;
201 private IActivityManager mActivityService;
202 private IBatteryStats mBatteryStats;
203 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700204 private SensorManager mSensorManager;
205 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400206 private Sensor mLightSensor;
207 private boolean mLightSensorEnabled;
208 private float mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700209 private float mLightSensorPendingValue = -1;
210 private int mLightSensorBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 private boolean mDimScreen = true;
212 private long mNextTimeout;
213 private volatile int mPokey = 0;
214 private volatile boolean mPokeAwakeOnSet = false;
215 private volatile boolean mInitComplete = false;
216 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500217 // mScreenOnTime and mScreenOnStartTime are used for computing total time screen
218 // has been on since boot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 private long mScreenOnTime;
220 private long mScreenOnStartTime;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500221 // mLastScreenOnTime is the time the screen was last turned on
222 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 private boolean mPreventScreenOn;
224 private int mScreenBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400225 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700226 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700227 private int[] mAutoBrightnessLevels;
228 private int[] mLcdBacklightValues;
229 private int[] mButtonBacklightValues;
230 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500231 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
233 // Used when logging number and duration of touch-down cycles
234 private long mTotalTouchDownTime;
235 private long mLastTouchDown;
236 private int mTouchCycles;
237
238 // could be either static or controllable at runtime
239 private static final boolean mSpew = false;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500240 private static final boolean mDebugProximitySensor = (true || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400241 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242
243 /*
244 static PrintStream mLog;
245 static {
246 try {
247 mLog = new PrintStream("/data/power.log");
248 }
249 catch (FileNotFoundException e) {
250 android.util.Log.e(TAG, "Life is hard", e);
251 }
252 }
253 static class Log {
254 static void d(String tag, String s) {
255 mLog.println(s);
256 android.util.Log.d(tag, s);
257 }
258 static void i(String tag, String s) {
259 mLog.println(s);
260 android.util.Log.i(tag, s);
261 }
262 static void w(String tag, String s) {
263 mLog.println(s);
264 android.util.Log.w(tag, s);
265 }
266 static void e(String tag, String s) {
267 mLog.println(s);
268 android.util.Log.e(tag, s);
269 }
270 }
271 */
272
273 /**
274 * This class works around a deadlock between the lock in PowerManager.WakeLock
275 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
276 * mToken object so it can be accessed from any thread, but it calls into here
277 * with its lock held. This class is essentially a reimplementation of
278 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
279 * only call it with our own locks held.
280 */
281 private class UnsynchronizedWakeLock {
282 int mFlags;
283 String mTag;
284 IBinder mToken;
285 int mCount = 0;
286 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500287 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288
289 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
290 mFlags = flags;
291 mTag = tag;
292 mToken = new Binder();
293 mRefCounted = refCounted;
294 }
295
296 public void acquire() {
297 if (!mRefCounted || mCount++ == 0) {
298 long ident = Binder.clearCallingIdentity();
299 try {
300 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
301 MY_UID, mTag);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500302 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 } finally {
304 Binder.restoreCallingIdentity(ident);
305 }
306 }
307 }
308
309 public void release() {
310 if (!mRefCounted || --mCount == 0) {
311 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500312 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 }
314 if (mCount < 0) {
315 throw new RuntimeException("WakeLock under-locked " + mTag);
316 }
317 }
318
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500319 public boolean isHeld()
320 {
321 return mHeld;
322 }
323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 public String toString() {
325 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500326 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 }
328 }
329
330 private final class BatteryReceiver extends BroadcastReceiver {
331 @Override
332 public void onReceive(Context context, Intent intent) {
333 synchronized (mLocks) {
334 boolean wasPowered = mIsPowered;
335 mIsPowered = mBatteryService.isPowered();
336
337 if (mIsPowered != wasPowered) {
338 // update mStayOnWhilePluggedIn wake lock
339 updateWakeLockLocked();
340
341 // treat plugging and unplugging the devices as a user activity.
342 // users find it disconcerting when they unplug the device
343 // and it shuts off right away.
344 // temporarily set mUserActivityAllowed to true so this will work
345 // even when the keyguard is on.
346 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400347 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 }
349 }
350 }
351 }
352 }
353
354 /**
355 * Set the setting that determines whether the device stays on when plugged in.
356 * The argument is a bit string, with each bit specifying a power source that,
357 * when the device is connected to that source, causes the device to stay on.
358 * See {@link android.os.BatteryManager} for the list of power sources that
359 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
360 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
361 * @param val an {@code int} containing the bits that specify which power sources
362 * should cause the device to stay on.
363 */
364 public void setStayOnSetting(int val) {
365 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
366 Settings.System.putInt(mContext.getContentResolver(),
367 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
368 }
369
370 private class SettingsObserver implements Observer {
371 private int getInt(String name) {
372 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
373 }
374
375 public void update(Observable o, Object arg) {
376 synchronized (mLocks) {
377 // STAY_ON_WHILE_PLUGGED_IN
378 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
379 updateWakeLockLocked();
380
381 // SCREEN_OFF_TIMEOUT
382 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
383
384 // DIM_SCREEN
385 //mDimScreen = getInt(DIM_SCREEN) != 0;
386
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700387 // SCREEN_BRIGHTNESS_MODE
388 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 // recalculate everything
391 setScreenOffTimeoutsLocked();
392 }
393 }
394 }
395
396 PowerManagerService()
397 {
398 // Hack to get our uid... should have a func for this.
399 long token = Binder.clearCallingIdentity();
400 MY_UID = Binder.getCallingUid();
401 Binder.restoreCallingIdentity(token);
402
403 // XXX remove this when the kernel doesn't timeout wake locks
404 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
405
406 // assume nothing is on yet
407 mUserState = mPowerState = 0;
408
409 // Add ourself to the Watchdog monitors.
410 Watchdog.getInstance().addMonitor(this);
411 mScreenOnStartTime = SystemClock.elapsedRealtime();
412 }
413
414 private ContentQueryMap mSettings;
415
The Android Open Source Project10592532009-03-18 17:39:46 -0700416 void init(Context context, HardwareService hardware, IActivityManager activity,
417 BatteryService battery) {
418 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 mContext = context;
420 mActivityService = activity;
421 mBatteryStats = BatteryStatsService.getService();
422 mBatteryService = battery;
423
424 mHandlerThread = new HandlerThread("PowerManagerService") {
425 @Override
426 protected void onLooperPrepared() {
427 super.onLooperPrepared();
428 initInThread();
429 }
430 };
431 mHandlerThread.start();
432
433 synchronized (mHandlerThread) {
434 while (!mInitComplete) {
435 try {
436 mHandlerThread.wait();
437 } catch (InterruptedException e) {
438 // Ignore
439 }
440 }
441 }
442 }
443
444 void initInThread() {
445 mHandler = new Handler();
446
447 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700448 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
450 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
451 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
452 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
453 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
454 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500455 mProximityPartialLock = new UnsynchronizedWakeLock(
456 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457
458 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
459 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
460 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
461 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
462
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700463 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400464
465 // read settings for auto-brightness
466 mUseSoftwareAutoBrightness = resources.getBoolean(
467 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400468 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700469 mAutoBrightnessLevels = resources.getIntArray(
470 com.android.internal.R.array.config_autoBrightnessLevels);
471 mLcdBacklightValues = resources.getIntArray(
472 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
473 mButtonBacklightValues = resources.getIntArray(
474 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
475 mKeyboardBacklightValues = resources.getIntArray(
476 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500477 mLightSensorWarmupTime = resources.getInteger(
478 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700479 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700480
481 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
483 "(" + Settings.System.NAME + "=?) or ("
484 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700485 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700487 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
488 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 null);
490 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
491 SettingsObserver settingsObserver = new SettingsObserver();
492 mSettings.addObserver(settingsObserver);
493
494 // pretend that the settings changed so we will get their initial state
495 settingsObserver.update(mSettings, null);
496
497 // register for the battery changed notifications
498 IntentFilter filter = new IntentFilter();
499 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
500 mContext.registerReceiver(new BatteryReceiver(), filter);
501
502 // Listen for Gservices changes
503 IntentFilter gservicesChangedFilter =
504 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
505 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
506 // And explicitly do the initial update of our cached settings
507 updateGservicesValues();
508
Mike Lockwood4984e732009-11-01 08:16:33 -0500509 if (mUseSoftwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400510 // turn the screen on
511 setPowerState(SCREEN_BRIGHT);
512 } else {
513 // turn everything on
514 setPowerState(ALL_BRIGHT);
515 }
Dan Murphy951764b2009-08-27 14:59:03 -0500516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 synchronized (mHandlerThread) {
518 mInitComplete = true;
519 mHandlerThread.notifyAll();
520 }
521 }
522
523 private class WakeLock implements IBinder.DeathRecipient
524 {
525 WakeLock(int f, IBinder b, String t, int u) {
526 super();
527 flags = f;
528 binder = b;
529 tag = t;
530 uid = u == MY_UID ? Process.SYSTEM_UID : u;
531 if (u != MY_UID || (
532 !"KEEP_SCREEN_ON_FLAG".equals(tag)
533 && !"KeyInputQueue".equals(tag))) {
534 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
535 ? BatteryStats.WAKE_TYPE_PARTIAL
536 : BatteryStats.WAKE_TYPE_FULL;
537 } else {
538 monitorType = -1;
539 }
540 try {
541 b.linkToDeath(this, 0);
542 } catch (RemoteException e) {
543 binderDied();
544 }
545 }
546 public void binderDied() {
547 synchronized (mLocks) {
548 releaseWakeLockLocked(this.binder, true);
549 }
550 }
551 final int flags;
552 final IBinder binder;
553 final String tag;
554 final int uid;
555 final int monitorType;
556 boolean activated = true;
557 int minState;
558 }
559
560 private void updateWakeLockLocked() {
561 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
562 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
563 mStayOnWhilePluggedInScreenDimLock.acquire();
564 mStayOnWhilePluggedInPartialLock.acquire();
565 } else {
566 mStayOnWhilePluggedInScreenDimLock.release();
567 mStayOnWhilePluggedInPartialLock.release();
568 }
569 }
570
571 private boolean isScreenLock(int flags)
572 {
573 int n = flags & LOCK_MASK;
574 return n == PowerManager.FULL_WAKE_LOCK
575 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
576 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
577 }
578
579 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700581 if (uid != Process.myUid()) {
582 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 long ident = Binder.clearCallingIdentity();
585 try {
586 synchronized (mLocks) {
587 acquireWakeLockLocked(flags, lock, uid, tag);
588 }
589 } finally {
590 Binder.restoreCallingIdentity(ident);
591 }
592 }
593
594 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
595 int acquireUid = -1;
596 String acquireName = null;
597 int acquireType = -1;
598
599 if (mSpew) {
600 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
601 }
602
603 int index = mLocks.getIndex(lock);
604 WakeLock wl;
605 boolean newlock;
606 if (index < 0) {
607 wl = new WakeLock(flags, lock, tag, uid);
608 switch (wl.flags & LOCK_MASK)
609 {
610 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500611 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400612 wl.minState = SCREEN_BRIGHT;
613 } else {
614 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 break;
617 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
618 wl.minState = SCREEN_BRIGHT;
619 break;
620 case PowerManager.SCREEN_DIM_WAKE_LOCK:
621 wl.minState = SCREEN_DIM;
622 break;
623 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700624 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 break;
626 default:
627 // just log and bail. we're in the server, so don't
628 // throw an exception.
629 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
630 + " flags=" + flags);
631 return;
632 }
633 mLocks.addLock(wl);
634 newlock = true;
635 } else {
636 wl = mLocks.get(index);
637 newlock = false;
638 }
639 if (isScreenLock(flags)) {
640 // if this causes a wakeup, we reactivate all of the locks and
641 // set it to whatever they want. otherwise, we modulate that
642 // by the current state so we never turn it more on than
643 // it already is.
644 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700645 int oldWakeLockState = mWakeLockState;
646 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 if (mSpew) {
648 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700649 + " mWakeLockState=0x"
650 + Integer.toHexString(mWakeLockState)
651 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 } else {
654 if (mSpew) {
655 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
656 + " mLocks.gatherState()=0x"
657 + Integer.toHexString(mLocks.gatherState())
658 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
659 }
660 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
661 }
662 setPowerState(mWakeLockState | mUserState);
663 }
664 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
665 if (newlock) {
666 mPartialCount++;
667 if (mPartialCount == 1) {
668 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
669 }
670 }
671 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700672 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500673 mProximityWakeLockCount++;
674 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700675 enableProximityLockLocked();
676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 }
678 if (newlock) {
679 acquireUid = wl.uid;
680 acquireName = wl.tag;
681 acquireType = wl.monitorType;
682 }
683
684 if (acquireType >= 0) {
685 try {
686 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
687 } catch (RemoteException e) {
688 // Ignore
689 }
690 }
691 }
692
693 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700694 int uid = Binder.getCallingUid();
695 if (uid != Process.myUid()) {
696 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698
699 synchronized (mLocks) {
700 releaseWakeLockLocked(lock, false);
701 }
702 }
703
704 private void releaseWakeLockLocked(IBinder lock, boolean death) {
705 int releaseUid;
706 String releaseName;
707 int releaseType;
708
709 WakeLock wl = mLocks.removeLock(lock);
710 if (wl == null) {
711 return;
712 }
713
714 if (mSpew) {
715 Log.d(TAG, "releaseWakeLock flags=0x"
716 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
717 }
718
719 if (isScreenLock(wl.flags)) {
720 mWakeLockState = mLocks.gatherState();
721 // goes in the middle to reduce flicker
722 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
723 userActivity(SystemClock.uptimeMillis(), false);
724 }
725 setPowerState(mWakeLockState | mUserState);
726 }
727 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
728 mPartialCount--;
729 if (mPartialCount == 0) {
730 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
731 Power.releaseWakeLock(PARTIAL_NAME);
732 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700733 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500734 mProximityWakeLockCount--;
735 if (mProximityWakeLockCount == 0) {
736 if (mProximitySensorActive) {
737 // wait for proximity sensor to go negative before disabling sensor
738 if (mDebugProximitySensor) {
739 Log.d(TAG, "waiting for proximity sensor to go negative");
740 }
741 } else {
742 disableProximityLockLocked();
743 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 }
746 // Unlink the lock from the binder.
747 wl.binder.unlinkToDeath(wl, 0);
748 releaseUid = wl.uid;
749 releaseName = wl.tag;
750 releaseType = wl.monitorType;
751
752 if (releaseType >= 0) {
753 long origId = Binder.clearCallingIdentity();
754 try {
755 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
756 } catch (RemoteException e) {
757 // Ignore
758 } finally {
759 Binder.restoreCallingIdentity(origId);
760 }
761 }
762 }
763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 private class PokeLock implements IBinder.DeathRecipient
765 {
766 PokeLock(int p, IBinder b, String t) {
767 super();
768 this.pokey = p;
769 this.binder = b;
770 this.tag = t;
771 try {
772 b.linkToDeath(this, 0);
773 } catch (RemoteException e) {
774 binderDied();
775 }
776 }
777 public void binderDied() {
778 setPokeLock(0, this.binder, this.tag);
779 }
780 int pokey;
781 IBinder binder;
782 String tag;
783 boolean awakeOnSet;
784 }
785
786 public void setPokeLock(int pokey, IBinder token, String tag) {
787 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
788 if (token == null) {
789 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
790 return;
791 }
792
793 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
794 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
795 + " and POKE_LOCK_MEDIUM_TIMEOUT");
796 }
797
798 synchronized (mLocks) {
799 if (pokey != 0) {
800 PokeLock p = mPokeLocks.get(token);
801 int oldPokey = 0;
802 if (p != null) {
803 oldPokey = p.pokey;
804 p.pokey = pokey;
805 } else {
806 p = new PokeLock(pokey, token, tag);
807 mPokeLocks.put(token, p);
808 }
809 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
810 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
811 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
812 p.awakeOnSet = true;
813 }
814 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700815 PokeLock rLock = mPokeLocks.remove(token);
816 if (rLock != null) {
817 token.unlinkToDeath(rLock, 0);
818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 }
820
821 int oldPokey = mPokey;
822 int cumulative = 0;
823 boolean oldAwakeOnSet = mPokeAwakeOnSet;
824 boolean awakeOnSet = false;
825 for (PokeLock p: mPokeLocks.values()) {
826 cumulative |= p.pokey;
827 if (p.awakeOnSet) {
828 awakeOnSet = true;
829 }
830 }
831 mPokey = cumulative;
832 mPokeAwakeOnSet = awakeOnSet;
833
834 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
835 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
836
837 if (oldCumulativeTimeout != newCumulativeTimeout) {
838 setScreenOffTimeoutsLocked();
839 // reset the countdown timer, but use the existing nextState so it doesn't
840 // change anything
841 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
842 }
843 }
844 }
845
846 private static String lockType(int type)
847 {
848 switch (type)
849 {
850 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700851 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700853 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700855 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700857 return "PARTIAL_WAKE_LOCK ";
858 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
859 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 default:
David Brown251faa62009-08-02 22:04:36 -0700861 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 }
863 }
864
865 private static String dumpPowerState(int state) {
866 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
867 ? "KEYBOARD_BRIGHT_BIT " : "")
868 + (((state & SCREEN_BRIGHT_BIT) != 0)
869 ? "SCREEN_BRIGHT_BIT " : "")
870 + (((state & SCREEN_ON_BIT) != 0)
871 ? "SCREEN_ON_BIT " : "")
872 + (((state & BATTERY_LOW_BIT) != 0)
873 ? "BATTERY_LOW_BIT " : "");
874 }
875
876 @Override
877 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
878 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
879 != PackageManager.PERMISSION_GRANTED) {
880 pw.println("Permission Denial: can't dump PowerManager from from pid="
881 + Binder.getCallingPid()
882 + ", uid=" + Binder.getCallingUid());
883 return;
884 }
885
886 long now = SystemClock.uptimeMillis();
887
888 pw.println("Power Manager State:");
889 pw.println(" mIsPowered=" + mIsPowered
890 + " mPowerState=" + mPowerState
891 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
892 + " ms");
893 pw.println(" mPartialCount=" + mPartialCount);
894 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
895 pw.println(" mUserState=" + dumpPowerState(mUserState));
896 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
897 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
898 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
899 + " " + ((mNextTimeout-now)/1000) + "s from now");
900 pw.println(" mDimScreen=" + mDimScreen
901 + " mStayOnConditions=" + mStayOnConditions);
902 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
903 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700904 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
905 + ',' + mBroadcastQueue[2] + "}");
906 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
907 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
909 pw.println(" mKeyboardVisible=" + mKeyboardVisible
910 + " mUserActivityAllowed=" + mUserActivityAllowed);
911 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
912 + " mScreenOffDelay=" + mScreenOffDelay);
913 pw.println(" mPreventScreenOn=" + mPreventScreenOn
914 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
915 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500916 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
918 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
919 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
920 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500921 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500922 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
923 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700924 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
Mike Lockwood20f87d72009-11-05 16:08:51 -0500925 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
926 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700927 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
928 pw.println(" mLightSensorValue=" + mLightSensorValue);
929 pw.println(" mLightSensorPendingValue=" + mLightSensorPendingValue);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400930 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700931 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 mScreenBrightness.dump(pw, " mScreenBrightness: ");
933 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
934 mButtonBrightness.dump(pw, " mButtonBrightness: ");
935
936 int N = mLocks.size();
937 pw.println();
938 pw.println("mLocks.size=" + N + ":");
939 for (int i=0; i<N; i++) {
940 WakeLock wl = mLocks.get(i);
941 String type = lockType(wl.flags & LOCK_MASK);
942 String acquireCausesWakeup = "";
943 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
944 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
945 }
946 String activated = "";
947 if (wl.activated) {
948 activated = " activated";
949 }
950 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
951 + activated + " (minState=" + wl.minState + ")");
952 }
953
954 pw.println();
955 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
956 for (PokeLock p: mPokeLocks.values()) {
957 pw.println(" poke lock '" + p.tag + "':"
958 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
959 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700960 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
961 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
963 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
964 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
965 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
966 }
967
968 pw.println();
969 }
970
971 private void setTimeoutLocked(long now, int nextState)
972 {
973 if (mDoneBooting) {
974 mHandler.removeCallbacks(mTimeoutTask);
975 mTimeoutTask.nextState = nextState;
976 long when = now;
977 switch (nextState)
978 {
979 case SCREEN_BRIGHT:
980 when += mKeylightDelay;
981 break;
982 case SCREEN_DIM:
983 if (mDimDelay >= 0) {
984 when += mDimDelay;
985 break;
986 } else {
987 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
988 }
989 case SCREEN_OFF:
990 synchronized (mLocks) {
991 when += mScreenOffDelay;
992 }
993 break;
994 }
995 if (mSpew) {
996 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
997 + " when=" + when);
998 }
999 mHandler.postAtTime(mTimeoutTask, when);
1000 mNextTimeout = when; // for debugging
1001 }
1002 }
1003
1004 private void cancelTimerLocked()
1005 {
1006 mHandler.removeCallbacks(mTimeoutTask);
1007 mTimeoutTask.nextState = -1;
1008 }
1009
1010 private class TimeoutTask implements Runnable
1011 {
1012 int nextState; // access should be synchronized on mLocks
1013 public void run()
1014 {
1015 synchronized (mLocks) {
1016 if (mSpew) {
1017 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
1018 }
1019
1020 if (nextState == -1) {
1021 return;
1022 }
1023
1024 mUserState = this.nextState;
1025 setPowerState(this.nextState | mWakeLockState);
1026
1027 long now = SystemClock.uptimeMillis();
1028
1029 switch (this.nextState)
1030 {
1031 case SCREEN_BRIGHT:
1032 if (mDimDelay >= 0) {
1033 setTimeoutLocked(now, SCREEN_DIM);
1034 break;
1035 }
1036 case SCREEN_DIM:
1037 setTimeoutLocked(now, SCREEN_OFF);
1038 break;
1039 }
1040 }
1041 }
1042 }
1043
1044 private void sendNotificationLocked(boolean on, int why)
1045 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001046 if (!on) {
1047 mStillNeedSleepNotification = false;
1048 }
1049
Joe Onorato128e7292009-03-24 18:41:31 -07001050 // Add to the queue.
1051 int index = 0;
1052 while (mBroadcastQueue[index] != -1) {
1053 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 }
Joe Onorato128e7292009-03-24 18:41:31 -07001055 mBroadcastQueue[index] = on ? 1 : 0;
1056 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057
Joe Onorato128e7292009-03-24 18:41:31 -07001058 // If we added it position 2, then there is a pair that can be stripped.
1059 // If we added it position 1 and we're turning the screen off, we can strip
1060 // the pair and do nothing, because the screen is already off, and therefore
1061 // keyguard has already been enabled.
1062 // However, if we added it at position 1 and we're turning it on, then position
1063 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1064 // on, so have to run the queue then.
1065 if (index == 2) {
1066 // Also, while we're collapsing them, if it's going to be an "off," and one
1067 // is off because of user, then use that, regardless of whether it's the first
1068 // or second one.
1069 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
1070 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
1071 }
1072 mBroadcastQueue[0] = on ? 1 : 0;
1073 mBroadcastQueue[1] = -1;
1074 mBroadcastQueue[2] = -1;
1075 index = 0;
1076 }
1077 if (index == 1 && !on) {
1078 mBroadcastQueue[0] = -1;
1079 mBroadcastQueue[1] = -1;
1080 index = -1;
1081 // The wake lock was being held, but we're not actually going to do any
1082 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1084 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001085 }
1086
1087 // Now send the message.
1088 if (index >= 0) {
1089 // Acquire the broadcast wake lock before changing the power
1090 // state. It will be release after the broadcast is sent.
1091 // We always increment the ref count for each notification in the queue
1092 // and always decrement when that notification is handled.
1093 mBroadcastWakeLock.acquire();
1094 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1095 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 }
1097 }
1098
1099 private Runnable mNotificationTask = new Runnable()
1100 {
1101 public void run()
1102 {
Joe Onorato128e7292009-03-24 18:41:31 -07001103 while (true) {
1104 int value;
1105 int why;
1106 WindowManagerPolicy policy;
1107 synchronized (mLocks) {
1108 value = mBroadcastQueue[0];
1109 why = mBroadcastWhy[0];
1110 for (int i=0; i<2; i++) {
1111 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1112 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1113 }
1114 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 }
Joe Onorato128e7292009-03-24 18:41:31 -07001116 if (value == 1) {
1117 mScreenOnStart = SystemClock.uptimeMillis();
1118
1119 policy.screenTurnedOn();
1120 try {
1121 ActivityManagerNative.getDefault().wakingUp();
1122 } catch (RemoteException e) {
1123 // ignore it
1124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125
Joe Onorato128e7292009-03-24 18:41:31 -07001126 if (mSpew) {
1127 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1128 }
1129 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1130 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1131 mScreenOnBroadcastDone, mHandler, 0, null, null);
1132 } else {
1133 synchronized (mLocks) {
1134 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1135 mBroadcastWakeLock.mCount);
1136 mBroadcastWakeLock.release();
1137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 }
1139 }
Joe Onorato128e7292009-03-24 18:41:31 -07001140 else if (value == 0) {
1141 mScreenOffStart = SystemClock.uptimeMillis();
1142
1143 policy.screenTurnedOff(why);
1144 try {
1145 ActivityManagerNative.getDefault().goingToSleep();
1146 } catch (RemoteException e) {
1147 // ignore it.
1148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149
Joe Onorato128e7292009-03-24 18:41:31 -07001150 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1151 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1152 mScreenOffBroadcastDone, mHandler, 0, null, null);
1153 } else {
1154 synchronized (mLocks) {
1155 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1156 mBroadcastWakeLock.mCount);
1157 mBroadcastWakeLock.release();
1158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 }
1160 }
Joe Onorato128e7292009-03-24 18:41:31 -07001161 else {
1162 // If we're in this case, then this handler is running for a previous
1163 // paired transaction. mBroadcastWakeLock will already have been released.
1164 break;
1165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 }
1167 }
1168 };
1169
1170 long mScreenOnStart;
1171 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1172 public void onReceive(Context context, Intent intent) {
1173 synchronized (mLocks) {
1174 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1175 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1176 mBroadcastWakeLock.release();
1177 }
1178 }
1179 };
1180
1181 long mScreenOffStart;
1182 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1183 public void onReceive(Context context, Intent intent) {
1184 synchronized (mLocks) {
1185 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1186 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1187 mBroadcastWakeLock.release();
1188 }
1189 }
1190 };
1191
1192 void logPointerUpEvent() {
1193 if (LOG_TOUCH_DOWNS) {
1194 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1195 mLastTouchDown = 0;
1196 }
1197 }
1198
1199 void logPointerDownEvent() {
1200 if (LOG_TOUCH_DOWNS) {
1201 // If we are not already timing a down/up sequence
1202 if (mLastTouchDown == 0) {
1203 mLastTouchDown = SystemClock.elapsedRealtime();
1204 mTouchCycles++;
1205 }
1206 }
1207 }
1208
1209 /**
1210 * Prevents the screen from turning on even if it *should* turn on due
1211 * to a subsequent full wake lock being acquired.
1212 * <p>
1213 * This is a temporary hack that allows an activity to "cover up" any
1214 * display glitches that happen during the activity's startup
1215 * sequence. (Specifically, this API was added to work around a
1216 * cosmetic bug in the "incoming call" sequence, where the lock screen
1217 * would flicker briefly before the incoming call UI became visible.)
1218 * TODO: There ought to be a more elegant way of doing this,
1219 * probably by having the PowerManager and ActivityManager
1220 * work together to let apps specify that the screen on/off
1221 * state should be synchronized with the Activity lifecycle.
1222 * <p>
1223 * Note that calling preventScreenOn(true) will NOT turn the screen
1224 * off if it's currently on. (This API only affects *future*
1225 * acquisitions of full wake locks.)
1226 * But calling preventScreenOn(false) WILL turn the screen on if
1227 * it's currently off because of a prior preventScreenOn(true) call.
1228 * <p>
1229 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1230 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1231 * call doesn't occur within 5 seconds, we'll turn the screen back on
1232 * ourselves (and log a warning about it); this prevents a buggy app
1233 * from disabling the screen forever.)
1234 * <p>
1235 * TODO: this feature should really be controlled by a new type of poke
1236 * lock (rather than an IPowerManager call).
1237 */
1238 public void preventScreenOn(boolean prevent) {
1239 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1240
1241 synchronized (mLocks) {
1242 if (prevent) {
1243 // First of all, grab a partial wake lock to
1244 // make sure the CPU stays on during the entire
1245 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1246 mPreventScreenOnPartialLock.acquire();
1247
1248 // Post a forceReenableScreen() call (for 5 seconds in the
1249 // future) to make sure the matching preventScreenOn(false) call
1250 // has happened by then.
1251 mHandler.removeCallbacks(mForceReenableScreenTask);
1252 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1253
1254 // Finally, set the flag that prevents the screen from turning on.
1255 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001256 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 mPreventScreenOn = true;
1258 } else {
1259 // (Re)enable the screen.
1260 mPreventScreenOn = false;
1261
1262 // We're "undoing" a the prior preventScreenOn(true) call, so we
1263 // no longer need the 5-second safeguard.
1264 mHandler.removeCallbacks(mForceReenableScreenTask);
1265
1266 // Forcibly turn on the screen if it's supposed to be on. (This
1267 // handles the case where the screen is currently off because of
1268 // a prior preventScreenOn(true) call.)
1269 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1270 if (mSpew) {
1271 Log.d(TAG,
1272 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1273 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001274 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001276 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 }
1278 }
1279
1280 // Release the partial wake lock that we held during the
1281 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1282 mPreventScreenOnPartialLock.release();
1283 }
1284 }
1285 }
1286
1287 public void setScreenBrightnessOverride(int brightness) {
1288 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1289
1290 synchronized (mLocks) {
1291 if (mScreenBrightnessOverride != brightness) {
1292 mScreenBrightnessOverride = brightness;
1293 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1294 }
1295 }
1296 }
1297
1298 /**
1299 * Sanity-check that gets called 5 seconds after any call to
1300 * preventScreenOn(true). This ensures that the original call
1301 * is followed promptly by a call to preventScreenOn(false).
1302 */
1303 private void forceReenableScreen() {
1304 // We shouldn't get here at all if mPreventScreenOn is false, since
1305 // we should have already removed any existing
1306 // mForceReenableScreenTask messages...
1307 if (!mPreventScreenOn) {
1308 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1309 return;
1310 }
1311
1312 // Uh oh. It's been 5 seconds since a call to
1313 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1314 // This means the app that called preventScreenOn(true) is either
1315 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1316 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1317 // crashed before doing so.)
1318
1319 // Log a warning, and forcibly turn the screen back on.
1320 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1321 + "Forcing the screen back on...");
1322 preventScreenOn(false);
1323 }
1324
1325 private Runnable mForceReenableScreenTask = new Runnable() {
1326 public void run() {
1327 forceReenableScreen();
1328 }
1329 };
1330
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001331 private int setScreenStateLocked(boolean on) {
1332 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001333 if (err == 0) {
1334 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1335 if (mUseSoftwareAutoBrightness) {
1336 enableLightSensor(on);
1337 if (!on) {
1338 // make sure button and key backlights are off too
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001339 int brightnessMode = (mUseSoftwareAutoBrightness
1340 ? HardwareService.BRIGHTNESS_MODE_SENSOR
1341 : HardwareService.BRIGHTNESS_MODE_USER);
1342 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, 0,
1343 brightnessMode);
1344 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, 0,
1345 brightnessMode);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001346 // clear current value so we will update based on the new conditions
1347 // when the sensor is reenabled.
1348 mLightSensorValue = -1;
1349 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001350 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001351 }
1352 return err;
1353 }
1354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 private void setPowerState(int state)
1356 {
1357 setPowerState(state, false, false);
1358 }
1359
1360 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1361 {
1362 synchronized (mLocks) {
1363 int err;
1364
1365 if (mSpew) {
1366 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1367 + " newState=0x" + Integer.toHexString(newState)
1368 + " noChangeLights=" + noChangeLights);
1369 }
1370
1371 if (noChangeLights) {
1372 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1373 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001374 if (mProximitySensorActive) {
1375 // don't turn on the screen when the proximity sensor lock is held
1376 newState = (newState & ~SCREEN_BRIGHT);
1377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378
1379 if (batteryIsLow()) {
1380 newState |= BATTERY_LOW_BIT;
1381 } else {
1382 newState &= ~BATTERY_LOW_BIT;
1383 }
1384 if (newState == mPowerState) {
1385 return;
1386 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001387
Mike Lockwood4984e732009-11-01 08:16:33 -05001388 if (!mDoneBooting && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 newState |= ALL_BRIGHT;
1390 }
1391
1392 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1393 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1394
Mike Lockwood24ace332009-11-09 19:53:08 -05001395 if (mPowerState != newState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1397 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1398 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1399 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1400 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1401 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1402 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1403 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1404 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1405 + " newScreenOn=" + newScreenOn);
1406 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1407 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1408 }
1409
1410 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001411 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1413 }
1414
1415 if (oldScreenOn != newScreenOn) {
1416 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001417 // When the user presses the power button, we need to always send out the
1418 // notification that it's going to sleep so the keyguard goes on. But
1419 // we can't do that until the screen fades out, so we don't show the keyguard
1420 // too early.
1421 if (mStillNeedSleepNotification) {
1422 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1423 }
1424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 // Turn on the screen UNLESS there was a prior
1426 // preventScreenOn(true) request. (Note that the lifetime
1427 // of a single preventScreenOn() request is limited to 5
1428 // seconds to prevent a buggy app from disabling the
1429 // screen forever; see forceReenableScreen().)
1430 boolean reallyTurnScreenOn = true;
1431 if (mSpew) {
1432 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1433 + mPreventScreenOn);
1434 }
1435
1436 if (mPreventScreenOn) {
1437 if (mSpew) {
1438 Log.d(TAG, "- PREVENTING screen from really turning on!");
1439 }
1440 reallyTurnScreenOn = false;
1441 }
1442 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001443 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 long identity = Binder.clearCallingIdentity();
1445 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001446 mBatteryStats.noteScreenBrightness(
1447 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 mBatteryStats.noteScreenOn();
1449 } catch (RemoteException e) {
1450 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1451 } finally {
1452 Binder.restoreCallingIdentity(identity);
1453 }
1454 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001455 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 // But continue as if we really did turn the screen on...
1457 err = 0;
1458 }
1459
1460 mScreenOnStartTime = SystemClock.elapsedRealtime();
1461 mLastTouchDown = 0;
1462 mTotalTouchDownTime = 0;
1463 mTouchCycles = 0;
1464 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1465 mTotalTouchDownTime, mTouchCycles);
1466 if (err == 0) {
1467 mPowerState |= SCREEN_ON_BIT;
1468 sendNotificationLocked(true, -1);
1469 }
1470 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001471 // cancel light sensor task
1472 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 mScreenOffTime = SystemClock.elapsedRealtime();
1474 long identity = Binder.clearCallingIdentity();
1475 try {
1476 mBatteryStats.noteScreenOff();
1477 } catch (RemoteException e) {
1478 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1479 } finally {
1480 Binder.restoreCallingIdentity(identity);
1481 }
1482 mPowerState &= ~SCREEN_ON_BIT;
1483 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001484 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 } else {
1486 mOffBecauseOfUser = becauseOfUser;
1487 err = 0;
1488 mLastTouchDown = 0;
1489 }
1490 }
1491 }
1492 }
1493 }
1494
Joe Onorato128e7292009-03-24 18:41:31 -07001495 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 // I don't think we need to check the current state here because all of these
1497 // Power.setScreenState and sendNotificationLocked can both handle being
1498 // called multiple times in the same state. -joeo
1499 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1500 mTotalTouchDownTime, mTouchCycles);
1501 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001502 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 if (mScreenOnStartTime != 0) {
1504 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1505 mScreenOnStartTime = 0;
1506 }
1507 if (err == 0) {
1508 int why = becauseOfUser
1509 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1510 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1511 sendNotificationLocked(false, why);
1512 }
1513 return err;
1514 }
1515
1516 private boolean batteryIsLow() {
1517 return (!mIsPowered &&
1518 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1519 }
1520
The Android Open Source Project10592532009-03-18 17:39:46 -07001521 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001522 final int oldState = mPowerState;
1523 final int realDifference = (newState ^ oldState);
1524 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001526 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 }
1528
1529 int offMask = 0;
1530 int dimMask = 0;
1531 int onMask = 0;
1532
1533 int preferredBrightness = getPreferredBrightness();
1534 boolean startAnimation = false;
1535
1536 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1537 if (ANIMATE_KEYBOARD_LIGHTS) {
1538 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1539 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001540 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1541 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 } else {
1543 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001544 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1545 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547 startAnimation = true;
1548 } else {
1549 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001550 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001552 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 }
1554 }
1555 }
1556
1557 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1558 if (ANIMATE_BUTTON_LIGHTS) {
1559 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1560 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001561 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1562 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 } else {
1564 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001565 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1566 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 }
1568 startAnimation = true;
1569 } else {
1570 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001571 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001573 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 }
1575 }
1576 }
1577
1578 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1579 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001580 int nominalCurrentValue = -1;
1581 // If there was an actual difference in the light state, then
1582 // figure out the "ideal" current value based on the previous
1583 // state. Otherwise, this is a change due to the brightness
1584 // override, so we want to animate from whatever the current
1585 // value is.
1586 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1587 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1588 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1589 nominalCurrentValue = preferredBrightness;
1590 break;
1591 case SCREEN_ON_BIT:
1592 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1593 break;
1594 case 0:
1595 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1596 break;
1597 case SCREEN_BRIGHT_BIT:
1598 default:
1599 // not possible
1600 nominalCurrentValue = (int)mScreenBrightness.curValue;
1601 break;
1602 }
Joe Onorato128e7292009-03-24 18:41:31 -07001603 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001604 int brightness = preferredBrightness;
1605 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1607 // dim or turn off backlight, depending on if the screen is on
1608 // the scale is because the brightness ramp isn't linear and this biases
1609 // it so the later parts take longer.
1610 final float scale = 1.5f;
1611 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1612 if (ratio > 1.0f) ratio = 1.0f;
1613 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1615 // was bright
1616 steps = ANIM_STEPS;
1617 } else {
1618 // was dim
1619 steps = (int)(ANIM_STEPS*ratio*scale);
1620 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001621 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 if ((oldState & SCREEN_ON_BIT) != 0) {
1624 // was bright
1625 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1626 } else {
1627 // was dim
1628 steps = (int)(ANIM_STEPS*ratio);
1629 }
1630 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1631 // If the "stay on while plugged in" option is
1632 // turned on, then the screen will often not
1633 // automatically turn off while plugged in. To
1634 // still have a sense of when it is inactive, we
1635 // will then count going dim as turning off.
1636 mScreenOffTime = SystemClock.elapsedRealtime();
1637 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001638 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001641 long identity = Binder.clearCallingIdentity();
1642 try {
1643 mBatteryStats.noteScreenBrightness(brightness);
1644 } catch (RemoteException e) {
1645 // Nothing interesting to do.
1646 } finally {
1647 Binder.restoreCallingIdentity(identity);
1648 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001649 if (mScreenBrightness.setTargetLocked(brightness,
1650 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1651 startAnimation = true;
1652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 } else {
1654 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1655 // dim or turn off backlight, depending on if the screen is on
1656 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001657 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001659 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
1661 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001662 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 }
1664 }
1665 }
1666
1667 if (startAnimation) {
1668 if (mSpew) {
1669 Log.i(TAG, "Scheduling light animator!");
1670 }
1671 mHandler.removeCallbacks(mLightAnimator);
1672 mHandler.post(mLightAnimator);
1673 }
1674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 if (offMask != 0) {
1676 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001677 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 }
1679 if (dimMask != 0) {
1680 int brightness = Power.BRIGHTNESS_DIM;
1681 if ((newState & BATTERY_LOW_BIT) != 0 &&
1682 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1683 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1684 }
1685 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001686 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
1688 if (onMask != 0) {
1689 int brightness = getPreferredBrightness();
1690 if ((newState & BATTERY_LOW_BIT) != 0 &&
1691 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1692 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1693 }
1694 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001695 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698
The Android Open Source Project10592532009-03-18 17:39:46 -07001699 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001700 int brightnessMode = (mAutoBrightessEnabled
1701 ? HardwareService.BRIGHTNESS_MODE_SENSOR
1702 : HardwareService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001703 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001704 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value,
1705 brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001706 }
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001707 brightnessMode = (mUseSoftwareAutoBrightness
1708 ? HardwareService.BRIGHTNESS_MODE_SENSOR
1709 : HardwareService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001710 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001711 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value,
1712 brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001713 }
1714 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001715 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value,
1716 brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 }
1719
1720 class BrightnessState {
1721 final int mask;
1722
1723 boolean initialized;
1724 int targetValue;
1725 float curValue;
1726 float delta;
1727 boolean animating;
1728
1729 BrightnessState(int m) {
1730 mask = m;
1731 }
1732
1733 public void dump(PrintWriter pw, String prefix) {
1734 pw.println(prefix + "animating=" + animating
1735 + " targetValue=" + targetValue
1736 + " curValue=" + curValue
1737 + " delta=" + delta);
1738 }
1739
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001740 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001741 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 if (!initialized) {
1743 initialized = true;
1744 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001745 } else if (targetValue == target) {
1746 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 }
1748 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001749 delta = (targetValue -
1750 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1751 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001753 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001755 + " target=" + targetValue + " delta=" + delta
1756 + " nominalCurrentValue=" + nominalCurrentValue
1757 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 }
1759 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001760 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 }
1762
1763 boolean stepLocked() {
1764 if (!animating) return false;
1765 if (false && mSpew) {
1766 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1767 + " target=" + targetValue + " delta=" + delta);
1768 }
1769 curValue += delta;
1770 int curIntValue = (int)curValue;
1771 boolean more = true;
1772 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001773 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 more = false;
1775 } else if (delta > 0) {
1776 if (curIntValue >= targetValue) {
1777 curValue = curIntValue = targetValue;
1778 more = false;
1779 }
1780 } else {
1781 if (curIntValue <= targetValue) {
1782 curValue = curIntValue = targetValue;
1783 more = false;
1784 }
1785 }
1786 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001787 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 animating = more;
1789 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001790 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001791 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 }
1793 }
1794 return more;
1795 }
1796 }
1797
1798 private class LightAnimator implements Runnable {
1799 public void run() {
1800 synchronized (mLocks) {
1801 long now = SystemClock.uptimeMillis();
1802 boolean more = mScreenBrightness.stepLocked();
1803 if (mKeyboardBrightness.stepLocked()) {
1804 more = true;
1805 }
1806 if (mButtonBrightness.stepLocked()) {
1807 more = true;
1808 }
1809 if (more) {
1810 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1811 }
1812 }
1813 }
1814 }
1815
1816 private int getPreferredBrightness() {
1817 try {
1818 if (mScreenBrightnessOverride >= 0) {
1819 return mScreenBrightnessOverride;
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001820 } else if (mLightSensorBrightness >= 0 && mUseSoftwareAutoBrightness
1821 && mAutoBrightessEnabled) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001822 return mLightSensorBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 }
1824 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1825 SCREEN_BRIGHTNESS);
1826 // Don't let applications turn the screen all the way off
1827 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1828 } catch (SettingNotFoundException snfe) {
1829 return Power.BRIGHTNESS_ON;
1830 }
1831 }
1832
Charles Mendis322591c2009-10-29 11:06:59 -07001833 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 synchronized (mLocks) {
1835 return (mPowerState & SCREEN_ON_BIT) != 0;
1836 }
1837 }
1838
Charles Mendis322591c2009-10-29 11:06:59 -07001839 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 synchronized (mLocks) {
1841 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1842 }
1843 }
1844
Mike Lockwood497087e32009-11-08 18:33:03 -05001845 private boolean isScreenTurningOffLocked() {
1846 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1847 }
1848
Mike Lockwood200b30b2009-09-20 00:23:59 -04001849 private void forceUserActivityLocked() {
Mike Lockwood952211b2009-11-02 14:17:57 -05001850 // cancel animation so userActivity will succeed
1851 mScreenBrightness.animating = false;
Mike Lockwood200b30b2009-09-20 00:23:59 -04001852 boolean savedActivityAllowed = mUserActivityAllowed;
1853 mUserActivityAllowed = true;
1854 userActivity(SystemClock.uptimeMillis(), false);
1855 mUserActivityAllowed = savedActivityAllowed;
1856 }
1857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1859 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1860 userActivity(time, noChangeLights, OTHER_EVENT, force);
1861 }
1862
1863 public void userActivity(long time, boolean noChangeLights) {
1864 userActivity(time, noChangeLights, OTHER_EVENT, false);
1865 }
1866
1867 public void userActivity(long time, boolean noChangeLights, int eventType) {
1868 userActivity(time, noChangeLights, eventType, false);
1869 }
1870
1871 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1872 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1873
1874 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001875 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001877 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 }
1879 return;
1880 }
1881
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001882 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1883 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1884 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1885 if (false) {
1886 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1887 }
1888 return;
1889 }
1890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 if (false) {
1892 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1893 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1894 } else {
1895 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1896 }
1897 }
1898
1899 synchronized (mLocks) {
1900 if (mSpew) {
1901 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1902 + " mUserActivityAllowed=" + mUserActivityAllowed
1903 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001904 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1905 + " mProximitySensorActive=" + mProximitySensorActive
1906 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 }
Mike Lockwood05067122009-10-27 23:07:25 -04001908 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05001909 if (isScreenTurningOffLocked()) {
Mike Lockwood05067122009-10-27 23:07:25 -04001910 Log.d(TAG, "ignoring user activity while turning off screen");
1911 return;
1912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 if (mLastEventTime <= time || force) {
1914 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001915 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001916 // Only turn on button backlights if a button was pressed
1917 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05001918 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1920 } else {
1921 // don't clear button/keyboard backlights when the screen is touched.
1922 mUserState |= SCREEN_BRIGHT;
1923 }
1924
Dianne Hackborn617f8772009-03-31 15:04:46 -07001925 int uid = Binder.getCallingUid();
1926 long ident = Binder.clearCallingIdentity();
1927 try {
1928 mBatteryStats.noteUserActivity(uid, eventType);
1929 } catch (RemoteException e) {
1930 // Ignore
1931 } finally {
1932 Binder.restoreCallingIdentity(ident);
1933 }
1934
Michael Chane96440f2009-05-06 10:27:36 -07001935 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1937 setTimeoutLocked(time, SCREEN_BRIGHT);
1938 }
1939 }
1940 }
1941 }
1942
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001943 private int getAutoBrightnessValue(int sensorValue, int[] values) {
1944 try {
1945 int i;
1946 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
1947 if (sensorValue < mAutoBrightnessLevels[i]) {
1948 break;
1949 }
1950 }
1951 return values[i];
1952 } catch (Exception e) {
1953 // guard against null pointer or index out of bounds errors
1954 Log.e(TAG, "getAutoBrightnessValue", e);
1955 return 255;
1956 }
1957 }
1958
Mike Lockwood20f87d72009-11-05 16:08:51 -05001959 private Runnable mProximityTask = new Runnable() {
1960 public void run() {
1961 synchronized (mLocks) {
1962 if (mProximityPendingValue != -1) {
1963 proximityChangedLocked(mProximityPendingValue == 1);
1964 mProximityPendingValue = -1;
1965 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05001966 if (mProximityPartialLock.isHeld()) {
1967 mProximityPartialLock.release();
1968 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05001969 }
1970 }
1971 };
1972
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001973 private Runnable mAutoBrightnessTask = new Runnable() {
1974 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04001975 synchronized (mLocks) {
1976 int value = (int)mLightSensorPendingValue;
1977 if (value >= 0) {
1978 mLightSensorPendingValue = -1;
1979 lightSensorChangedLocked(value);
1980 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001981 }
1982 }
1983 };
1984
1985 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001986 if (mDebugLightSensor) {
1987 Log.d(TAG, "lightSensorChangedLocked " + value);
1988 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001989
1990 if (mLightSensorValue != value) {
1991 mLightSensorValue = value;
1992 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
1993 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
1994 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04001995 int keyboardValue;
1996 if (mKeyboardVisible) {
1997 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
1998 } else {
1999 keyboardValue = 0;
2000 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002001 mLightSensorBrightness = lcdValue;
2002
2003 if (mDebugLightSensor) {
2004 Log.d(TAG, "lcdValue " + lcdValue);
2005 Log.d(TAG, "buttonValue " + buttonValue);
2006 Log.d(TAG, "keyboardValue " + keyboardValue);
2007 }
2008
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002009 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002010 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002011 if (ANIMATE_SCREEN_LIGHTS) {
2012 if (mScreenBrightness.setTargetLocked(lcdValue,
2013 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2014 (int)mScreenBrightness.curValue)) {
2015 startAnimation = true;
2016 }
2017 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002018 int brightnessMode = (mAutoBrightessEnabled
2019 ? HardwareService.BRIGHTNESS_MODE_SENSOR
2020 : HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002021 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002022 lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002023 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002024 }
2025 if (ANIMATE_BUTTON_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002026 if (mButtonBrightness.setTargetLocked(buttonValue,
2027 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2028 (int)mButtonBrightness.curValue)) {
2029 startAnimation = true;
2030 }
2031 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002032 int brightnessMode = (mUseSoftwareAutoBrightness
2033 ? HardwareService.BRIGHTNESS_MODE_SENSOR
2034 : HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002035 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002036 buttonValue, brightnessMode);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002037 }
2038 if (ANIMATE_KEYBOARD_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002039 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2040 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2041 (int)mKeyboardBrightness.curValue)) {
2042 startAnimation = true;
2043 }
2044 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002045 int brightnessMode = (mUseSoftwareAutoBrightness
2046 ? HardwareService.BRIGHTNESS_MODE_SENSOR
2047 : HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002048 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002049 keyboardValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002050 }
2051 if (startAnimation) {
2052 if (mDebugLightSensor) {
2053 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
2054 }
2055 mHandler.removeCallbacks(mLightAnimator);
2056 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002057 }
2058 }
2059 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002060 }
2061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 /**
2063 * The user requested that we go to sleep (probably with the power button).
2064 * This overrides all wake locks that are held.
2065 */
2066 public void goToSleep(long time)
2067 {
2068 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2069 synchronized (mLocks) {
2070 goToSleepLocked(time);
2071 }
2072 }
2073
2074 /**
2075 * Returns the time the screen has been on since boot, in millis.
2076 * @return screen on time
2077 */
2078 public long getScreenOnTime() {
2079 synchronized (mLocks) {
2080 if (mScreenOnStartTime == 0) {
2081 return mScreenOnTime;
2082 } else {
2083 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
2084 }
2085 }
2086 }
2087
2088 private void goToSleepLocked(long time) {
2089
2090 if (mLastEventTime <= time) {
2091 mLastEventTime = time;
2092 // cancel all of the wake locks
2093 mWakeLockState = SCREEN_OFF;
2094 int N = mLocks.size();
2095 int numCleared = 0;
2096 for (int i=0; i<N; i++) {
2097 WakeLock wl = mLocks.get(i);
2098 if (isScreenLock(wl.flags)) {
2099 mLocks.get(i).activated = false;
2100 numCleared++;
2101 }
2102 }
2103 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002104 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 mUserState = SCREEN_OFF;
2106 setPowerState(SCREEN_OFF, false, true);
2107 cancelTimerLocked();
2108 }
2109 }
2110
2111 public long timeSinceScreenOn() {
2112 synchronized (mLocks) {
2113 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2114 return 0;
2115 }
2116 return SystemClock.elapsedRealtime() - mScreenOffTime;
2117 }
2118 }
2119
2120 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002121 synchronized (mLocks) {
2122 if (mSpew) {
2123 Log.d(TAG, "setKeyboardVisibility: " + visible);
2124 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002125 if (mKeyboardVisible != visible) {
2126 mKeyboardVisible = visible;
2127 // don't signal user activity if the screen is off; other code
2128 // will take care of turning on due to a true change to the lid
2129 // switch and synchronized with the lock screen.
2130 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002131 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002132 // force recompute of backlight values
2133 if (mLightSensorValue >= 0) {
2134 int value = (int)mLightSensorValue;
2135 mLightSensorValue = -1;
2136 lightSensorChangedLocked(value);
2137 }
2138 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002139 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2140 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002141 }
2142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 }
2144
2145 /**
2146 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002147 * When disabling user activity we also reset user power state so the keyguard can reset its
2148 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 */
2150 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002151 if (mSpew) {
2152 Log.d(TAG, "enableUserActivity " + enabled);
2153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 synchronized (mLocks) {
2155 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002156 if (!enabled) {
2157 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2158 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 }
2161 }
2162
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002163 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002164 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002165 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002166 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002167 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002168 // force recompute of backlight values
2169 if (mLightSensorValue >= 0) {
2170 int value = (int)mLightSensorValue;
2171 mLightSensorValue = -1;
2172 lightSensorChangedLocked(value);
2173 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002174 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002175 }
2176 }
2177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178 /** Sets the screen off timeouts:
2179 * mKeylightDelay
2180 * mDimDelay
2181 * mScreenOffDelay
2182 * */
2183 private void setScreenOffTimeoutsLocked() {
2184 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
2185 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
2186 mDimDelay = -1;
2187 mScreenOffDelay = 0;
2188 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2189 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2190 mDimDelay = -1;
2191 mScreenOffDelay = 0;
2192 } else {
2193 int totalDelay = mTotalDelaySetting;
2194 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2195 if (totalDelay < 0) {
2196 mScreenOffDelay = Integer.MAX_VALUE;
2197 } else if (mKeylightDelay < totalDelay) {
2198 // subtract the time that the keylight delay. This will give us the
2199 // remainder of the time that we need to sleep to get the accurate
2200 // screen off timeout.
2201 mScreenOffDelay = totalDelay - mKeylightDelay;
2202 } else {
2203 mScreenOffDelay = 0;
2204 }
2205 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2206 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2207 mScreenOffDelay = LONG_DIM_TIME;
2208 } else {
2209 mDimDelay = -1;
2210 }
2211 }
2212 if (mSpew) {
2213 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2214 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2215 + " mDimScreen=" + mDimScreen);
2216 }
2217 }
2218
2219 /**
2220 * Refreshes cached Gservices settings. Called once on startup, and
2221 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
2222 * GservicesChangedReceiver).
2223 */
2224 private void updateGservicesValues() {
2225 mShortKeylightDelay = Settings.Gservices.getInt(
2226 mContext.getContentResolver(),
2227 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
2228 SHORT_KEYLIGHT_DELAY_DEFAULT);
2229 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
2230 }
2231
2232 /**
2233 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
2234 * which tells us we need to refresh our cached Gservices settings.
2235 */
2236 private class GservicesChangedReceiver extends BroadcastReceiver {
2237 @Override
2238 public void onReceive(Context context, Intent intent) {
2239 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
2240 updateGservicesValues();
2241 }
2242 }
2243
2244 private class LockList extends ArrayList<WakeLock>
2245 {
2246 void addLock(WakeLock wl)
2247 {
2248 int index = getIndex(wl.binder);
2249 if (index < 0) {
2250 this.add(wl);
2251 }
2252 }
2253
2254 WakeLock removeLock(IBinder binder)
2255 {
2256 int index = getIndex(binder);
2257 if (index >= 0) {
2258 return this.remove(index);
2259 } else {
2260 return null;
2261 }
2262 }
2263
2264 int getIndex(IBinder binder)
2265 {
2266 int N = this.size();
2267 for (int i=0; i<N; i++) {
2268 if (this.get(i).binder == binder) {
2269 return i;
2270 }
2271 }
2272 return -1;
2273 }
2274
2275 int gatherState()
2276 {
2277 int result = 0;
2278 int N = this.size();
2279 for (int i=0; i<N; i++) {
2280 WakeLock wl = this.get(i);
2281 if (wl.activated) {
2282 if (isScreenLock(wl.flags)) {
2283 result |= wl.minState;
2284 }
2285 }
2286 }
2287 return result;
2288 }
Michael Chane96440f2009-05-06 10:27:36 -07002289
2290 int reactivateScreenLocksLocked()
2291 {
2292 int result = 0;
2293 int N = this.size();
2294 for (int i=0; i<N; i++) {
2295 WakeLock wl = this.get(i);
2296 if (isScreenLock(wl.flags)) {
2297 wl.activated = true;
2298 result |= wl.minState;
2299 }
2300 }
2301 return result;
2302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 }
2304
2305 void setPolicy(WindowManagerPolicy p) {
2306 synchronized (mLocks) {
2307 mPolicy = p;
2308 mLocks.notifyAll();
2309 }
2310 }
2311
2312 WindowManagerPolicy getPolicyLocked() {
2313 while (mPolicy == null || !mDoneBooting) {
2314 try {
2315 mLocks.wait();
2316 } catch (InterruptedException e) {
2317 // Ignore
2318 }
2319 }
2320 return mPolicy;
2321 }
2322
2323 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002324 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2325 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2326 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002327 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002328 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002329 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002330 }
2331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332 synchronized (mLocks) {
2333 Log.d(TAG, "system ready!");
2334 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002335 long identity = Binder.clearCallingIdentity();
2336 try {
2337 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2338 mBatteryStats.noteScreenOn();
2339 } catch (RemoteException e) {
2340 // Nothing interesting to do.
2341 } finally {
2342 Binder.restoreCallingIdentity(identity);
2343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2345 updateWakeLockLocked();
2346 mLocks.notifyAll();
2347 }
2348 }
2349
2350 public void monitor() {
2351 synchronized (mLocks) { }
2352 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002353
2354 public int getSupportedWakeLockFlags() {
2355 int result = PowerManager.PARTIAL_WAKE_LOCK
2356 | PowerManager.FULL_WAKE_LOCK
2357 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2358
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002359 if (mProximitySensor != null) {
2360 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2361 }
2362
2363 return result;
2364 }
2365
Mike Lockwood237a2992009-09-15 14:42:16 -04002366 public void setBacklightBrightness(int brightness) {
2367 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2368 // Don't let applications turn the screen all the way off
2369 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002370 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness,
2371 HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwooddf024922009-10-29 21:29:15 -04002372 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002373 (mKeyboardVisible ? brightness : 0), HardwareService.BRIGHTNESS_MODE_USER);
2374 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness,
2375 HardwareService.BRIGHTNESS_MODE_USER);
Mike Lockwood237a2992009-09-15 14:42:16 -04002376 long identity = Binder.clearCallingIdentity();
2377 try {
2378 mBatteryStats.noteScreenBrightness(brightness);
2379 } catch (RemoteException e) {
2380 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2381 } finally {
2382 Binder.restoreCallingIdentity(identity);
2383 }
2384
2385 // update our animation state
2386 if (ANIMATE_SCREEN_LIGHTS) {
2387 mScreenBrightness.curValue = brightness;
2388 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002389 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002390 }
2391 if (ANIMATE_KEYBOARD_LIGHTS) {
2392 mKeyboardBrightness.curValue = brightness;
2393 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002394 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002395 }
2396 if (ANIMATE_BUTTON_LIGHTS) {
2397 mButtonBrightness.curValue = brightness;
2398 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002399 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002400 }
2401 }
2402
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002403 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002404 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002405 Log.d(TAG, "enableProximityLockLocked");
2406 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002407 if (!mProximitySensorEnabled) {
2408 // clear calling identity so sensor manager battery stats are accurate
2409 long identity = Binder.clearCallingIdentity();
2410 try {
2411 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2412 SensorManager.SENSOR_DELAY_NORMAL);
2413 mProximitySensorEnabled = true;
2414 } finally {
2415 Binder.restoreCallingIdentity(identity);
2416 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002417 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002418 }
2419
2420 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002421 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002422 Log.d(TAG, "disableProximityLockLocked");
2423 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002424 if (mProximitySensorEnabled) {
2425 // clear calling identity so sensor manager battery stats are accurate
2426 long identity = Binder.clearCallingIdentity();
2427 try {
2428 mSensorManager.unregisterListener(mProximityListener);
2429 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002430 if (mProximityPartialLock.isHeld()) {
2431 mProximityPartialLock.release();
2432 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002433 mProximitySensorEnabled = false;
2434 } finally {
2435 Binder.restoreCallingIdentity(identity);
2436 }
2437 if (mProximitySensorActive) {
2438 mProximitySensorActive = false;
2439 forceUserActivityLocked();
2440 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002441 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002442 }
2443
Mike Lockwood20f87d72009-11-05 16:08:51 -05002444 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002445 if (mDebugProximitySensor) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002446 Log.d(TAG, "proximityChangedLocked, active: " + active);
2447 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002448 if (!mProximitySensorEnabled) {
2449 Log.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002450 return;
2451 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002452 if (active) {
2453 goToSleepLocked(SystemClock.uptimeMillis());
2454 mProximitySensorActive = true;
2455 } else {
2456 // proximity sensor negative events trigger as user activity.
2457 // temporarily set mUserActivityAllowed to true so this will work
2458 // even when the keyguard is on.
2459 mProximitySensorActive = false;
2460 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002461
2462 if (mProximityWakeLockCount == 0) {
2463 // disable sensor if we have no listeners left after proximity negative
2464 disableProximityLockLocked();
2465 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002466 }
2467 }
2468
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002469 private void enableLightSensor(boolean enable) {
2470 if (mDebugLightSensor) {
2471 Log.d(TAG, "enableLightSensor " + enable);
2472 }
2473 if (mSensorManager != null && mLightSensorEnabled != enable) {
2474 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002475 // clear calling identity so sensor manager battery stats are accurate
2476 long identity = Binder.clearCallingIdentity();
2477 try {
2478 if (enable) {
2479 mSensorManager.registerListener(mLightListener, mLightSensor,
2480 SensorManager.SENSOR_DELAY_NORMAL);
2481 } else {
2482 mSensorManager.unregisterListener(mLightListener);
2483 mHandler.removeCallbacks(mAutoBrightnessTask);
2484 }
2485 } finally {
2486 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002487 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002488 }
2489 }
2490
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002491 SensorEventListener mProximityListener = new SensorEventListener() {
2492 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002493 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002494 synchronized (mLocks) {
2495 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002496 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2497 mLastProximityEventTime = milliseconds;
2498 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002499 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002500
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002501 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002502 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2503 distance < mProximitySensor.getMaximumRange());
2504
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002505 if (mDebugProximitySensor) {
2506 Log.d(TAG, "mProximityListener.onSensorChanged active: " + active);
2507 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002508 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2509 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2510 mProximityPendingValue = (active ? 1 : 0);
2511 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002512 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002513 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002514 // process the value immediately
2515 mProximityPendingValue = -1;
2516 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002517 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002518
2519 // update mProximityPartialLock state
2520 boolean held = mProximityPartialLock.isHeld();
2521 if (!held && proximityTaskQueued) {
2522 // hold wakelock until mProximityTask runs
2523 mProximityPartialLock.acquire();
2524 } else if (held && !proximityTaskQueued) {
2525 mProximityPartialLock.release();
2526 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002527 }
2528 }
2529
2530 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2531 // ignore
2532 }
2533 };
2534
2535 SensorEventListener mLightListener = new SensorEventListener() {
2536 public void onSensorChanged(SensorEvent event) {
2537 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002538 // ignore light sensor while screen is turning off
2539 if (isScreenTurningOffLocked()) {
2540 return;
2541 }
2542
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002543 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002544 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002545 if (mDebugLightSensor) {
2546 Log.d(TAG, "onSensorChanged: light value: " + value);
2547 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002548 mHandler.removeCallbacks(mAutoBrightnessTask);
2549 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002550 if (mLightSensorValue == -1 ||
2551 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2552 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002553 lightSensorChangedLocked(value);
2554 } else {
2555 // delay processing to debounce the sensor
2556 mLightSensorPendingValue = value;
2557 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2558 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002559 } else {
2560 mLightSensorPendingValue = -1;
2561 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002562 }
2563 }
2564
2565 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2566 // ignore
2567 }
2568 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569}