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