PowerManagerService.java revision e5167ca61e2c5607aad9041b44158581bc61b4d8
1/*
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.power;
18
19import com.android.internal.app.IAppOpsService;
20import com.android.internal.app.IBatteryStats;
21import com.android.server.BatteryService;
22import com.android.server.EventLogTags;
23import com.android.server.LocalServices;
24import com.android.server.ServiceThread;
25import com.android.server.lights.Light;
26import com.android.server.lights.LightsManager;
27import com.android.server.twilight.TwilightManager;
28import com.android.server.Watchdog;
29
30import android.Manifest;
31import android.content.BroadcastReceiver;
32import android.content.ContentResolver;
33import android.content.Context;
34import android.content.Intent;
35import android.content.IntentFilter;
36import android.content.pm.PackageManager;
37import android.content.res.Resources;
38import android.database.ContentObserver;
39import android.hardware.SensorManager;
40import android.hardware.SystemSensorManager;
41import android.hardware.display.DisplayManagerInternal;
42import android.net.Uri;
43import android.os.BatteryManager;
44import android.os.Binder;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.IPowerManager;
48import android.os.Looper;
49import android.os.Message;
50import android.os.PowerManager;
51import android.os.PowerManagerInternal;
52import android.os.Process;
53import android.os.RemoteException;
54import android.os.SystemClock;
55import android.os.SystemProperties;
56import android.os.SystemService;
57import android.os.UserHandle;
58import android.os.WorkSource;
59import android.provider.Settings;
60import android.service.dreams.DreamManagerInternal;
61import android.util.EventLog;
62import android.util.Log;
63import android.util.Slog;
64import android.util.TimeUtils;
65import android.view.WindowManagerPolicy;
66
67import java.io.FileDescriptor;
68import java.io.PrintWriter;
69import java.util.ArrayList;
70
71import libcore.util.Objects;
72
73/**
74 * The power manager service is responsible for coordinating power management
75 * functions on the device.
76 */
77public final class PowerManagerService extends com.android.server.SystemService
78        implements Watchdog.Monitor {
79    private static final String TAG = "PowerManagerService";
80
81    private static final boolean DEBUG = false;
82    private static final boolean DEBUG_SPEW = DEBUG && true;
83
84    // Message: Sent when a user activity timeout occurs to update the power state.
85    private static final int MSG_USER_ACTIVITY_TIMEOUT = 1;
86    // Message: Sent when the device enters or exits a dreaming or dozing state.
87    private static final int MSG_SANDMAN = 2;
88    // Message: Sent when the screen on blocker is released.
89    private static final int MSG_SCREEN_ON_BLOCKER_RELEASED = 3;
90    // Message: Sent to poll whether the boot animation has terminated.
91    private static final int MSG_CHECK_IF_BOOT_ANIMATION_FINISHED = 4;
92
93    // Dirty bit: mWakeLocks changed
94    private static final int DIRTY_WAKE_LOCKS = 1 << 0;
95    // Dirty bit: mWakefulness changed
96    private static final int DIRTY_WAKEFULNESS = 1 << 1;
97    // Dirty bit: user activity was poked or may have timed out
98    private static final int DIRTY_USER_ACTIVITY = 1 << 2;
99    // Dirty bit: actual display power state was updated asynchronously
100    private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3;
101    // Dirty bit: mBootCompleted changed
102    private static final int DIRTY_BOOT_COMPLETED = 1 << 4;
103    // Dirty bit: settings changed
104    private static final int DIRTY_SETTINGS = 1 << 5;
105    // Dirty bit: mIsPowered changed
106    private static final int DIRTY_IS_POWERED = 1 << 6;
107    // Dirty bit: mStayOn changed
108    private static final int DIRTY_STAY_ON = 1 << 7;
109    // Dirty bit: battery state changed
110    private static final int DIRTY_BATTERY_STATE = 1 << 8;
111    // Dirty bit: proximity state changed
112    private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9;
113    // Dirty bit: screen on blocker state became held or unheld
114    private static final int DIRTY_SCREEN_ON_BLOCKER_RELEASED = 1 << 10;
115    // Dirty bit: dock state changed
116    private static final int DIRTY_DOCK_STATE = 1 << 11;
117
118    // Wakefulness: The device is asleep and can only be awoken by a call to wakeUp().
119    // The screen should be off or in the process of being turned off by the display controller.
120    // The device typically passes through the dozing state first.
121    private static final int WAKEFULNESS_ASLEEP = 0;
122    // Wakefulness: The device is fully awake.  It can be put to sleep by a call to goToSleep().
123    // When the user activity timeout expires, the device may start dreaming or go to sleep.
124    private static final int WAKEFULNESS_AWAKE = 1;
125    // Wakefulness: The device is dreaming.  It can be awoken by a call to wakeUp(),
126    // which ends the dream.  The device goes to sleep when goToSleep() is called, when
127    // the dream ends or when unplugged.
128    // User activity may brighten the screen but does not end the dream.
129    private static final int WAKEFULNESS_DREAMING = 2;
130    // Wakefulness: The device is dozing.  It is almost asleep but is allowing a special
131    // low-power "doze" dream to run which keeps the display on but lets the application
132    // processor be suspended.  It can be awoken by a call to wakeUp() which ends the dream.
133    // The device fully goes to sleep if the dream cannot be started or ends on its own.
134    private static final int WAKEFULNESS_DOZING = 3;
135
136    // Summarizes the state of all active wakelocks.
137    private static final int WAKE_LOCK_CPU = 1 << 0;
138    private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1;
139    private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2;
140    private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3;
141    private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4;
142    private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake
143    private static final int WAKE_LOCK_DOZE = 1 << 6;
144
145    // Summarizes the user activity state.
146    private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0;
147    private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1;
148
149    // Default and minimum screen off timeout in milliseconds.
150    private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
151    private static final int MINIMUM_SCREEN_OFF_TIMEOUT = 10 * 1000;
152
153    // The screen dim duration, in milliseconds.
154    // This is subtracted from the end of the screen off timeout so the
155    // minimum screen off timeout should be longer than this.
156    private static final int SCREEN_DIM_DURATION = 7 * 1000;
157
158    // The maximum screen dim time expressed as a ratio relative to the screen
159    // off timeout.  If the screen off timeout is very short then we want the
160    // dim timeout to also be quite short so that most of the time is spent on.
161    // Otherwise the user won't get much screen on time before dimming occurs.
162    private static final float MAXIMUM_SCREEN_DIM_RATIO = 0.2f;
163
164    // The name of the boot animation service in init.rc.
165    private static final String BOOT_ANIMATION_SERVICE = "bootanim";
166
167    // Poll interval in milliseconds for watching boot animation finished.
168    private static final int BOOT_ANIMATION_POLL_INTERVAL = 200;
169
170    private final Context mContext;
171    private LightsManager mLightsManager;
172    private BatteryService mBatteryService;
173    private DisplayManagerInternal mDisplayManagerInternal;
174    private IBatteryStats mBatteryStats;
175    private IAppOpsService mAppOps;
176    private ServiceThread mHandlerThread;
177    private PowerManagerHandler mHandler;
178    private WindowManagerPolicy mPolicy;
179    private Notifier mNotifier;
180    private DisplayPowerController mDisplayPowerController;
181    private WirelessChargerDetector mWirelessChargerDetector;
182    private SettingsObserver mSettingsObserver;
183    private DreamManagerInternal mDreamManager;
184    private Light mAttentionLight;
185
186    private final Object mLock = new Object();
187
188    // A bitfield that indicates what parts of the power state have
189    // changed and need to be recalculated.
190    private int mDirty;
191
192    // Indicates whether the device is awake or asleep or somewhere in between.
193    // This is distinct from the screen power state, which is managed separately.
194    private int mWakefulness;
195
196    // True if the sandman has just been summoned for the first time since entering the
197    // dreaming or dozing state.  Indicates whether a new dream should begin.
198    private boolean mSandmanSummoned;
199
200    // True if MSG_SANDMAN has been scheduled.
201    private boolean mSandmanScheduled;
202
203    // Table of all suspend blockers.
204    // There should only be a few of these.
205    private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
206
207    // Table of all wake locks acquired by applications.
208    private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
209
210    // A bitfield that summarizes the state of all active wakelocks.
211    private int mWakeLockSummary;
212
213    // If true, instructs the display controller to wait for the proximity sensor to
214    // go negative before turning the screen on.
215    private boolean mRequestWaitForNegativeProximity;
216
217    // Timestamp of the last time the device was awoken or put to sleep.
218    private long mLastWakeTime;
219    private long mLastSleepTime;
220
221    // True if we need to send a wake up or go to sleep finished notification
222    // when the display is ready.
223    private boolean mSendWakeUpFinishedNotificationWhenReady;
224    private boolean mSendGoToSleepFinishedNotificationWhenReady;
225
226    // Timestamp of the last call to user activity.
227    private long mLastUserActivityTime;
228    private long mLastUserActivityTimeNoChangeLights;
229
230    // A bitfield that summarizes the effect of the user activity timer.
231    // A zero value indicates that the user activity timer has expired.
232    private int mUserActivitySummary;
233
234    // The desired display power state.  The actual state may lag behind the
235    // requested because it is updated asynchronously by the display power controller.
236    private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
237
238    // True if the display power state has been fully applied, which means the display
239    // is actually on or actually off or whatever was requested.
240    private boolean mDisplayReady;
241
242    // The suspend blocker used to keep the CPU alive when an application has acquired
243    // a wake lock.
244    private final SuspendBlocker mWakeLockSuspendBlocker;
245
246    // True if the wake lock suspend blocker has been acquired.
247    private boolean mHoldingWakeLockSuspendBlocker;
248
249    // The suspend blocker used to keep the CPU alive when the display is on, the
250    // display is getting ready or there is user activity (in which case the display
251    // must be on).
252    private final SuspendBlocker mDisplaySuspendBlocker;
253
254    // True if the display suspend blocker has been acquired.
255    private boolean mHoldingDisplaySuspendBlocker;
256
257    // The screen on blocker used to keep the screen from turning on while the lock
258    // screen is coming up.
259    private final ScreenOnBlockerImpl mScreenOnBlocker;
260
261    // The display blanker used to turn the screen on or off.
262    private final DisplayBlankerImpl mDisplayBlanker;
263
264    // True if systemReady() has been called.
265    private boolean mSystemReady;
266
267    // True if boot completed occurred.  We keep the screen on until this happens.
268    private boolean mBootCompleted;
269
270    // True if auto-suspend mode is enabled.
271    // Refer to autosuspend.h.
272    private boolean mAutoSuspendModeEnabled;
273
274    // True if interactive mode is enabled.
275    // Refer to power.h.
276    private boolean mInteractiveModeEnabled;
277
278    // True if the device is plugged into a power source.
279    private boolean mIsPowered;
280
281    // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
282    private int mPlugType;
283
284    // The current battery level percentage.
285    private int mBatteryLevel;
286
287    // The battery level percentage at the time the dream started.
288    // This is used to terminate a dream and go to sleep if the battery is
289    // draining faster than it is charging and the user activity timeout has expired.
290    private int mBatteryLevelWhenDreamStarted;
291
292    // The current dock state.
293    private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
294
295    // True to decouple auto-suspend mode from the display state.
296    private boolean mDecoupleAutoSuspendModeFromDisplayConfig;
297
298    // True to decouple interactive mode from the display state.
299    private boolean mDecoupleInteractiveModeFromDisplayConfig;
300
301    // True if the device should wake up when plugged or unplugged.
302    private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
303
304    // True if the device should suspend when the screen is off due to proximity.
305    private boolean mSuspendWhenScreenOffDueToProximityConfig;
306
307    // True if dreams are supported on this device.
308    private boolean mDreamsSupportedConfig;
309
310    // Default value for dreams enabled
311    private boolean mDreamsEnabledByDefaultConfig;
312
313    // Default value for dreams activate-on-sleep
314    private boolean mDreamsActivatedOnSleepByDefaultConfig;
315
316    // Default value for dreams activate-on-dock
317    private boolean mDreamsActivatedOnDockByDefaultConfig;
318
319    // True if dreams can run while not plugged in.
320    private boolean mDreamsEnabledOnBatteryConfig;
321
322    // Minimum battery level to allow dreaming when powered.
323    // Use -1 to disable this safety feature.
324    private int mDreamsBatteryLevelMinimumWhenPoweredConfig;
325
326    // Minimum battery level to allow dreaming when not powered.
327    // Use -1 to disable this safety feature.
328    private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig;
329
330    // If the battery level drops by this percentage and the user activity timeout
331    // has expired, then assume the device is receiving insufficient current to charge
332    // effectively and terminate the dream.  Use -1 to disable this safety feature.
333    private int mDreamsBatteryLevelDrainCutoffConfig;
334
335    // True if dreams are enabled by the user.
336    private boolean mDreamsEnabledSetting;
337
338    // True if dreams should be activated on sleep.
339    private boolean mDreamsActivateOnSleepSetting;
340
341    // True if dreams should be activated on dock.
342    private boolean mDreamsActivateOnDockSetting;
343
344    // The screen off timeout setting value in milliseconds.
345    private int mScreenOffTimeoutSetting;
346
347    // The maximum allowable screen off timeout according to the device
348    // administration policy.  Overrides other settings.
349    private int mMaximumScreenOffTimeoutFromDeviceAdmin = Integer.MAX_VALUE;
350
351    // The stay on while plugged in setting.
352    // A bitfield of battery conditions under which to make the screen stay on.
353    private int mStayOnWhilePluggedInSetting;
354
355    // True if the device should stay on.
356    private boolean mStayOn;
357
358    // True if the proximity sensor reads a positive result.
359    private boolean mProximityPositive;
360
361    // Screen brightness setting limits.
362    private int mScreenBrightnessSettingMinimum;
363    private int mScreenBrightnessSettingMaximum;
364    private int mScreenBrightnessSettingDefault;
365
366    // The screen brightness setting, from 0 to 255.
367    // Use -1 if no value has been set.
368    private int mScreenBrightnessSetting;
369
370    // The screen auto-brightness adjustment setting, from -1 to 1.
371    // Use 0 if there is no adjustment.
372    private float mScreenAutoBrightnessAdjustmentSetting;
373
374    // The screen brightness mode.
375    // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
376    private int mScreenBrightnessModeSetting;
377
378    // The screen brightness setting override from the window manager
379    // to allow the current foreground activity to override the brightness.
380    // Use -1 to disable.
381    private int mScreenBrightnessOverrideFromWindowManager = -1;
382
383    // The user activity timeout override from the window manager
384    // to allow the current foreground activity to override the user activity timeout.
385    // Use -1 to disable.
386    private long mUserActivityTimeoutOverrideFromWindowManager = -1;
387
388    // The screen brightness setting override from the settings application
389    // to temporarily adjust the brightness until next updated,
390    // Use -1 to disable.
391    private int mTemporaryScreenBrightnessSettingOverride = -1;
392
393    // The screen brightness adjustment setting override from the settings
394    // application to temporarily adjust the auto-brightness adjustment factor
395    // until next updated, in the range -1..1.
396    // Use NaN to disable.
397    private float mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN;
398
399    // Time when we last logged a warning about calling userActivity() without permission.
400    private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
401
402    private native void nativeInit();
403
404    private static native void nativeSetPowerState(boolean screenOn, boolean screenBright);
405    private static native void nativeAcquireSuspendBlocker(String name);
406    private static native void nativeReleaseSuspendBlocker(String name);
407    private static native void nativeSetInteractive(boolean enable);
408    private static native void nativeSetAutoSuspend(boolean enable);
409
410    public PowerManagerService(Context context) {
411        super(context);
412        mContext = context;
413        synchronized (mLock) {
414            mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks");
415            mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display");
416            mDisplaySuspendBlocker.acquire();
417            mHoldingDisplaySuspendBlocker = true;
418
419            mScreenOnBlocker = new ScreenOnBlockerImpl();
420            mDisplayBlanker = new DisplayBlankerImpl();
421            mWakefulness = WAKEFULNESS_AWAKE;
422        }
423
424        nativeInit();
425        nativeSetPowerState(true, true);
426    }
427
428    @Override
429    public void onStart() {
430        publishBinderService(Context.POWER_SERVICE, new BinderService());
431        publishLocalService(PowerManagerInternal.class, new LocalService());
432    }
433
434    /**
435     * Initialize the power manager.
436     * Must be called before any other functions within the power manager are called.
437     */
438    public void init(LightsManager ls,
439            BatteryService bs, IBatteryStats bss,
440            IAppOpsService appOps) {
441        mLightsManager = ls;
442        mBatteryService = bs;
443        mBatteryStats = bss;
444        mAppOps = appOps;
445        mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
446        mHandlerThread = new ServiceThread(TAG,
447                Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
448        mHandlerThread.start();
449        mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
450
451        Watchdog.getInstance().addMonitor(this);
452        Watchdog.getInstance().addThread(mHandler);
453
454        // Forcibly turn the screen on at boot so that it is in a known power state.
455        // We do this in init() rather than in the constructor because setting the
456        // screen state requires a call into surface flinger which then needs to call back
457        // into the activity manager to check permissions.  Unfortunately the
458        // activity manager is not running when the constructor is called, so we
459        // have to defer setting the screen state until this point.
460        mDisplayBlanker.unblankAllDisplays();
461    }
462
463    void setPolicy(WindowManagerPolicy policy) {
464        synchronized (mLock) {
465            mPolicy = policy;
466        }
467    }
468
469    public void systemReady() {
470        synchronized (mLock) {
471            mSystemReady = true;
472            mDreamManager = LocalServices.getService(DreamManagerInternal.class);
473
474            PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
475            mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
476            mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
477            mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
478
479            SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
480
481            // The notifier runs on the system server's main looper so as not to interfere
482            // with the animations and other critical functions of the power manager.
483            mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats,
484                    mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"),
485                    mScreenOnBlocker, mPolicy);
486
487            // The display power controller runs on the power manager service's
488            // own handler thread to ensure timely operation.
489            mDisplayPowerController = new DisplayPowerController(mHandler.getLooper(),
490                    mContext, mNotifier, mLightsManager,
491                    LocalServices.getService(TwilightManager.class), sensorManager,
492                    mDisplaySuspendBlocker, mDisplayBlanker,
493                    mDisplayPowerControllerCallbacks, mHandler);
494
495            mWirelessChargerDetector = new WirelessChargerDetector(sensorManager,
496                    createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"),
497                    mHandler);
498            mSettingsObserver = new SettingsObserver(mHandler);
499            mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
500
501            // Register for broadcasts from other components of the system.
502            IntentFilter filter = new IntentFilter();
503            filter.addAction(Intent.ACTION_BATTERY_CHANGED);
504            mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
505
506            filter = new IntentFilter();
507            filter.addAction(Intent.ACTION_BOOT_COMPLETED);
508            mContext.registerReceiver(new BootCompletedReceiver(), filter, null, mHandler);
509
510            filter = new IntentFilter();
511            filter.addAction(Intent.ACTION_DREAMING_STARTED);
512            filter.addAction(Intent.ACTION_DREAMING_STOPPED);
513            mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
514
515            filter = new IntentFilter();
516            filter.addAction(Intent.ACTION_USER_SWITCHED);
517            mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
518
519            filter = new IntentFilter();
520            filter.addAction(Intent.ACTION_DOCK_EVENT);
521            mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
522
523            // Register for settings changes.
524            final ContentResolver resolver = mContext.getContentResolver();
525            resolver.registerContentObserver(Settings.Secure.getUriFor(
526                    Settings.Secure.SCREENSAVER_ENABLED),
527                    false, mSettingsObserver, UserHandle.USER_ALL);
528            resolver.registerContentObserver(Settings.Secure.getUriFor(
529                    Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
530                    false, mSettingsObserver, UserHandle.USER_ALL);
531            resolver.registerContentObserver(Settings.Secure.getUriFor(
532                    Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
533                    false, mSettingsObserver, UserHandle.USER_ALL);
534            resolver.registerContentObserver(Settings.System.getUriFor(
535                    Settings.System.SCREEN_OFF_TIMEOUT),
536                    false, mSettingsObserver, UserHandle.USER_ALL);
537            resolver.registerContentObserver(Settings.Global.getUriFor(
538                    Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
539                    false, mSettingsObserver, UserHandle.USER_ALL);
540            resolver.registerContentObserver(Settings.System.getUriFor(
541                    Settings.System.SCREEN_BRIGHTNESS),
542                    false, mSettingsObserver, UserHandle.USER_ALL);
543            resolver.registerContentObserver(Settings.System.getUriFor(
544                    Settings.System.SCREEN_BRIGHTNESS_MODE),
545                    false, mSettingsObserver, UserHandle.USER_ALL);
546
547            // Go.
548            readConfigurationLocked();
549            updateSettingsLocked();
550            mDirty |= DIRTY_BATTERY_STATE;
551            updatePowerStateLocked();
552        }
553    }
554
555    private void readConfigurationLocked() {
556        final Resources resources = mContext.getResources();
557
558        mDecoupleAutoSuspendModeFromDisplayConfig = resources.getBoolean(
559                com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
560        mDecoupleInteractiveModeFromDisplayConfig = resources.getBoolean(
561                com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
562        mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
563                com.android.internal.R.bool.config_unplugTurnsOnScreen);
564        mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
565                com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
566        mDreamsSupportedConfig = resources.getBoolean(
567                com.android.internal.R.bool.config_dreamsSupported);
568        mDreamsEnabledByDefaultConfig = resources.getBoolean(
569                com.android.internal.R.bool.config_dreamsEnabledByDefault);
570        mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
571                com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
572        mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
573                com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
574        mDreamsEnabledOnBatteryConfig = resources.getBoolean(
575                com.android.internal.R.bool.config_dreamsEnabledOnBattery);
576        mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
577                com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
578        mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
579                com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
580        mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
581                com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
582    }
583
584    private void updateSettingsLocked() {
585        final ContentResolver resolver = mContext.getContentResolver();
586
587        mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
588                Settings.Secure.SCREENSAVER_ENABLED,
589                mDreamsEnabledByDefaultConfig ? 1 : 0,
590                UserHandle.USER_CURRENT) != 0);
591        mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
592                Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
593                mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
594                UserHandle.USER_CURRENT) != 0);
595        mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
596                Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
597                mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
598                UserHandle.USER_CURRENT) != 0);
599        mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
600                Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
601                UserHandle.USER_CURRENT);
602        mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
603                Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
604
605        final int oldScreenBrightnessSetting = mScreenBrightnessSetting;
606        mScreenBrightnessSetting = Settings.System.getIntForUser(resolver,
607                Settings.System.SCREEN_BRIGHTNESS, mScreenBrightnessSettingDefault,
608                UserHandle.USER_CURRENT);
609        if (oldScreenBrightnessSetting != mScreenBrightnessSetting) {
610            mTemporaryScreenBrightnessSettingOverride = -1;
611        }
612
613        final float oldScreenAutoBrightnessAdjustmentSetting =
614                mScreenAutoBrightnessAdjustmentSetting;
615        mScreenAutoBrightnessAdjustmentSetting = Settings.System.getFloatForUser(resolver,
616                Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f,
617                UserHandle.USER_CURRENT);
618        if (oldScreenAutoBrightnessAdjustmentSetting != mScreenAutoBrightnessAdjustmentSetting) {
619            mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN;
620        }
621
622        mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
623                Settings.System.SCREEN_BRIGHTNESS_MODE,
624                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
625
626        mDirty |= DIRTY_SETTINGS;
627    }
628
629    private void handleSettingsChangedLocked() {
630        updateSettingsLocked();
631        updatePowerStateLocked();
632    }
633
634    private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
635            WorkSource ws, String historyTag, int uid, int pid) {
636        synchronized (mLock) {
637            if (DEBUG_SPEW) {
638                Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
639                        + ", flags=0x" + Integer.toHexString(flags)
640                        + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
641            }
642
643            WakeLock wakeLock;
644            int index = findWakeLockIndexLocked(lock);
645            if (index >= 0) {
646                wakeLock = mWakeLocks.get(index);
647                if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
648                    // Update existing wake lock.  This shouldn't happen but is harmless.
649                    notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
650                            uid, pid, ws, historyTag);
651                    wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);
652                }
653            } else {
654                wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid);
655                try {
656                    lock.linkToDeath(wakeLock, 0);
657                } catch (RemoteException ex) {
658                    throw new IllegalArgumentException("Wake lock is already dead.");
659                }
660                notifyWakeLockAcquiredLocked(wakeLock);
661                mWakeLocks.add(wakeLock);
662            }
663
664            applyWakeLockFlagsOnAcquireLocked(wakeLock);
665            mDirty |= DIRTY_WAKE_LOCKS;
666            updatePowerStateLocked();
667        }
668    }
669
670    @SuppressWarnings("deprecation")
671    private static boolean isScreenLock(final WakeLock wakeLock) {
672        switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
673            case PowerManager.FULL_WAKE_LOCK:
674            case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
675            case PowerManager.SCREEN_DIM_WAKE_LOCK:
676                return true;
677        }
678        return false;
679    }
680
681    private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock) {
682        if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
683                && isScreenLock(wakeLock)) {
684            wakeUpNoUpdateLocked(SystemClock.uptimeMillis());
685        }
686    }
687
688    private void releaseWakeLockInternal(IBinder lock, int flags) {
689        synchronized (mLock) {
690            int index = findWakeLockIndexLocked(lock);
691            if (index < 0) {
692                if (DEBUG_SPEW) {
693                    Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
694                            + " [not found], flags=0x" + Integer.toHexString(flags));
695                }
696                return;
697            }
698
699            WakeLock wakeLock = mWakeLocks.get(index);
700            if (DEBUG_SPEW) {
701                Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
702                        + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
703            }
704
705            mWakeLocks.remove(index);
706            notifyWakeLockReleasedLocked(wakeLock);
707            wakeLock.mLock.unlinkToDeath(wakeLock, 0);
708
709            if ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0) {
710                mRequestWaitForNegativeProximity = true;
711            }
712
713            applyWakeLockFlagsOnReleaseLocked(wakeLock);
714            mDirty |= DIRTY_WAKE_LOCKS;
715            updatePowerStateLocked();
716        }
717    }
718
719    private void handleWakeLockDeath(WakeLock wakeLock) {
720        synchronized (mLock) {
721            if (DEBUG_SPEW) {
722                Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
723                        + " [" + wakeLock.mTag + "]");
724            }
725
726            int index = mWakeLocks.indexOf(wakeLock);
727            if (index < 0) {
728                return;
729            }
730
731            mWakeLocks.remove(index);
732            notifyWakeLockReleasedLocked(wakeLock);
733
734            applyWakeLockFlagsOnReleaseLocked(wakeLock);
735            mDirty |= DIRTY_WAKE_LOCKS;
736            updatePowerStateLocked();
737        }
738    }
739
740    private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
741        if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
742                && isScreenLock(wakeLock)) {
743            userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
744                    PowerManager.USER_ACTIVITY_EVENT_OTHER,
745                    PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
746                    wakeLock.mOwnerUid);
747        }
748    }
749
750    private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws) {
751        synchronized (mLock) {
752            int index = findWakeLockIndexLocked(lock);
753            if (index < 0) {
754                if (DEBUG_SPEW) {
755                    Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
756                            + " [not found], ws=" + ws);
757                }
758                throw new IllegalArgumentException("Wake lock not active");
759            }
760
761            WakeLock wakeLock = mWakeLocks.get(index);
762            if (DEBUG_SPEW) {
763                Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
764                        + " [" + wakeLock.mTag + "], ws=" + ws);
765            }
766
767            if (!wakeLock.hasSameWorkSource(ws)) {
768                notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
769                        wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
770                        ws, wakeLock.mHistoryTag);
771                wakeLock.updateWorkSource(ws);
772            }
773        }
774    }
775
776    private int findWakeLockIndexLocked(IBinder lock) {
777        final int count = mWakeLocks.size();
778        for (int i = 0; i < count; i++) {
779            if (mWakeLocks.get(i).mLock == lock) {
780                return i;
781            }
782        }
783        return -1;
784    }
785
786    private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
787        if (mSystemReady) {
788            wakeLock.mNotifiedAcquired = true;
789            mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
790                    wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
791                    wakeLock.mHistoryTag);
792        }
793    }
794
795    private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
796            String packageName, int uid, int pid, WorkSource ws, String historyTag) {
797        if (mSystemReady && wakeLock.mNotifiedAcquired) {
798            mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
799                    wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
800                    wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag);
801        }
802    }
803
804    private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
805        if (mSystemReady && wakeLock.mNotifiedAcquired) {
806            wakeLock.mNotifiedAcquired = false;
807            mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
808                    wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource);
809        }
810    }
811
812    @SuppressWarnings("deprecation")
813    private boolean isWakeLockLevelSupportedInternal(int level) {
814        synchronized (mLock) {
815            switch (level) {
816                case PowerManager.PARTIAL_WAKE_LOCK:
817                case PowerManager.SCREEN_DIM_WAKE_LOCK:
818                case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
819                case PowerManager.FULL_WAKE_LOCK:
820                case PowerManager.DOZE_WAKE_LOCK:
821                    return true;
822
823                case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
824                    return mSystemReady && mDisplayPowerController.isProximitySensorAvailable();
825
826                default:
827                    return false;
828            }
829        }
830    }
831
832    // Called from native code.
833    private void userActivityFromNative(long eventTime, int event, int flags) {
834        userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
835    }
836
837    private void userActivityInternal(long eventTime, int event, int flags, int uid) {
838        synchronized (mLock) {
839            if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
840                updatePowerStateLocked();
841            }
842        }
843    }
844
845    private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
846        if (DEBUG_SPEW) {
847            Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
848                    + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
849                    + ", uid=" + uid);
850        }
851
852        if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
853                || mWakefulness == WAKEFULNESS_ASLEEP || mWakefulness == WAKEFULNESS_DOZING
854                || !mBootCompleted || !mSystemReady) {
855            return false;
856        }
857
858        mNotifier.onUserActivity(event, uid);
859
860        if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
861            if (eventTime > mLastUserActivityTimeNoChangeLights
862                    && eventTime > mLastUserActivityTime) {
863                mLastUserActivityTimeNoChangeLights = eventTime;
864                mDirty |= DIRTY_USER_ACTIVITY;
865                return true;
866            }
867        } else {
868            if (eventTime > mLastUserActivityTime) {
869                mLastUserActivityTime = eventTime;
870                mDirty |= DIRTY_USER_ACTIVITY;
871                return true;
872            }
873        }
874        return false;
875    }
876
877    // Called from native code.
878    private void wakeUpFromNative(long eventTime) {
879        wakeUpInternal(eventTime);
880    }
881
882    private void wakeUpInternal(long eventTime) {
883        synchronized (mLock) {
884            if (wakeUpNoUpdateLocked(eventTime)) {
885                updatePowerStateLocked();
886            }
887        }
888    }
889
890    private boolean wakeUpNoUpdateLocked(long eventTime) {
891        if (DEBUG_SPEW) {
892            Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime);
893        }
894
895        if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
896                || !mBootCompleted || !mSystemReady) {
897            return false;
898        }
899
900        switch (mWakefulness) {
901            case WAKEFULNESS_ASLEEP:
902                Slog.i(TAG, "Waking up from sleep...");
903                break;
904            case WAKEFULNESS_DREAMING:
905                Slog.i(TAG, "Waking up from dream...");
906                break;
907            case WAKEFULNESS_DOZING:
908                Slog.i(TAG, "Waking up from dozing...");
909                break;
910        }
911
912        if (mWakefulness != WAKEFULNESS_DREAMING) {
913            sendPendingNotificationsLocked();
914            mNotifier.onWakeUpStarted();
915            mSendWakeUpFinishedNotificationWhenReady = true;
916        }
917
918        mLastWakeTime = eventTime;
919        mWakefulness = WAKEFULNESS_AWAKE;
920        mDirty |= DIRTY_WAKEFULNESS;
921
922        userActivityNoUpdateLocked(
923                eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
924        return true;
925    }
926
927    // Called from native code.
928    private void goToSleepFromNative(long eventTime, int reason) {
929        goToSleepInternal(eventTime, reason);
930    }
931
932    private void goToSleepInternal(long eventTime, int reason) {
933        synchronized (mLock) {
934            if (goToSleepNoUpdateLocked(eventTime, reason)) {
935                updatePowerStateLocked();
936            }
937        }
938    }
939
940    // This method is called goToSleep for historical reasons but we actually start
941    // dozing before really going to sleep.
942    @SuppressWarnings("deprecation")
943    private boolean goToSleepNoUpdateLocked(long eventTime, int reason) {
944        if (DEBUG_SPEW) {
945            Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime + ", reason=" + reason);
946        }
947
948        if (eventTime < mLastWakeTime
949                || mWakefulness == WAKEFULNESS_ASLEEP
950                || mWakefulness == WAKEFULNESS_DOZING
951                || !mBootCompleted || !mSystemReady) {
952            return false;
953        }
954
955        switch (reason) {
956            case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN:
957                Slog.i(TAG, "Going to sleep due to device administration policy...");
958                break;
959            case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT:
960                Slog.i(TAG, "Going to sleep due to screen timeout...");
961                break;
962            default:
963                Slog.i(TAG, "Going to sleep by user request...");
964                reason = PowerManager.GO_TO_SLEEP_REASON_USER;
965                break;
966        }
967
968        sendPendingNotificationsLocked();
969        mNotifier.onGoToSleepStarted(reason);
970        mSendGoToSleepFinishedNotificationWhenReady = true;
971
972        mLastSleepTime = eventTime;
973        mDirty |= DIRTY_WAKEFULNESS;
974        mWakefulness = WAKEFULNESS_DOZING;
975        mSandmanSummoned = true;
976
977        // Report the number of wake locks that will be cleared by going to sleep.
978        int numWakeLocksCleared = 0;
979        final int numWakeLocks = mWakeLocks.size();
980        for (int i = 0; i < numWakeLocks; i++) {
981            final WakeLock wakeLock = mWakeLocks.get(i);
982            switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
983                case PowerManager.FULL_WAKE_LOCK:
984                case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
985                case PowerManager.SCREEN_DIM_WAKE_LOCK:
986                    numWakeLocksCleared += 1;
987                    break;
988            }
989        }
990        EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared);
991        return true;
992    }
993
994    private void napInternal(long eventTime) {
995        synchronized (mLock) {
996            if (napNoUpdateLocked(eventTime)) {
997                updatePowerStateLocked();
998            }
999        }
1000    }
1001
1002    private boolean napNoUpdateLocked(long eventTime) {
1003        if (DEBUG_SPEW) {
1004            Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime);
1005        }
1006
1007        if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
1008                || !mBootCompleted || !mSystemReady) {
1009            return false;
1010        }
1011
1012        Slog.i(TAG, "Nap time...");
1013
1014        mDirty |= DIRTY_WAKEFULNESS;
1015        mWakefulness = WAKEFULNESS_DREAMING;
1016        mSandmanSummoned = true;
1017        return true;
1018    }
1019
1020    // Done dozing, drop everything and go to sleep.
1021    private boolean reallyGoToSleepNoUpdateLocked(long eventTime) {
1022        if (DEBUG_SPEW) {
1023            Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime);
1024        }
1025
1026        if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1027                || !mBootCompleted || !mSystemReady) {
1028            return false;
1029        }
1030
1031        Slog.i(TAG, "Sleeping...");
1032
1033        mDirty |= DIRTY_WAKEFULNESS;
1034        mWakefulness = WAKEFULNESS_ASLEEP;
1035        return true;
1036    }
1037
1038    /**
1039     * Updates the global power state based on dirty bits recorded in mDirty.
1040     *
1041     * This is the main function that performs power state transitions.
1042     * We centralize them here so that we can recompute the power state completely
1043     * each time something important changes, and ensure that we do it the same
1044     * way each time.  The point is to gather all of the transition logic here.
1045     */
1046    private void updatePowerStateLocked() {
1047        if (!mSystemReady || mDirty == 0) {
1048            return;
1049        }
1050
1051        // Phase 0: Basic state updates.
1052        updateIsPoweredLocked(mDirty);
1053        updateStayOnLocked(mDirty);
1054
1055        // Phase 1: Update wakefulness.
1056        // Loop because the wake lock and user activity computations are influenced
1057        // by changes in wakefulness.
1058        final long now = SystemClock.uptimeMillis();
1059        int dirtyPhase2 = 0;
1060        for (;;) {
1061            int dirtyPhase1 = mDirty;
1062            dirtyPhase2 |= dirtyPhase1;
1063            mDirty = 0;
1064
1065            updateWakeLockSummaryLocked(dirtyPhase1);
1066            updateUserActivitySummaryLocked(now, dirtyPhase1);
1067            if (!updateWakefulnessLocked(dirtyPhase1)) {
1068                break;
1069            }
1070        }
1071
1072        // Phase 2: Update dreams and display power state.
1073        updateDreamLocked(dirtyPhase2);
1074        updateDisplayPowerStateLocked(dirtyPhase2);
1075
1076        // Phase 3: Send notifications, if needed.
1077        if (mDisplayReady) {
1078            sendPendingNotificationsLocked();
1079        }
1080
1081        // Phase 4: Update suspend blocker.
1082        // Because we might release the last suspend blocker here, we need to make sure
1083        // we finished everything else first!
1084        updateSuspendBlockerLocked();
1085    }
1086
1087    private void sendPendingNotificationsLocked() {
1088        if (mSendWakeUpFinishedNotificationWhenReady) {
1089            mSendWakeUpFinishedNotificationWhenReady = false;
1090            mNotifier.onWakeUpFinished();
1091        }
1092        if (mSendGoToSleepFinishedNotificationWhenReady) {
1093            mSendGoToSleepFinishedNotificationWhenReady = false;
1094            mNotifier.onGoToSleepFinished();
1095        }
1096    }
1097
1098    /**
1099     * Updates the value of mIsPowered.
1100     * Sets DIRTY_IS_POWERED if a change occurred.
1101     */
1102    private void updateIsPoweredLocked(int dirty) {
1103        if ((dirty & DIRTY_BATTERY_STATE) != 0) {
1104            final boolean wasPowered = mIsPowered;
1105            final int oldPlugType = mPlugType;
1106            mIsPowered = mBatteryService.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
1107            mPlugType = mBatteryService.getPlugType();
1108            mBatteryLevel = mBatteryService.getBatteryLevel();
1109
1110            if (DEBUG_SPEW) {
1111                Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
1112                        + ", mIsPowered=" + mIsPowered
1113                        + ", oldPlugType=" + oldPlugType
1114                        + ", mPlugType=" + mPlugType
1115                        + ", mBatteryLevel=" + mBatteryLevel);
1116            }
1117
1118            if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
1119                mDirty |= DIRTY_IS_POWERED;
1120
1121                // Update wireless dock detection state.
1122                final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
1123                        mIsPowered, mPlugType, mBatteryLevel);
1124
1125                // Treat plugging and unplugging the devices as a user activity.
1126                // Users find it disconcerting when they plug or unplug the device
1127                // and it shuts off right away.
1128                // Some devices also wake the device when plugged or unplugged because
1129                // they don't have a charging LED.
1130                final long now = SystemClock.uptimeMillis();
1131                if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1132                        dockedOnWirelessCharger)) {
1133                    wakeUpNoUpdateLocked(now);
1134                }
1135                userActivityNoUpdateLocked(
1136                        now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
1137
1138                // Tell the notifier whether wireless charging has started so that
1139                // it can provide feedback to the user.
1140                if (dockedOnWirelessCharger) {
1141                    mNotifier.onWirelessChargingStarted();
1142                }
1143            }
1144        }
1145    }
1146
1147    private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1148            boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
1149        // Don't wake when powered unless configured to do so.
1150        if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1151            return false;
1152        }
1153
1154        // Don't wake when undocked from wireless charger.
1155        // See WirelessChargerDetector for justification.
1156        if (wasPowered && !mIsPowered
1157                && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1158            return false;
1159        }
1160
1161        // Don't wake when docked on wireless charger unless we are certain of it.
1162        // See WirelessChargerDetector for justification.
1163        if (!wasPowered && mIsPowered
1164                && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
1165                && !dockedOnWirelessCharger) {
1166            return false;
1167        }
1168
1169        // If already dreaming and becoming powered, then don't wake.
1170        if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
1171            return false;
1172        }
1173
1174        // Otherwise wake up!
1175        return true;
1176    }
1177
1178    /**
1179     * Updates the value of mStayOn.
1180     * Sets DIRTY_STAY_ON if a change occurred.
1181     */
1182    private void updateStayOnLocked(int dirty) {
1183        if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
1184            final boolean wasStayOn = mStayOn;
1185            if (mStayOnWhilePluggedInSetting != 0
1186                    && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
1187                mStayOn = mBatteryService.isPowered(mStayOnWhilePluggedInSetting);
1188            } else {
1189                mStayOn = false;
1190            }
1191
1192            if (mStayOn != wasStayOn) {
1193                mDirty |= DIRTY_STAY_ON;
1194            }
1195        }
1196    }
1197
1198    /**
1199     * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1200     * Note that most wake-locks are ignored when the system is asleep.
1201     *
1202     * This function must have no other side-effects.
1203     */
1204    @SuppressWarnings("deprecation")
1205    private void updateWakeLockSummaryLocked(int dirty) {
1206        if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1207            mWakeLockSummary = 0;
1208
1209            final int numWakeLocks = mWakeLocks.size();
1210            for (int i = 0; i < numWakeLocks; i++) {
1211                final WakeLock wakeLock = mWakeLocks.get(i);
1212                switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1213                    case PowerManager.PARTIAL_WAKE_LOCK:
1214                        mWakeLockSummary |= WAKE_LOCK_CPU;
1215                        break;
1216                    case PowerManager.FULL_WAKE_LOCK:
1217                        if (mWakefulness == WAKEFULNESS_AWAKE
1218                                || mWakefulness == WAKEFULNESS_DREAMING) {
1219                            mWakeLockSummary |= WAKE_LOCK_CPU
1220                                    | WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
1221                        }
1222                        if (mWakefulness == WAKEFULNESS_AWAKE) {
1223                            mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
1224                        }
1225                        break;
1226                    case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1227                        if (mWakefulness == WAKEFULNESS_AWAKE
1228                                || mWakefulness == WAKEFULNESS_DREAMING) {
1229                            mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_BRIGHT;
1230                        }
1231                        if (mWakefulness == WAKEFULNESS_AWAKE) {
1232                            mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
1233                        }
1234                        break;
1235                    case PowerManager.SCREEN_DIM_WAKE_LOCK:
1236                        if (mWakefulness == WAKEFULNESS_AWAKE
1237                                || mWakefulness == WAKEFULNESS_DREAMING) {
1238                            mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_DIM;
1239                        }
1240                        if (mWakefulness == WAKEFULNESS_AWAKE) {
1241                            mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
1242                        }
1243                        break;
1244                    case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1245                        if (mWakefulness == WAKEFULNESS_AWAKE
1246                                || mWakefulness == WAKEFULNESS_DREAMING
1247                                || mWakefulness == WAKEFULNESS_DOZING) {
1248                            mWakeLockSummary |= WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1249                        }
1250                        break;
1251                    case PowerManager.DOZE_WAKE_LOCK:
1252                        if (mWakefulness == WAKEFULNESS_DOZING) {
1253                            mWakeLockSummary |= WAKE_LOCK_DOZE;
1254                        }
1255                        break;
1256                }
1257            }
1258
1259            if (DEBUG_SPEW) {
1260                Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
1261                        + wakefulnessToString(mWakefulness)
1262                        + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1263            }
1264        }
1265    }
1266
1267    /**
1268     * Updates the value of mUserActivitySummary to summarize the user requested
1269     * state of the system such as whether the screen should be bright or dim.
1270     * Note that user activity is ignored when the system is asleep.
1271     *
1272     * This function must have no other side-effects.
1273     */
1274    private void updateUserActivitySummaryLocked(long now, int dirty) {
1275        // Update the status of the user activity timeout timer.
1276        if ((dirty & (DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
1277            mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
1278
1279            long nextTimeout = 0;
1280            if (mWakefulness == WAKEFULNESS_AWAKE
1281                    || mWakefulness == WAKEFULNESS_DREAMING) {
1282                final int screenOffTimeout = getScreenOffTimeoutLocked();
1283                final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
1284
1285                mUserActivitySummary = 0;
1286                if (mLastUserActivityTime >= mLastWakeTime) {
1287                    nextTimeout = mLastUserActivityTime
1288                            + screenOffTimeout - screenDimDuration;
1289                    if (now < nextTimeout) {
1290                        mUserActivitySummary |= USER_ACTIVITY_SCREEN_BRIGHT;
1291                    } else {
1292                        nextTimeout = mLastUserActivityTime + screenOffTimeout;
1293                        if (now < nextTimeout) {
1294                            mUserActivitySummary |= USER_ACTIVITY_SCREEN_DIM;
1295                        }
1296                    }
1297                }
1298                if (mUserActivitySummary == 0
1299                        && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
1300                    nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
1301                    if (now < nextTimeout
1302                            && mDisplayPowerRequest.wantScreenOnNormal()) {
1303                        mUserActivitySummary = mDisplayPowerRequest.screenState
1304                                == DisplayPowerRequest.SCREEN_STATE_BRIGHT ?
1305                                USER_ACTIVITY_SCREEN_BRIGHT : USER_ACTIVITY_SCREEN_DIM;
1306                    }
1307                }
1308                if (mUserActivitySummary != 0) {
1309                    Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
1310                    msg.setAsynchronous(true);
1311                    mHandler.sendMessageAtTime(msg, nextTimeout);
1312                }
1313            } else {
1314                mUserActivitySummary = 0;
1315            }
1316
1317            if (DEBUG_SPEW) {
1318                Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
1319                        + wakefulnessToString(mWakefulness)
1320                        + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
1321                        + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
1322            }
1323        }
1324    }
1325
1326    /**
1327     * Called when a user activity timeout has occurred.
1328     * Simply indicates that something about user activity has changed so that the new
1329     * state can be recomputed when the power state is updated.
1330     *
1331     * This function must have no other side-effects besides setting the dirty
1332     * bit and calling update power state.  Wakefulness transitions are handled elsewhere.
1333     */
1334    private void handleUserActivityTimeout() { // runs on handler thread
1335        synchronized (mLock) {
1336            if (DEBUG_SPEW) {
1337                Slog.d(TAG, "handleUserActivityTimeout");
1338            }
1339
1340            mDirty |= DIRTY_USER_ACTIVITY;
1341            updatePowerStateLocked();
1342        }
1343    }
1344
1345    private int getScreenOffTimeoutLocked() {
1346        int timeout = mScreenOffTimeoutSetting;
1347        if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
1348            timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
1349        }
1350        if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
1351            timeout = (int)Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
1352        }
1353        return Math.max(timeout, MINIMUM_SCREEN_OFF_TIMEOUT);
1354    }
1355
1356    private int getScreenDimDurationLocked(int screenOffTimeout) {
1357        return Math.min(SCREEN_DIM_DURATION,
1358                (int)(screenOffTimeout * MAXIMUM_SCREEN_DIM_RATIO));
1359    }
1360
1361    /**
1362     * Updates the wakefulness of the device.
1363     *
1364     * This is the function that decides whether the device should start dreaming
1365     * based on the current wake locks and user activity state.  It may modify mDirty
1366     * if the wakefulness changes.
1367     *
1368     * Returns true if the wakefulness changed and we need to restart power state calculation.
1369     */
1370    private boolean updateWakefulnessLocked(int dirty) {
1371        boolean changed = false;
1372        if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
1373                | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
1374                | DIRTY_DOCK_STATE)) != 0) {
1375            if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
1376                if (DEBUG_SPEW) {
1377                    Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
1378                }
1379                final long time = SystemClock.uptimeMillis();
1380                if (shouldNapAtBedTimeLocked()) {
1381                    changed = napNoUpdateLocked(time);
1382                } else {
1383                    changed = goToSleepNoUpdateLocked(time,
1384                            PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
1385                }
1386            }
1387        }
1388        return changed;
1389    }
1390
1391    /**
1392     * Returns true if the device should automatically nap and start dreaming when the user
1393     * activity timeout has expired and it's bedtime.
1394     */
1395    private boolean shouldNapAtBedTimeLocked() {
1396        return mDreamsActivateOnSleepSetting
1397                || (mDreamsActivateOnDockSetting
1398                        && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
1399    }
1400
1401    /**
1402     * Returns true if the device should go to sleep now.
1403     * Also used when exiting a dream to determine whether we should go back
1404     * to being fully awake or else go to sleep for good.
1405     */
1406    private boolean isItBedTimeYetLocked() {
1407        return mBootCompleted && !isBeingKeptAwakeLocked();
1408    }
1409
1410    /**
1411     * Returns true if the device is being kept awake by a wake lock, user activity
1412     * or the stay on while powered setting.  We also keep the phone awake when
1413     * the proximity sensor returns a positive result so that the device does not
1414     * lock while in a phone call.  This function only controls whether the device
1415     * will go to sleep or dream which is independent of whether it will be allowed
1416     * to suspend.
1417     */
1418    private boolean isBeingKeptAwakeLocked() {
1419        return mStayOn
1420                || mProximityPositive
1421                || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
1422                || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
1423                        | USER_ACTIVITY_SCREEN_DIM)) != 0;
1424    }
1425
1426    /**
1427     * Determines whether to post a message to the sandman to update the dream state.
1428     */
1429    private void updateDreamLocked(int dirty) {
1430        if ((dirty & (DIRTY_WAKEFULNESS
1431                | DIRTY_USER_ACTIVITY
1432                | DIRTY_WAKE_LOCKS
1433                | DIRTY_BOOT_COMPLETED
1434                | DIRTY_SETTINGS
1435                | DIRTY_IS_POWERED
1436                | DIRTY_STAY_ON
1437                | DIRTY_PROXIMITY_POSITIVE
1438                | DIRTY_BATTERY_STATE)) != 0) {
1439            scheduleSandmanLocked();
1440        }
1441    }
1442
1443    private void scheduleSandmanLocked() {
1444        if (!mSandmanScheduled) {
1445            mSandmanScheduled = true;
1446            Message msg = mHandler.obtainMessage(MSG_SANDMAN);
1447            msg.setAsynchronous(true);
1448            mHandler.sendMessage(msg);
1449        }
1450    }
1451
1452    /**
1453     * Called when the device enters or exits a dreaming or dozing state.
1454     *
1455     * We do this asynchronously because we must call out of the power manager to start
1456     * the dream and we don't want to hold our lock while doing so.  There is a risk that
1457     * the device will wake or go to sleep in the meantime so we have to handle that case.
1458     */
1459    private void handleSandman() { // runs on handler thread
1460        // Handle preconditions.
1461        final boolean startDreaming;
1462        final int wakefulness;
1463        synchronized (mLock) {
1464            mSandmanScheduled = false;
1465            wakefulness = mWakefulness;
1466            if (mSandmanSummoned) {
1467                startDreaming = ((wakefulness == WAKEFULNESS_DREAMING && canDreamLocked())
1468                        || wakefulness == WAKEFULNESS_DOZING);
1469                mSandmanSummoned = false;
1470            } else {
1471                startDreaming = false;
1472            }
1473        }
1474
1475        // Start dreaming if needed.
1476        // We only control the dream on the handler thread, so we don't need to worry about
1477        // concurrent attempts to start or stop the dream.
1478        final boolean isDreaming;
1479        if (mDreamManager != null) {
1480            // Restart the dream whenever the sandman is summoned.
1481            if (startDreaming) {
1482                mDreamManager.stopDream();
1483                mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
1484            }
1485            isDreaming = mDreamManager.isDreaming();
1486        } else {
1487            isDreaming = false;
1488        }
1489
1490        // Update dream state.
1491        synchronized (mLock) {
1492            // Remember the initial battery level when the dream started.
1493            if (startDreaming && isDreaming) {
1494                mBatteryLevelWhenDreamStarted = mBatteryLevel;
1495                if (wakefulness == WAKEFULNESS_DOZING) {
1496                    Slog.i(TAG, "Dozing...");
1497                } else {
1498                    Slog.i(TAG, "Dreaming...");
1499                }
1500            }
1501
1502            // If preconditions changed, wait for the next iteration to determine
1503            // whether the dream should continue (or be restarted).
1504            if (mSandmanSummoned || mWakefulness != wakefulness) {
1505                return; // wait for next cycle
1506            }
1507
1508            // Determine whether the dream should continue.
1509            if (wakefulness == WAKEFULNESS_DREAMING) {
1510                if (isDreaming && canDreamLocked()) {
1511                    if (mDreamsBatteryLevelDrainCutoffConfig >= 0
1512                            && mBatteryLevel < mBatteryLevelWhenDreamStarted
1513                                    - mDreamsBatteryLevelDrainCutoffConfig
1514                            && !isBeingKeptAwakeLocked()) {
1515                        // If the user activity timeout expired and the battery appears
1516                        // to be draining faster than it is charging then stop dreaming
1517                        // and go to sleep.
1518                        Slog.i(TAG, "Stopping dream because the battery appears to "
1519                                + "be draining faster than it is charging.  "
1520                                + "Battery level when dream started: "
1521                                + mBatteryLevelWhenDreamStarted + "%.  "
1522                                + "Battery level now: " + mBatteryLevel + "%.");
1523                    } else {
1524                        return; // continue dreaming
1525                    }
1526                }
1527
1528                // Dream has ended or will be stopped.  Update the power state.
1529                if (isItBedTimeYetLocked()) {
1530                    goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
1531                            PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
1532                    updatePowerStateLocked();
1533                } else {
1534                    wakeUpNoUpdateLocked(SystemClock.uptimeMillis());
1535                    updatePowerStateLocked();
1536                }
1537            } else if (wakefulness == WAKEFULNESS_DOZING) {
1538                if (isDreaming) {
1539                    return; // continue dozing
1540                }
1541
1542                // Doze has ended or will be stopped.  Update the power state.
1543                reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis());
1544                updatePowerStateLocked();
1545            }
1546        }
1547
1548        // Stop dream.
1549        if (isDreaming) {
1550            mDreamManager.stopDream();
1551        }
1552    }
1553
1554    /**
1555     * Returns true if the device is allowed to dream in its current state.
1556     * This function is not called when dozing.
1557     */
1558    private boolean canDreamLocked() {
1559        if (mWakefulness != WAKEFULNESS_DREAMING
1560                || !mDreamsSupportedConfig
1561                || !mDreamsEnabledSetting
1562                || !mDisplayPowerRequest.wantScreenOnNormal()
1563                || !mBootCompleted) {
1564            return false;
1565        }
1566        if (!isBeingKeptAwakeLocked()) {
1567            if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
1568                return false;
1569            }
1570            if (!mIsPowered
1571                    && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
1572                    && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
1573                return false;
1574            }
1575            if (mIsPowered
1576                    && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
1577                    && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
1578                return false;
1579            }
1580        }
1581        return true;
1582    }
1583
1584    private void handleScreenOnBlockerReleased() {
1585        synchronized (mLock) {
1586            mDirty |= DIRTY_SCREEN_ON_BLOCKER_RELEASED;
1587            updatePowerStateLocked();
1588        }
1589    }
1590
1591    /**
1592     * Updates the display power state asynchronously.
1593     * When the update is finished, mDisplayReady will be set to true.  The display
1594     * controller posts a message to tell us when the actual display power state
1595     * has been updated so we come back here to double-check and finish up.
1596     *
1597     * This function recalculates the display power state each time.
1598     */
1599    private void updateDisplayPowerStateLocked(int dirty) {
1600        if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
1601                | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
1602                | DIRTY_SETTINGS | DIRTY_SCREEN_ON_BLOCKER_RELEASED)) != 0) {
1603            final int newScreenState = getDesiredScreenPowerStateLocked();
1604            mDisplayPowerRequest.screenState = newScreenState;
1605            nativeSetPowerState(isScreenOnLocked(),
1606                    newScreenState == DisplayPowerRequest.SCREEN_STATE_BRIGHT);
1607
1608            int screenBrightness = mScreenBrightnessSettingDefault;
1609            float screenAutoBrightnessAdjustment = 0.0f;
1610            boolean autoBrightness = (mScreenBrightnessModeSetting ==
1611                    Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
1612            if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
1613                screenBrightness = mScreenBrightnessOverrideFromWindowManager;
1614                autoBrightness = false;
1615            } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) {
1616                screenBrightness = mTemporaryScreenBrightnessSettingOverride;
1617            } else if (isValidBrightness(mScreenBrightnessSetting)) {
1618                screenBrightness = mScreenBrightnessSetting;
1619            }
1620            if (autoBrightness) {
1621                screenBrightness = mScreenBrightnessSettingDefault;
1622                if (isValidAutoBrightnessAdjustment(
1623                        mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) {
1624                    screenAutoBrightnessAdjustment =
1625                            mTemporaryScreenAutoBrightnessAdjustmentSettingOverride;
1626                } else if (isValidAutoBrightnessAdjustment(
1627                        mScreenAutoBrightnessAdjustmentSetting)) {
1628                    screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting;
1629                }
1630            }
1631            screenBrightness = Math.max(Math.min(screenBrightness,
1632                    mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum);
1633            screenAutoBrightnessAdjustment = Math.max(Math.min(
1634                    screenAutoBrightnessAdjustment, 1.0f), -1.0f);
1635            mDisplayPowerRequest.screenBrightness = screenBrightness;
1636            mDisplayPowerRequest.screenAutoBrightnessAdjustment =
1637                    screenAutoBrightnessAdjustment;
1638            mDisplayPowerRequest.useAutoBrightness = autoBrightness;
1639
1640            mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
1641
1642            mDisplayPowerRequest.blockScreenOn = mScreenOnBlocker.isHeld();
1643
1644            mDisplayReady = mDisplayPowerController.requestPowerState(mDisplayPowerRequest,
1645                    mRequestWaitForNegativeProximity);
1646            mRequestWaitForNegativeProximity = false;
1647
1648            if (DEBUG_SPEW) {
1649                Slog.d(TAG, "updateScreenStateLocked: mDisplayReady=" + mDisplayReady
1650                        + ", newScreenState=" + newScreenState
1651                        + ", mWakefulness=" + mWakefulness
1652                        + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
1653                        + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
1654                        + ", mBootCompleted=" + mBootCompleted);
1655            }
1656        }
1657    }
1658
1659    private static boolean isValidBrightness(int value) {
1660        return value >= 0 && value <= 255;
1661    }
1662
1663    private static boolean isValidAutoBrightnessAdjustment(float value) {
1664        // Handles NaN by always returning false.
1665        return value >= -1.0f && value <= 1.0f;
1666    }
1667
1668    private int getDesiredScreenPowerStateLocked() {
1669        if (mWakefulness == WAKEFULNESS_ASLEEP) {
1670            return DisplayPowerRequest.SCREEN_STATE_OFF;
1671        }
1672
1673        if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1674            return DisplayPowerRequest.SCREEN_STATE_DOZE;
1675        }
1676
1677        if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
1678                || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
1679                || !mBootCompleted) {
1680            return DisplayPowerRequest.SCREEN_STATE_BRIGHT;
1681        }
1682
1683        return DisplayPowerRequest.SCREEN_STATE_DIM;
1684    }
1685
1686    private final DisplayPowerController.Callbacks mDisplayPowerControllerCallbacks =
1687            new DisplayPowerController.Callbacks() {
1688        @Override
1689        public void onStateChanged() {
1690            synchronized (mLock) {
1691                mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
1692                updatePowerStateLocked();
1693            }
1694        }
1695
1696        @Override
1697        public void onProximityPositive() {
1698            synchronized (mLock) {
1699                mProximityPositive = true;
1700                mDirty |= DIRTY_PROXIMITY_POSITIVE;
1701                updatePowerStateLocked();
1702            }
1703        }
1704
1705        @Override
1706        public void onProximityNegative() {
1707            synchronized (mLock) {
1708                mProximityPositive = false;
1709                mDirty |= DIRTY_PROXIMITY_POSITIVE;
1710                userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1711                        PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
1712                updatePowerStateLocked();
1713            }
1714        }
1715    };
1716
1717    private boolean shouldUseProximitySensorLocked() {
1718        return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
1719    }
1720
1721    /**
1722     * Updates the suspend blocker that keeps the CPU alive.
1723     *
1724     * This function must have no other side-effects.
1725     */
1726    private void updateSuspendBlockerLocked() {
1727        final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
1728        final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
1729        final boolean autoSuspend = !needDisplaySuspendBlocker;
1730
1731        // Disable auto-suspend if needed.
1732        if (!autoSuspend) {
1733            if (mDecoupleAutoSuspendModeFromDisplayConfig) {
1734                setAutoSuspendModeLocked(false);
1735            }
1736            if (mDecoupleInteractiveModeFromDisplayConfig) {
1737                setInteractiveModeLocked(true);
1738            }
1739        }
1740
1741        // First acquire suspend blockers if needed.
1742        if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
1743            mWakeLockSuspendBlocker.acquire();
1744            mHoldingWakeLockSuspendBlocker = true;
1745        }
1746        if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
1747            mDisplaySuspendBlocker.acquire();
1748            mHoldingDisplaySuspendBlocker = true;
1749        }
1750
1751        // Then release suspend blockers if needed.
1752        if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
1753            mWakeLockSuspendBlocker.release();
1754            mHoldingWakeLockSuspendBlocker = false;
1755        }
1756        if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
1757            mDisplaySuspendBlocker.release();
1758            mHoldingDisplaySuspendBlocker = false;
1759        }
1760
1761        // Enable auto-suspend if needed.
1762        if (autoSuspend) {
1763            if (mDecoupleInteractiveModeFromDisplayConfig) {
1764                setInteractiveModeLocked(false);
1765            }
1766            if (mDecoupleAutoSuspendModeFromDisplayConfig) {
1767                setAutoSuspendModeLocked(true);
1768            }
1769        }
1770    }
1771
1772    /**
1773     * Return true if we must keep a suspend blocker active on behalf of the display.
1774     * We do so if the screen is on or is in transition between states.
1775     */
1776    private boolean needDisplaySuspendBlockerLocked() {
1777        if (!mDisplayReady) {
1778            return true;
1779        }
1780        if (mDisplayPowerRequest.wantScreenOnNormal()) {
1781            // If we asked for the screen to be on but it is off due to the proximity
1782            // sensor then we may suspend but only if the configuration allows it.
1783            // On some hardware it may not be safe to suspend because the proximity
1784            // sensor may not be correctly configured as a wake-up source.
1785            if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
1786                    || !mSuspendWhenScreenOffDueToProximityConfig) {
1787                return true;
1788            }
1789        }
1790        // Let the system suspend if the screen is off or dozing.
1791        return false;
1792    }
1793
1794    private void setAutoSuspendModeLocked(boolean enable) {
1795        if (enable != mAutoSuspendModeEnabled) {
1796            if (DEBUG) {
1797                Slog.d(TAG, "Setting auto-suspend mode to " + enable);
1798            }
1799            mAutoSuspendModeEnabled = enable;
1800            nativeSetAutoSuspend(enable);
1801        }
1802    }
1803
1804    private void setInteractiveModeLocked(boolean enable) {
1805        if (enable != mInteractiveModeEnabled) {
1806            if (DEBUG) {
1807                Slog.d(TAG, "Setting interactive mode to " + enable);
1808            }
1809            mInteractiveModeEnabled = enable;
1810            nativeSetInteractive(enable);
1811        }
1812    }
1813
1814    private boolean isScreenOnInternal() {
1815        synchronized (mLock) {
1816            return isScreenOnLocked();
1817        }
1818    }
1819
1820    private boolean isScreenOnLocked() {
1821        return mWakefulness == WAKEFULNESS_AWAKE
1822                || mWakefulness == WAKEFULNESS_DREAMING;
1823    }
1824
1825    private void handleBatteryStateChangedLocked() {
1826        mDirty |= DIRTY_BATTERY_STATE;
1827        updatePowerStateLocked();
1828    }
1829
1830    private void startWatchingForBootAnimationFinished() {
1831        mHandler.sendEmptyMessage(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED);
1832    }
1833
1834    private void checkIfBootAnimationFinished() {
1835        if (DEBUG) {
1836            Slog.d(TAG, "Check if boot animation finished...");
1837        }
1838
1839        if (SystemService.isRunning(BOOT_ANIMATION_SERVICE)) {
1840            mHandler.sendEmptyMessageDelayed(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED,
1841                    BOOT_ANIMATION_POLL_INTERVAL);
1842            return;
1843        }
1844
1845        synchronized (mLock) {
1846            if (!mBootCompleted) {
1847                Slog.i(TAG, "Boot animation finished.");
1848                handleBootCompletedLocked();
1849            }
1850        }
1851    }
1852
1853    private void handleBootCompletedLocked() {
1854        final long now = SystemClock.uptimeMillis();
1855        mBootCompleted = true;
1856        mDirty |= DIRTY_BOOT_COMPLETED;
1857        userActivityNoUpdateLocked(
1858                now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
1859        updatePowerStateLocked();
1860    }
1861
1862    private void shutdownOrRebootInternal(final boolean shutdown, final boolean confirm,
1863            final String reason, boolean wait) {
1864        if (mHandler == null || !mSystemReady) {
1865            throw new IllegalStateException("Too early to call shutdown() or reboot()");
1866        }
1867
1868        Runnable runnable = new Runnable() {
1869            @Override
1870            public void run() {
1871                synchronized (this) {
1872                    if (shutdown) {
1873                        ShutdownThread.shutdown(mContext, confirm);
1874                    } else {
1875                        ShutdownThread.reboot(mContext, reason, confirm);
1876                    }
1877                }
1878            }
1879        };
1880
1881        // ShutdownThread must run on a looper capable of displaying the UI.
1882        Message msg = Message.obtain(mHandler, runnable);
1883        msg.setAsynchronous(true);
1884        mHandler.sendMessage(msg);
1885
1886        // PowerManager.reboot() is documented not to return so just wait for the inevitable.
1887        if (wait) {
1888            synchronized (runnable) {
1889                while (true) {
1890                    try {
1891                        runnable.wait();
1892                    } catch (InterruptedException e) {
1893                    }
1894                }
1895            }
1896        }
1897    }
1898
1899    private void crashInternal(final String message) {
1900        Thread t = new Thread("PowerManagerService.crash()") {
1901            @Override
1902            public void run() {
1903                throw new RuntimeException(message);
1904            }
1905        };
1906        try {
1907            t.start();
1908            t.join();
1909        } catch (InterruptedException e) {
1910            Log.wtf(TAG, e);
1911        }
1912    }
1913
1914    private void setStayOnSettingInternal(int val) {
1915        Settings.Global.putInt(mContext.getContentResolver(),
1916                Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
1917    }
1918
1919    private void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) {
1920        synchronized (mLock) {
1921            mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
1922            mDirty |= DIRTY_SETTINGS;
1923            updatePowerStateLocked();
1924        }
1925    }
1926
1927    private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
1928        return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
1929                && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE;
1930    }
1931
1932    private void setAttentionLightInternal(boolean on, int color) {
1933        Light light;
1934        synchronized (mLock) {
1935            if (!mSystemReady) {
1936                return;
1937            }
1938            light = mAttentionLight;
1939        }
1940
1941        // Control light outside of lock.
1942        light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
1943    }
1944
1945    private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
1946        synchronized (mLock) {
1947            if (mScreenBrightnessOverrideFromWindowManager != brightness) {
1948                mScreenBrightnessOverrideFromWindowManager = brightness;
1949                mDirty |= DIRTY_SETTINGS;
1950                updatePowerStateLocked();
1951            }
1952        }
1953    }
1954
1955    private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
1956        synchronized (mLock) {
1957            if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
1958                mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
1959                mDirty |= DIRTY_SETTINGS;
1960                updatePowerStateLocked();
1961            }
1962        }
1963    }
1964
1965    private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) {
1966        synchronized (mLock) {
1967            if (mTemporaryScreenBrightnessSettingOverride != brightness) {
1968                mTemporaryScreenBrightnessSettingOverride = brightness;
1969                mDirty |= DIRTY_SETTINGS;
1970                updatePowerStateLocked();
1971            }
1972        }
1973    }
1974
1975    private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) {
1976        synchronized (mLock) {
1977            // Note: This condition handles NaN because NaN is not equal to any other
1978            // value, including itself.
1979            if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) {
1980                mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj;
1981                mDirty |= DIRTY_SETTINGS;
1982                updatePowerStateLocked();
1983            }
1984        }
1985    }
1986
1987    /**
1988     * Low-level function turn the device off immediately, without trying
1989     * to be clean.  Most people should use {@link ShutdownThread} for a clean shutdown.
1990     */
1991    public static void lowLevelShutdown() {
1992        SystemProperties.set("sys.powerctl", "shutdown");
1993    }
1994
1995    /**
1996     * Low-level function to reboot the device. On success, this
1997     * function doesn't return. If more than 20 seconds passes from
1998     * the time a reboot is requested (120 seconds for reboot to
1999     * recovery), this method returns.
2000     *
2001     * @param reason code to pass to the kernel (e.g. "recovery"), or null.
2002     */
2003    public static void lowLevelReboot(String reason) {
2004        if (reason == null) {
2005            reason = "";
2006        }
2007        long duration;
2008        if (reason.equals(PowerManager.REBOOT_RECOVERY)) {
2009            // If we are rebooting to go into recovery, instead of
2010            // setting sys.powerctl directly we'll start the
2011            // pre-recovery service which will do some preparation for
2012            // recovery and then reboot for us.
2013            //
2014            // This preparation can take more than 20 seconds if
2015            // there's a very large update package, so lengthen the
2016            // timeout.
2017            SystemProperties.set("ctl.start", "pre-recovery");
2018            duration = 120 * 1000L;
2019        } else {
2020            SystemProperties.set("sys.powerctl", "reboot," + reason);
2021            duration = 20 * 1000L;
2022        }
2023        try {
2024            Thread.sleep(duration);
2025        } catch (InterruptedException e) {
2026            Thread.currentThread().interrupt();
2027        }
2028    }
2029
2030    @Override // Watchdog.Monitor implementation
2031    public void monitor() {
2032        // Grab and release lock for watchdog monitor to detect deadlocks.
2033        synchronized (mLock) {
2034        }
2035    }
2036
2037    private void dumpInternal(PrintWriter pw) {
2038        pw.println("POWER MANAGER (dumpsys power)\n");
2039
2040        final DisplayPowerController dpc;
2041        final WirelessChargerDetector wcd;
2042        synchronized (mLock) {
2043            pw.println("Power Manager State:");
2044            pw.println("  mDirty=0x" + Integer.toHexString(mDirty));
2045            pw.println("  mWakefulness=" + wakefulnessToString(mWakefulness));
2046            pw.println("  mIsPowered=" + mIsPowered);
2047            pw.println("  mPlugType=" + mPlugType);
2048            pw.println("  mBatteryLevel=" + mBatteryLevel);
2049            pw.println("  mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
2050            pw.println("  mDockState=" + mDockState);
2051            pw.println("  mStayOn=" + mStayOn);
2052            pw.println("  mProximityPositive=" + mProximityPositive);
2053            pw.println("  mBootCompleted=" + mBootCompleted);
2054            pw.println("  mSystemReady=" + mSystemReady);
2055            pw.println("  mAutoSuspendModeEnabled=" + mAutoSuspendModeEnabled);
2056            pw.println("  mInteactiveModeEnabled=" + mInteractiveModeEnabled);
2057            pw.println("  mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
2058            pw.println("  mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
2059            pw.println("  mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
2060            pw.println("  mSandmanScheduled=" + mSandmanScheduled);
2061            pw.println("  mSandmanSummoned=" + mSandmanSummoned);
2062            pw.println("  mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
2063            pw.println("  mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
2064            pw.println("  mSendWakeUpFinishedNotificationWhenReady="
2065                    + mSendWakeUpFinishedNotificationWhenReady);
2066            pw.println("  mSendGoToSleepFinishedNotificationWhenReady="
2067                    + mSendGoToSleepFinishedNotificationWhenReady);
2068            pw.println("  mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
2069            pw.println("  mLastUserActivityTimeNoChangeLights="
2070                    + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
2071            pw.println("  mDisplayReady=" + mDisplayReady);
2072            pw.println("  mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
2073            pw.println("  mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
2074
2075            pw.println();
2076            pw.println("Settings and Configuration:");
2077            pw.println("  mDecoupleAutoSuspendModeFromDisplayConfig="
2078                    + mDecoupleAutoSuspendModeFromDisplayConfig);
2079            pw.println("  mDecoupleInteractiveModeFromDisplayConfig="
2080                    + mDecoupleInteractiveModeFromDisplayConfig);
2081            pw.println("  mWakeUpWhenPluggedOrUnpluggedConfig="
2082                    + mWakeUpWhenPluggedOrUnpluggedConfig);
2083            pw.println("  mSuspendWhenScreenOffDueToProximityConfig="
2084                    + mSuspendWhenScreenOffDueToProximityConfig);
2085            pw.println("  mDreamsSupportedConfig=" + mDreamsSupportedConfig);
2086            pw.println("  mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
2087            pw.println("  mDreamsActivatedOnSleepByDefaultConfig="
2088                    + mDreamsActivatedOnSleepByDefaultConfig);
2089            pw.println("  mDreamsActivatedOnDockByDefaultConfig="
2090                    + mDreamsActivatedOnDockByDefaultConfig);
2091            pw.println("  mDreamsEnabledOnBatteryConfig="
2092                    + mDreamsEnabledOnBatteryConfig);
2093            pw.println("  mDreamsBatteryLevelMinimumWhenPoweredConfig="
2094                    + mDreamsBatteryLevelMinimumWhenPoweredConfig);
2095            pw.println("  mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
2096                    + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
2097            pw.println("  mDreamsBatteryLevelDrainCutoffConfig="
2098                    + mDreamsBatteryLevelDrainCutoffConfig);
2099            pw.println("  mDreamsEnabledSetting=" + mDreamsEnabledSetting);
2100            pw.println("  mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
2101            pw.println("  mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
2102            pw.println("  mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
2103            pw.println("  mMaximumScreenOffTimeoutFromDeviceAdmin="
2104                    + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
2105                    + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
2106            pw.println("  mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
2107            pw.println("  mScreenBrightnessSetting=" + mScreenBrightnessSetting);
2108            pw.println("  mScreenAutoBrightnessAdjustmentSetting="
2109                    + mScreenAutoBrightnessAdjustmentSetting);
2110            pw.println("  mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
2111            pw.println("  mScreenBrightnessOverrideFromWindowManager="
2112                    + mScreenBrightnessOverrideFromWindowManager);
2113            pw.println("  mUserActivityTimeoutOverrideFromWindowManager="
2114                    + mUserActivityTimeoutOverrideFromWindowManager);
2115            pw.println("  mTemporaryScreenBrightnessSettingOverride="
2116                    + mTemporaryScreenBrightnessSettingOverride);
2117            pw.println("  mTemporaryScreenAutoBrightnessAdjustmentSettingOverride="
2118                    + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride);
2119            pw.println("  mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
2120            pw.println("  mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
2121            pw.println("  mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
2122
2123            final int screenOffTimeout = getScreenOffTimeoutLocked();
2124            final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
2125            pw.println();
2126            pw.println("Screen off timeout: " + screenOffTimeout + " ms");
2127            pw.println("Screen dim duration: " + screenDimDuration + " ms");
2128
2129            pw.println();
2130            pw.println("Wake Locks: size=" + mWakeLocks.size());
2131            for (WakeLock wl : mWakeLocks) {
2132                pw.println("  " + wl);
2133            }
2134
2135            pw.println();
2136            pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
2137            for (SuspendBlocker sb : mSuspendBlockers) {
2138                pw.println("  " + sb);
2139            }
2140
2141            pw.println();
2142            pw.println("Screen On Blocker: " + mScreenOnBlocker);
2143
2144            pw.println();
2145            pw.println("Display Blanker: " + mDisplayBlanker);
2146
2147            dpc = mDisplayPowerController;
2148            wcd = mWirelessChargerDetector;
2149        }
2150
2151        if (dpc != null) {
2152            dpc.dump(pw);
2153        }
2154
2155        if (wcd != null) {
2156            wcd.dump(pw);
2157        }
2158    }
2159
2160    private SuspendBlocker createSuspendBlockerLocked(String name) {
2161        SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name);
2162        mSuspendBlockers.add(suspendBlocker);
2163        return suspendBlocker;
2164    }
2165
2166    private static String wakefulnessToString(int wakefulness) {
2167        switch (wakefulness) {
2168            case WAKEFULNESS_ASLEEP:
2169                return "Asleep";
2170            case WAKEFULNESS_AWAKE:
2171                return "Awake";
2172            case WAKEFULNESS_DREAMING:
2173                return "Dreaming";
2174            case WAKEFULNESS_DOZING:
2175                return "Dozing";
2176            default:
2177                return Integer.toString(wakefulness);
2178        }
2179    }
2180
2181    private static WorkSource copyWorkSource(WorkSource workSource) {
2182        return workSource != null ? new WorkSource(workSource) : null;
2183    }
2184
2185    private final class BatteryReceiver extends BroadcastReceiver {
2186        @Override
2187        public void onReceive(Context context, Intent intent) {
2188            synchronized (mLock) {
2189                handleBatteryStateChangedLocked();
2190            }
2191        }
2192    }
2193
2194    private final class BootCompletedReceiver extends BroadcastReceiver {
2195        @Override
2196        public void onReceive(Context context, Intent intent) {
2197            // This is our early signal that the system thinks it has finished booting.
2198            // However, the boot animation may still be running for a few more seconds
2199            // since it is ultimately in charge of when it terminates.
2200            // Defer transitioning into the boot completed state until the animation exits.
2201            // We do this so that the screen does not start to dim prematurely before
2202            // the user has actually had a chance to interact with the device.
2203            startWatchingForBootAnimationFinished();
2204        }
2205    }
2206
2207    private final class DreamReceiver extends BroadcastReceiver {
2208        @Override
2209        public void onReceive(Context context, Intent intent) {
2210            synchronized (mLock) {
2211                scheduleSandmanLocked();
2212            }
2213        }
2214    }
2215
2216    private final class UserSwitchedReceiver extends BroadcastReceiver {
2217        @Override
2218        public void onReceive(Context context, Intent intent) {
2219            synchronized (mLock) {
2220                handleSettingsChangedLocked();
2221            }
2222        }
2223    }
2224
2225    private final class DockReceiver extends BroadcastReceiver {
2226        @Override
2227        public void onReceive(Context context, Intent intent) {
2228            synchronized (mLock) {
2229                int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
2230                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
2231                if (mDockState != dockState) {
2232                    mDockState = dockState;
2233                    mDirty |= DIRTY_DOCK_STATE;
2234                    updatePowerStateLocked();
2235                }
2236            }
2237        }
2238    }
2239
2240    private final class SettingsObserver extends ContentObserver {
2241        public SettingsObserver(Handler handler) {
2242            super(handler);
2243        }
2244
2245        @Override
2246        public void onChange(boolean selfChange, Uri uri) {
2247            synchronized (mLock) {
2248                handleSettingsChangedLocked();
2249            }
2250        }
2251    }
2252
2253    /**
2254     * Handler for asynchronous operations performed by the power manager.
2255     */
2256    private final class PowerManagerHandler extends Handler {
2257        public PowerManagerHandler(Looper looper) {
2258            super(looper, null, true /*async*/);
2259        }
2260
2261        @Override
2262        public void handleMessage(Message msg) {
2263            switch (msg.what) {
2264                case MSG_USER_ACTIVITY_TIMEOUT:
2265                    handleUserActivityTimeout();
2266                    break;
2267                case MSG_SANDMAN:
2268                    handleSandman();
2269                    break;
2270                case MSG_SCREEN_ON_BLOCKER_RELEASED:
2271                    handleScreenOnBlockerReleased();
2272                    break;
2273                case MSG_CHECK_IF_BOOT_ANIMATION_FINISHED:
2274                    checkIfBootAnimationFinished();
2275                    break;
2276            }
2277        }
2278    }
2279
2280    /**
2281     * Represents a wake lock that has been acquired by an application.
2282     */
2283    private final class WakeLock implements IBinder.DeathRecipient {
2284        public final IBinder mLock;
2285        public int mFlags;
2286        public String mTag;
2287        public final String mPackageName;
2288        public WorkSource mWorkSource;
2289        public String mHistoryTag;
2290        public final int mOwnerUid;
2291        public final int mOwnerPid;
2292        public boolean mNotifiedAcquired;
2293
2294        public WakeLock(IBinder lock, int flags, String tag, String packageName,
2295                WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
2296            mLock = lock;
2297            mFlags = flags;
2298            mTag = tag;
2299            mPackageName = packageName;
2300            mWorkSource = copyWorkSource(workSource);
2301            mHistoryTag = historyTag;
2302            mOwnerUid = ownerUid;
2303            mOwnerPid = ownerPid;
2304        }
2305
2306        @Override
2307        public void binderDied() {
2308            PowerManagerService.this.handleWakeLockDeath(this);
2309        }
2310
2311        public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
2312                int ownerUid, int ownerPid) {
2313            return mFlags == flags
2314                    && mTag.equals(tag)
2315                    && hasSameWorkSource(workSource)
2316                    && mOwnerUid == ownerUid
2317                    && mOwnerPid == ownerPid;
2318        }
2319
2320        public void updateProperties(int flags, String tag, String packageName,
2321                WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
2322            if (!mPackageName.equals(packageName)) {
2323                throw new IllegalStateException("Existing wake lock package name changed: "
2324                        + mPackageName + " to " + packageName);
2325            }
2326            if (mOwnerUid != ownerUid) {
2327                throw new IllegalStateException("Existing wake lock uid changed: "
2328                        + mOwnerUid + " to " + ownerUid);
2329            }
2330            if (mOwnerPid != ownerPid) {
2331                throw new IllegalStateException("Existing wake lock pid changed: "
2332                        + mOwnerPid + " to " + ownerPid);
2333            }
2334            mFlags = flags;
2335            mTag = tag;
2336            updateWorkSource(workSource);
2337            mHistoryTag = historyTag;
2338        }
2339
2340        public boolean hasSameWorkSource(WorkSource workSource) {
2341            return Objects.equal(mWorkSource, workSource);
2342        }
2343
2344        public void updateWorkSource(WorkSource workSource) {
2345            mWorkSource = copyWorkSource(workSource);
2346        }
2347
2348        @Override
2349        public String toString() {
2350            return getLockLevelString()
2351                    + " '" + mTag + "'" + getLockFlagsString()
2352                    + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")";
2353        }
2354
2355        @SuppressWarnings("deprecation")
2356        private String getLockLevelString() {
2357            switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
2358                case PowerManager.FULL_WAKE_LOCK:
2359                    return "FULL_WAKE_LOCK                ";
2360                case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
2361                    return "SCREEN_BRIGHT_WAKE_LOCK       ";
2362                case PowerManager.SCREEN_DIM_WAKE_LOCK:
2363                    return "SCREEN_DIM_WAKE_LOCK          ";
2364                case PowerManager.PARTIAL_WAKE_LOCK:
2365                    return "PARTIAL_WAKE_LOCK             ";
2366                case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
2367                    return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
2368                case PowerManager.DOZE_WAKE_LOCK:
2369                    return "DOZE_WAKE_LOCK                ";
2370                default:
2371                    return "???                           ";
2372            }
2373        }
2374
2375        private String getLockFlagsString() {
2376            String result = "";
2377            if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
2378                result += " ACQUIRE_CAUSES_WAKEUP";
2379            }
2380            if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
2381                result += " ON_AFTER_RELEASE";
2382            }
2383            return result;
2384        }
2385    }
2386
2387    private final class SuspendBlockerImpl implements SuspendBlocker {
2388        private final String mName;
2389        private int mReferenceCount;
2390
2391        public SuspendBlockerImpl(String name) {
2392            mName = name;
2393        }
2394
2395        @Override
2396        protected void finalize() throws Throwable {
2397            try {
2398                if (mReferenceCount != 0) {
2399                    Log.wtf(TAG, "Suspend blocker \"" + mName
2400                            + "\" was finalized without being released!");
2401                    mReferenceCount = 0;
2402                    nativeReleaseSuspendBlocker(mName);
2403                }
2404            } finally {
2405                super.finalize();
2406            }
2407        }
2408
2409        @Override
2410        public void acquire() {
2411            synchronized (this) {
2412                mReferenceCount += 1;
2413                if (mReferenceCount == 1) {
2414                    if (DEBUG_SPEW) {
2415                        Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
2416                    }
2417                    nativeAcquireSuspendBlocker(mName);
2418                }
2419            }
2420        }
2421
2422        @Override
2423        public void release() {
2424            synchronized (this) {
2425                mReferenceCount -= 1;
2426                if (mReferenceCount == 0) {
2427                    if (DEBUG_SPEW) {
2428                        Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
2429                    }
2430                    nativeReleaseSuspendBlocker(mName);
2431                } else if (mReferenceCount < 0) {
2432                    Log.wtf(TAG, "Suspend blocker \"" + mName
2433                            + "\" was released without being acquired!", new Throwable());
2434                    mReferenceCount = 0;
2435                }
2436            }
2437        }
2438
2439        @Override
2440        public String toString() {
2441            synchronized (this) {
2442                return mName + ": ref count=" + mReferenceCount;
2443            }
2444        }
2445    }
2446
2447    private final class ScreenOnBlockerImpl implements ScreenOnBlocker {
2448        private int mNestCount;
2449
2450        public boolean isHeld() {
2451            synchronized (this) {
2452                return mNestCount != 0;
2453            }
2454        }
2455
2456        @Override
2457        public void acquire() {
2458            synchronized (this) {
2459                mNestCount += 1;
2460                if (DEBUG) {
2461                    Slog.d(TAG, "Screen on blocked: mNestCount=" + mNestCount);
2462                }
2463            }
2464        }
2465
2466        @Override
2467        public void release() {
2468            synchronized (this) {
2469                mNestCount -= 1;
2470                if (mNestCount < 0) {
2471                    Log.wtf(TAG, "Screen on blocker was released without being acquired!",
2472                            new Throwable());
2473                    mNestCount = 0;
2474                }
2475                if (mNestCount == 0) {
2476                    mHandler.sendEmptyMessage(MSG_SCREEN_ON_BLOCKER_RELEASED);
2477                }
2478                if (DEBUG) {
2479                    Slog.d(TAG, "Screen on unblocked: mNestCount=" + mNestCount);
2480                }
2481            }
2482        }
2483
2484        @Override
2485        public String toString() {
2486            synchronized (this) {
2487                return "held=" + (mNestCount != 0) + ", mNestCount=" + mNestCount;
2488            }
2489        }
2490    }
2491
2492    private final class DisplayBlankerImpl implements DisplayBlanker {
2493        private boolean mBlanked;
2494
2495        @Override
2496        public void blankAllDisplays() {
2497            synchronized (this) {
2498                mBlanked = true;
2499                mDisplayManagerInternal.blankAllDisplaysFromPowerManager();
2500                if (!mDecoupleInteractiveModeFromDisplayConfig) {
2501                    setInteractiveModeLocked(false);
2502                }
2503                if (!mDecoupleAutoSuspendModeFromDisplayConfig) {
2504                    setAutoSuspendModeLocked(true);
2505                }
2506            }
2507        }
2508
2509        @Override
2510        public void unblankAllDisplays() {
2511            synchronized (this) {
2512                if (!mDecoupleAutoSuspendModeFromDisplayConfig) {
2513                    setAutoSuspendModeLocked(false);
2514                }
2515                if (!mDecoupleInteractiveModeFromDisplayConfig) {
2516                    setInteractiveModeLocked(true);
2517                }
2518                mDisplayManagerInternal.unblankAllDisplaysFromPowerManager();
2519                mBlanked = false;
2520            }
2521        }
2522
2523        @Override
2524        public String toString() {
2525            synchronized (this) {
2526                return "blanked=" + mBlanked;
2527            }
2528        }
2529    }
2530
2531    private final class BinderService extends IPowerManager.Stub {
2532        @Override // Binder call
2533        public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
2534                String packageName, int uid) {
2535            acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
2536        }
2537
2538        @Override // Binder call
2539        public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
2540                WorkSource ws, String historyTag) {
2541            if (lock == null) {
2542                throw new IllegalArgumentException("lock must not be null");
2543            }
2544            if (packageName == null) {
2545                throw new IllegalArgumentException("packageName must not be null");
2546            }
2547            PowerManager.validateWakeLockParameters(flags, tag);
2548
2549            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2550            if (ws != null && ws.size() != 0) {
2551                mContext.enforceCallingOrSelfPermission(
2552                        android.Manifest.permission.UPDATE_DEVICE_STATS, null);
2553            } else {
2554                ws = null;
2555            }
2556
2557            final int uid = Binder.getCallingUid();
2558            final int pid = Binder.getCallingPid();
2559            final long ident = Binder.clearCallingIdentity();
2560            try {
2561                acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid);
2562            } finally {
2563                Binder.restoreCallingIdentity(ident);
2564            }
2565        }
2566
2567        @Override // Binder call
2568        public void releaseWakeLock(IBinder lock, int flags) {
2569            if (lock == null) {
2570                throw new IllegalArgumentException("lock must not be null");
2571            }
2572
2573            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2574
2575            final long ident = Binder.clearCallingIdentity();
2576            try {
2577                releaseWakeLockInternal(lock, flags);
2578            } finally {
2579                Binder.restoreCallingIdentity(ident);
2580            }
2581        }
2582
2583        @Override // Binder call
2584        public void updateWakeLockUids(IBinder lock, int[] uids) {
2585            WorkSource ws = null;
2586
2587            if (uids != null) {
2588                ws = new WorkSource();
2589                // XXX should WorkSource have a way to set uids as an int[] instead of adding them
2590                // one at a time?
2591                for (int i = 0; i < uids.length; i++) {
2592                    ws.add(uids[i]);
2593                }
2594            }
2595            updateWakeLockWorkSource(lock, ws);
2596        }
2597
2598        @Override // Binder call
2599        public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
2600            if (lock == null) {
2601                throw new IllegalArgumentException("lock must not be null");
2602            }
2603
2604            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2605            if (ws != null && ws.size() != 0) {
2606                mContext.enforceCallingOrSelfPermission(
2607                        android.Manifest.permission.UPDATE_DEVICE_STATS, null);
2608            } else {
2609                ws = null;
2610            }
2611
2612            final long ident = Binder.clearCallingIdentity();
2613            try {
2614                updateWakeLockWorkSourceInternal(lock, ws);
2615            } finally {
2616                Binder.restoreCallingIdentity(ident);
2617            }
2618        }
2619
2620        @Override // Binder call
2621        public boolean isWakeLockLevelSupported(int level) {
2622            final long ident = Binder.clearCallingIdentity();
2623            try {
2624                return isWakeLockLevelSupportedInternal(level);
2625            } finally {
2626                Binder.restoreCallingIdentity(ident);
2627            }
2628        }
2629
2630        @Override // Binder call
2631        public void userActivity(long eventTime, int event, int flags) {
2632            final long now = SystemClock.uptimeMillis();
2633            if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2634                    != PackageManager.PERMISSION_GRANTED) {
2635                // Once upon a time applications could call userActivity().
2636                // Now we require the DEVICE_POWER permission.  Log a warning and ignore the
2637                // request instead of throwing a SecurityException so we don't break old apps.
2638                synchronized (mLock) {
2639                    if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
2640                        mLastWarningAboutUserActivityPermission = now;
2641                        Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
2642                                + "caller does not have DEVICE_POWER permission.  "
2643                                + "Please fix your app!  "
2644                                + " pid=" + Binder.getCallingPid()
2645                                + " uid=" + Binder.getCallingUid());
2646                    }
2647                }
2648                return;
2649            }
2650
2651            if (eventTime > SystemClock.uptimeMillis()) {
2652                throw new IllegalArgumentException("event time must not be in the future");
2653            }
2654
2655            final int uid = Binder.getCallingUid();
2656            final long ident = Binder.clearCallingIdentity();
2657            try {
2658                userActivityInternal(eventTime, event, flags, uid);
2659            } finally {
2660                Binder.restoreCallingIdentity(ident);
2661            }
2662        }
2663
2664        @Override // Binder call
2665        public void wakeUp(long eventTime) {
2666            if (eventTime > SystemClock.uptimeMillis()) {
2667                throw new IllegalArgumentException("event time must not be in the future");
2668            }
2669
2670            mContext.enforceCallingOrSelfPermission(
2671                    android.Manifest.permission.DEVICE_POWER, null);
2672
2673            final long ident = Binder.clearCallingIdentity();
2674            try {
2675                wakeUpInternal(eventTime);
2676            } finally {
2677                Binder.restoreCallingIdentity(ident);
2678            }
2679        }
2680
2681        @Override // Binder call
2682        public void goToSleep(long eventTime, int reason) {
2683            if (eventTime > SystemClock.uptimeMillis()) {
2684                throw new IllegalArgumentException("event time must not be in the future");
2685            }
2686
2687            mContext.enforceCallingOrSelfPermission(
2688                    android.Manifest.permission.DEVICE_POWER, null);
2689
2690            final long ident = Binder.clearCallingIdentity();
2691            try {
2692                goToSleepInternal(eventTime, reason);
2693            } finally {
2694                Binder.restoreCallingIdentity(ident);
2695            }
2696        }
2697
2698        @Override // Binder call
2699        public void nap(long eventTime) {
2700            if (eventTime > SystemClock.uptimeMillis()) {
2701                throw new IllegalArgumentException("event time must not be in the future");
2702            }
2703
2704            mContext.enforceCallingOrSelfPermission(
2705                    android.Manifest.permission.DEVICE_POWER, null);
2706
2707            final long ident = Binder.clearCallingIdentity();
2708            try {
2709                napInternal(eventTime);
2710            } finally {
2711                Binder.restoreCallingIdentity(ident);
2712            }
2713        }
2714
2715        @Override // Binder call
2716        public boolean isScreenOn() {
2717            final long ident = Binder.clearCallingIdentity();
2718            try {
2719                return isScreenOnInternal();
2720            } finally {
2721                Binder.restoreCallingIdentity(ident);
2722            }
2723        }
2724
2725        /**
2726         * Reboots the device.
2727         *
2728         * @param confirm If true, shows a reboot confirmation dialog.
2729         * @param reason The reason for the reboot, or null if none.
2730         * @param wait If true, this call waits for the reboot to complete and does not return.
2731         */
2732        @Override // Binder call
2733        public void reboot(boolean confirm, String reason, boolean wait) {
2734            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2735            if (PowerManager.REBOOT_RECOVERY.equals(reason)) {
2736                mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
2737            }
2738
2739            final long ident = Binder.clearCallingIdentity();
2740            try {
2741                shutdownOrRebootInternal(false, confirm, reason, wait);
2742            } finally {
2743                Binder.restoreCallingIdentity(ident);
2744            }
2745        }
2746
2747        /**
2748         * Shuts down the device.
2749         *
2750         * @param confirm If true, shows a shutdown confirmation dialog.
2751         * @param wait If true, this call waits for the shutdown to complete and does not return.
2752         */
2753        @Override // Binder call
2754        public void shutdown(boolean confirm, boolean wait) {
2755            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2756
2757            final long ident = Binder.clearCallingIdentity();
2758            try {
2759                shutdownOrRebootInternal(true, confirm, null, wait);
2760            } finally {
2761                Binder.restoreCallingIdentity(ident);
2762            }
2763        }
2764
2765        /**
2766         * Crash the runtime (causing a complete restart of the Android framework).
2767         * Requires REBOOT permission.  Mostly for testing.  Should not return.
2768         */
2769        @Override // Binder call
2770        public void crash(String message) {
2771            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2772
2773            final long ident = Binder.clearCallingIdentity();
2774            try {
2775                crashInternal(message);
2776            } finally {
2777                Binder.restoreCallingIdentity(ident);
2778            }
2779        }
2780
2781        /**
2782         * Set the setting that determines whether the device stays on when plugged in.
2783         * The argument is a bit string, with each bit specifying a power source that,
2784         * when the device is connected to that source, causes the device to stay on.
2785         * See {@link android.os.BatteryManager} for the list of power sources that
2786         * can be specified. Current values include
2787         * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
2788         * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
2789         *
2790         * Used by "adb shell svc power stayon ..."
2791         *
2792         * @param val an {@code int} containing the bits that specify which power sources
2793         * should cause the device to stay on.
2794         */
2795        @Override // Binder call
2796        public void setStayOnSetting(int val) {
2797            mContext.enforceCallingOrSelfPermission(
2798                    android.Manifest.permission.WRITE_SETTINGS, null);
2799
2800            final long ident = Binder.clearCallingIdentity();
2801            try {
2802                setStayOnSettingInternal(val);
2803            } finally {
2804                Binder.restoreCallingIdentity(ident);
2805            }
2806        }
2807
2808        /**
2809         * Used by device administration to set the maximum screen off timeout.
2810         *
2811         * This method must only be called by the device administration policy manager.
2812         */
2813        @Override // Binder call
2814        public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) {
2815            final long ident = Binder.clearCallingIdentity();
2816            try {
2817                setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs);
2818            } finally {
2819                Binder.restoreCallingIdentity(ident);
2820            }
2821        }
2822
2823        /**
2824         * Used by the settings application and brightness control widgets to
2825         * temporarily override the current screen brightness setting so that the
2826         * user can observe the effect of an intended settings change without applying
2827         * it immediately.
2828         *
2829         * The override will be canceled when the setting value is next updated.
2830         *
2831         * @param brightness The overridden brightness.
2832         *
2833         * @see android.provider.Settings.System#SCREEN_BRIGHTNESS
2834         */
2835        @Override // Binder call
2836        public void setTemporaryScreenBrightnessSettingOverride(int brightness) {
2837            mContext.enforceCallingOrSelfPermission(
2838                    android.Manifest.permission.DEVICE_POWER, null);
2839
2840            final long ident = Binder.clearCallingIdentity();
2841            try {
2842                setTemporaryScreenBrightnessSettingOverrideInternal(brightness);
2843            } finally {
2844                Binder.restoreCallingIdentity(ident);
2845            }
2846        }
2847
2848        /**
2849         * Used by the settings application and brightness control widgets to
2850         * temporarily override the current screen auto-brightness adjustment setting so that the
2851         * user can observe the effect of an intended settings change without applying
2852         * it immediately.
2853         *
2854         * The override will be canceled when the setting value is next updated.
2855         *
2856         * @param adj The overridden brightness, or Float.NaN to disable the override.
2857         *
2858         * @see Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ
2859         */
2860        @Override // Binder call
2861        public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) {
2862            mContext.enforceCallingOrSelfPermission(
2863                    android.Manifest.permission.DEVICE_POWER, null);
2864
2865            final long ident = Binder.clearCallingIdentity();
2866            try {
2867                setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj);
2868            } finally {
2869                Binder.restoreCallingIdentity(ident);
2870            }
2871        }
2872
2873        /**
2874         * Used by the phone application to make the attention LED flash when ringing.
2875         */
2876        @Override // Binder call
2877        public void setAttentionLight(boolean on, int color) {
2878            mContext.enforceCallingOrSelfPermission(
2879                    android.Manifest.permission.DEVICE_POWER, null);
2880
2881            final long ident = Binder.clearCallingIdentity();
2882            try {
2883                setAttentionLightInternal(on, color);
2884            } finally {
2885                Binder.restoreCallingIdentity(ident);
2886            }
2887        }
2888
2889        @Override // Binder call
2890        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2891            if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
2892                    != PackageManager.PERMISSION_GRANTED) {
2893                pw.println("Permission Denial: can't dump PowerManager from from pid="
2894                        + Binder.getCallingPid()
2895                        + ", uid=" + Binder.getCallingUid());
2896                return;
2897            }
2898
2899            final long ident = Binder.clearCallingIdentity();
2900            try {
2901                dumpInternal(pw);
2902            } finally {
2903                Binder.restoreCallingIdentity(ident);
2904            }
2905        }
2906    }
2907
2908    private final class LocalService extends PowerManagerInternal {
2909        /**
2910         * Used by the window manager to override the screen brightness based on the
2911         * current foreground activity.
2912         *
2913         * This method must only be called by the window manager.
2914         *
2915         * @param brightness The overridden brightness, or -1 to disable the override.
2916         */
2917        @Override
2918        public void setScreenBrightnessOverrideFromWindowManager(int brightness) {
2919            mContext.enforceCallingOrSelfPermission(
2920                    android.Manifest.permission.DEVICE_POWER, null);
2921
2922            final long ident = Binder.clearCallingIdentity();
2923            try {
2924                setScreenBrightnessOverrideFromWindowManagerInternal(brightness);
2925            } finally {
2926                Binder.restoreCallingIdentity(ident);
2927            }
2928        }
2929
2930        /**
2931         * Used by the window manager to override the button brightness based on the
2932         * current foreground activity.
2933         *
2934         * This method must only be called by the window manager.
2935         *
2936         * @param brightness The overridden brightness, or -1 to disable the override.
2937         */
2938        @Override
2939        public void setButtonBrightnessOverrideFromWindowManager(int brightness) {
2940            // Do nothing.
2941            // Button lights are not currently supported in the new implementation.
2942            mContext.enforceCallingOrSelfPermission(
2943                    android.Manifest.permission.DEVICE_POWER, null);
2944        }
2945
2946        /**
2947         * Used by the window manager to override the user activity timeout based on the
2948         * current foreground activity.  It can only be used to make the timeout shorter
2949         * than usual, not longer.
2950         *
2951         * This method must only be called by the window manager.
2952         *
2953         * @param timeoutMillis The overridden timeout, or -1 to disable the override.
2954         */
2955        @Override
2956        public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
2957            mContext.enforceCallingOrSelfPermission(
2958                    android.Manifest.permission.DEVICE_POWER, null);
2959
2960            final long ident = Binder.clearCallingIdentity();
2961            try {
2962                setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
2963            } finally {
2964                Binder.restoreCallingIdentity(ident);
2965            }
2966        }
2967
2968        @Override
2969        public void setPolicy(WindowManagerPolicy policy) {
2970            PowerManagerService.this.setPolicy(policy);
2971        }
2972    }
2973}
2974