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