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