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 
   1139         // Phase 0: Basic state updates.
   1140         updateIsPoweredLocked(mDirty);
   1141         updateStayOnLocked(mDirty);
   1142 
   1143         // Phase 1: Update wakefulness.
   1144         // Loop because the wake lock and user activity computations are influenced
   1145         // by changes in wakefulness.
   1146         final long now = SystemClock.uptimeMillis();
   1147         int dirtyPhase2 = 0;
   1148         for (;;) {
   1149             int dirtyPhase1 = mDirty;
   1150             dirtyPhase2 |= dirtyPhase1;
   1151             mDirty = 0;
   1152 
   1153             updateWakeLockSummaryLocked(dirtyPhase1);
   1154             updateUserActivitySummaryLocked(now, dirtyPhase1);
   1155             if (!updateWakefulnessLocked(dirtyPhase1)) {
   1156                 break;
   1157             }
   1158         }
   1159 
   1160         // Phase 2: Update dreams and display power state.
   1161         updateDreamLocked(dirtyPhase2);
   1162         updateDisplayPowerStateLocked(dirtyPhase2);
   1163 
   1164         // Phase 3: Send notifications, if needed.
   1165         if (mDisplayReady) {
   1166             sendPendingNotificationsLocked();
   1167         }
   1168 
   1169         // Phase 4: Update suspend blocker.
   1170         // Because we might release the last suspend blocker here, we need to make sure
   1171         // we finished everything else first!
   1172         updateSuspendBlockerLocked();
   1173     }
   1174 
   1175     private void sendPendingNotificationsLocked() {
   1176         if (mSendWakeUpFinishedNotificationWhenReady) {
   1177             mSendWakeUpFinishedNotificationWhenReady = false;
   1178             mNotifier.onWakeUpFinished();
   1179         }
   1180         if (mSendGoToSleepFinishedNotificationWhenReady) {
   1181             mSendGoToSleepFinishedNotificationWhenReady = false;
   1182             mNotifier.onGoToSleepFinished();
   1183         }
   1184     }
   1185 
   1186     /**
   1187      * Updates the value of mIsPowered.
   1188      * Sets DIRTY_IS_POWERED if a change occurred.
   1189      */
   1190     private void updateIsPoweredLocked(int dirty) {
   1191         if ((dirty & DIRTY_BATTERY_STATE) != 0) {
   1192             final boolean wasPowered = mIsPowered;
   1193             final int oldPlugType = mPlugType;
   1194             mIsPowered = mBatteryService.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
   1195             mPlugType = mBatteryService.getPlugType();
   1196             mBatteryLevel = mBatteryService.getBatteryLevel();
   1197 
   1198             if (DEBUG) {
   1199                 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
   1200                         + ", mIsPowered=" + mIsPowered
   1201                         + ", oldPlugType=" + oldPlugType
   1202                         + ", mPlugType=" + mPlugType
   1203                         + ", mBatteryLevel=" + mBatteryLevel);
   1204             }
   1205 
   1206             if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
   1207                 mDirty |= DIRTY_IS_POWERED;
   1208 
   1209                 // Update wireless dock detection state.
   1210                 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
   1211                         mIsPowered, mPlugType, mBatteryLevel);
   1212 
   1213                 // Treat plugging and unplugging the devices as a user activity.
   1214                 // Users find it disconcerting when they plug or unplug the device
   1215                 // and it shuts off right away.
   1216                 // Some devices also wake the device when plugged or unplugged because
   1217                 // they don't have a charging LED.
   1218                 final long now = SystemClock.uptimeMillis();
   1219                 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
   1220                         dockedOnWirelessCharger)) {
   1221                     wakeUpNoUpdateLocked(now);
   1222                 }
   1223                 userActivityNoUpdateLocked(
   1224                         now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
   1225 
   1226                 // Tell the notifier whether wireless charging has started so that
   1227                 // it can provide feedback to the user.
   1228                 if (dockedOnWirelessCharger) {
   1229                     mNotifier.onWirelessChargingStarted();
   1230                 }
   1231             }
   1232         }
   1233     }
   1234 
   1235     private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
   1236             boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
   1237         // Don't wake when powered unless configured to do so.
   1238         if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
   1239             return false;
   1240         }
   1241 
   1242         // Don't wake when undocked from wireless charger.
   1243         // See WirelessChargerDetector for justification.
   1244         if (wasPowered && !mIsPowered
   1245                 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
   1246             return false;
   1247         }
   1248 
   1249         // Don't wake when docked on wireless charger unless we are certain of it.
   1250         // See WirelessChargerDetector for justification.
   1251         if (!wasPowered && mIsPowered
   1252                 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
   1253                 && !dockedOnWirelessCharger) {
   1254             return false;
   1255         }
   1256 
   1257         // If already dreaming and becoming powered, then don't wake.
   1258         if (mIsPowered && (mWakefulness == WAKEFULNESS_NAPPING
   1259                 || mWakefulness == WAKEFULNESS_DREAMING)) {
   1260             return false;
   1261         }
   1262 
   1263         // Otherwise wake up!
   1264         return true;
   1265     }
   1266 
   1267     /**
   1268      * Updates the value of mStayOn.
   1269      * Sets DIRTY_STAY_ON if a change occurred.
   1270      */
   1271     private void updateStayOnLocked(int dirty) {
   1272         if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
   1273             final boolean wasStayOn = mStayOn;
   1274             if (mStayOnWhilePluggedInSetting != 0
   1275                     && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
   1276                 mStayOn = mBatteryService.isPowered(mStayOnWhilePluggedInSetting);
   1277             } else {
   1278                 mStayOn = false;
   1279             }
   1280 
   1281             if (mStayOn != wasStayOn) {
   1282                 mDirty |= DIRTY_STAY_ON;
   1283             }
   1284         }
   1285     }
   1286 
   1287     /**
   1288      * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
   1289      * Note that most wake-locks are ignored when the system is asleep.
   1290      *
   1291      * This function must have no other side-effects.
   1292      */
   1293     @SuppressWarnings("deprecation")
   1294     private void updateWakeLockSummaryLocked(int dirty) {
   1295         if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
   1296             mWakeLockSummary = 0;
   1297 
   1298             final int numWakeLocks = mWakeLocks.size();
   1299             for (int i = 0; i < numWakeLocks; i++) {
   1300                 final WakeLock wakeLock = mWakeLocks.get(i);
   1301                 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
   1302                     case PowerManager.PARTIAL_WAKE_LOCK:
   1303                         mWakeLockSummary |= WAKE_LOCK_CPU;
   1304                         break;
   1305                     case PowerManager.FULL_WAKE_LOCK:
   1306                         if (mWakefulness != WAKEFULNESS_ASLEEP) {
   1307                             mWakeLockSummary |= WAKE_LOCK_CPU
   1308                                     | WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
   1309                             if (mWakefulness == WAKEFULNESS_AWAKE) {
   1310                                 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
   1311                             }
   1312                         }
   1313                         break;
   1314                     case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
   1315                         if (mWakefulness != WAKEFULNESS_ASLEEP) {
   1316                             mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_BRIGHT;
   1317                             if (mWakefulness == WAKEFULNESS_AWAKE) {
   1318                                 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
   1319                             }
   1320                         }
   1321                         break;
   1322                     case PowerManager.SCREEN_DIM_WAKE_LOCK:
   1323                         if (mWakefulness != WAKEFULNESS_ASLEEP) {
   1324                             mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_DIM;
   1325                             if (mWakefulness == WAKEFULNESS_AWAKE) {
   1326                                 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
   1327                             }
   1328                         }
   1329                         break;
   1330                     case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
   1331                         if (mWakefulness != WAKEFULNESS_ASLEEP) {
   1332                             mWakeLockSummary |= WAKE_LOCK_PROXIMITY_SCREEN_OFF;
   1333                         }
   1334                         break;
   1335                 }
   1336             }
   1337 
   1338             if (DEBUG_SPEW) {
   1339                 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
   1340                         + wakefulnessToString(mWakefulness)
   1341                         + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
   1342             }
   1343         }
   1344     }
   1345 
   1346     /**
   1347      * Updates the value of mUserActivitySummary to summarize the user requested
   1348      * state of the system such as whether the screen should be bright or dim.
   1349      * Note that user activity is ignored when the system is asleep.
   1350      *
   1351      * This function must have no other side-effects.
   1352      */
   1353     private void updateUserActivitySummaryLocked(long now, int dirty) {
   1354         // Update the status of the user activity timeout timer.
   1355         if ((dirty & (DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
   1356             mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
   1357 
   1358             long nextTimeout = 0;
   1359             if (mWakefulness != WAKEFULNESS_ASLEEP) {
   1360                 final int screenOffTimeout = getScreenOffTimeoutLocked();
   1361                 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
   1362 
   1363                 mUserActivitySummary = 0;
   1364                 if (mLastUserActivityTime >= mLastWakeTime) {
   1365                     nextTimeout = mLastUserActivityTime
   1366                             + screenOffTimeout - screenDimDuration;
   1367                     if (now < nextTimeout) {
   1368                         mUserActivitySummary |= USER_ACTIVITY_SCREEN_BRIGHT;
   1369                     } else {
   1370                         nextTimeout = mLastUserActivityTime + screenOffTimeout;
   1371                         if (now < nextTimeout) {
   1372                             mUserActivitySummary |= USER_ACTIVITY_SCREEN_DIM;
   1373                         }
   1374                     }
   1375                 }
   1376                 if (mUserActivitySummary == 0
   1377                         && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
   1378                     nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
   1379                     if (now < nextTimeout
   1380                             && mDisplayPowerRequest.screenState
   1381                                     != DisplayPowerRequest.SCREEN_STATE_OFF) {
   1382                         mUserActivitySummary = mDisplayPowerRequest.screenState
   1383                                 == DisplayPowerRequest.SCREEN_STATE_BRIGHT ?
   1384                                 USER_ACTIVITY_SCREEN_BRIGHT : USER_ACTIVITY_SCREEN_DIM;
   1385                     }
   1386                 }
   1387                 if (mUserActivitySummary != 0) {
   1388                     Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
   1389                     msg.setAsynchronous(true);
   1390                     mHandler.sendMessageAtTime(msg, nextTimeout);
   1391                 }
   1392             } else {
   1393                 mUserActivitySummary = 0;
   1394             }
   1395 
   1396             if (DEBUG_SPEW) {
   1397                 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
   1398                         + wakefulnessToString(mWakefulness)
   1399                         + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
   1400                         + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
   1401             }
   1402         }
   1403     }
   1404 
   1405     /**
   1406      * Called when a user activity timeout has occurred.
   1407      * Simply indicates that something about user activity has changed so that the new
   1408      * state can be recomputed when the power state is updated.
   1409      *
   1410      * This function must have no other side-effects besides setting the dirty
   1411      * bit and calling update power state.  Wakefulness transitions are handled elsewhere.
   1412      */
   1413     private void handleUserActivityTimeout() { // runs on handler thread
   1414         synchronized (mLock) {
   1415             if (DEBUG_SPEW) {
   1416                 Slog.d(TAG, "handleUserActivityTimeout");
   1417             }
   1418 
   1419             mDirty |= DIRTY_USER_ACTIVITY;
   1420             updatePowerStateLocked();
   1421         }
   1422     }
   1423 
   1424     private int getScreenOffTimeoutLocked() {
   1425         int timeout = mScreenOffTimeoutSetting;
   1426         if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
   1427             timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
   1428         }
   1429         if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
   1430             timeout = (int)Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
   1431         }
   1432         return Math.max(timeout, MINIMUM_SCREEN_OFF_TIMEOUT);
   1433     }
   1434 
   1435     private int getScreenDimDurationLocked(int screenOffTimeout) {
   1436         return Math.min(SCREEN_DIM_DURATION,
   1437                 (int)(screenOffTimeout * MAXIMUM_SCREEN_DIM_RATIO));
   1438     }
   1439 
   1440     /**
   1441      * Updates the wakefulness of the device.
   1442      *
   1443      * This is the function that decides whether the device should start napping
   1444      * based on the current wake locks and user activity state.  It may modify mDirty
   1445      * if the wakefulness changes.
   1446      *
   1447      * Returns true if the wakefulness changed and we need to restart power state calculation.
   1448      */
   1449     private boolean updateWakefulnessLocked(int dirty) {
   1450         boolean changed = false;
   1451         if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
   1452                 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
   1453                 | DIRTY_DOCK_STATE)) != 0) {
   1454             if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
   1455                 if (DEBUG_SPEW) {
   1456                     Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
   1457                 }
   1458                 final long time = SystemClock.uptimeMillis();
   1459                 if (shouldNapAtBedTimeLocked()) {
   1460                     changed = napNoUpdateLocked(time);
   1461                 } else {
   1462                     changed = goToSleepNoUpdateLocked(time,
   1463                             PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
   1464                 }
   1465             }
   1466         }
   1467         return changed;
   1468     }
   1469 
   1470     /**
   1471      * Returns true if the device should automatically nap and start dreaming when the user
   1472      * activity timeout has expired and it's bedtime.
   1473      */
   1474     private boolean shouldNapAtBedTimeLocked() {
   1475         return mDreamsActivateOnSleepSetting
   1476                 || (mDreamsActivateOnDockSetting
   1477                         && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
   1478     }
   1479 
   1480     /**
   1481      * Returns true if the device should go to sleep now.
   1482      * Also used when exiting a dream to determine whether we should go back
   1483      * to being fully awake or else go to sleep for good.
   1484      */
   1485     private boolean isItBedTimeYetLocked() {
   1486         return mBootCompleted && !isBeingKeptAwakeLocked();
   1487     }
   1488 
   1489     /**
   1490      * Returns true if the device is being kept awake by a wake lock, user activity
   1491      * or the stay on while powered setting.  We also keep the phone awake when
   1492      * the proximity sensor returns a positive result so that the device does not
   1493      * lock while in a phone call.  This function only controls whether the device
   1494      * will go to sleep or dream which is independent of whether it will be allowed
   1495      * to suspend.
   1496      */
   1497     private boolean isBeingKeptAwakeLocked() {
   1498         return mStayOn
   1499                 || mProximityPositive
   1500                 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
   1501                 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
   1502                         | USER_ACTIVITY_SCREEN_DIM)) != 0;
   1503     }
   1504 
   1505     /**
   1506      * Determines whether to post a message to the sandman to update the dream state.
   1507      */
   1508     private void updateDreamLocked(int dirty) {
   1509         if ((dirty & (DIRTY_WAKEFULNESS
   1510                 | DIRTY_USER_ACTIVITY
   1511                 | DIRTY_WAKE_LOCKS
   1512                 | DIRTY_BOOT_COMPLETED
   1513                 | DIRTY_SETTINGS
   1514                 | DIRTY_IS_POWERED
   1515                 | DIRTY_STAY_ON
   1516                 | DIRTY_PROXIMITY_POSITIVE
   1517                 | DIRTY_BATTERY_STATE)) != 0) {
   1518             scheduleSandmanLocked();
   1519         }
   1520     }
   1521 
   1522     private void scheduleSandmanLocked() {
   1523         if (!mSandmanScheduled) {
   1524             mSandmanScheduled = true;
   1525             Message msg = mHandler.obtainMessage(MSG_SANDMAN);
   1526             msg.setAsynchronous(true);
   1527             mHandler.sendMessage(msg);
   1528         }
   1529     }
   1530 
   1531     /**
   1532      * Called when the device enters or exits a napping or dreaming state.
   1533      *
   1534      * We do this asynchronously because we must call out of the power manager to start
   1535      * the dream and we don't want to hold our lock while doing so.  There is a risk that
   1536      * the device will wake or go to sleep in the meantime so we have to handle that case.
   1537      */
   1538     private void handleSandman() { // runs on handler thread
   1539         // Handle preconditions.
   1540         boolean startDreaming = false;
   1541         synchronized (mLock) {
   1542             mSandmanScheduled = false;
   1543             boolean canDream = canDreamLocked();
   1544             if (DEBUG_SPEW) {
   1545                 Slog.d(TAG, "handleSandman: canDream=" + canDream
   1546                         + ", mWakefulness=" + wakefulnessToString(mWakefulness));
   1547             }
   1548 
   1549             if (canDream && mWakefulness == WAKEFULNESS_NAPPING) {
   1550                 startDreaming = true;
   1551             }
   1552         }
   1553 
   1554         // Start dreaming if needed.
   1555         // We only control the dream on the handler thread, so we don't need to worry about
   1556         // concurrent attempts to start or stop the dream.
   1557         boolean isDreaming = false;
   1558         if (mDreamManager != null) {
   1559             if (startDreaming) {
   1560                 mDreamManager.startDream();
   1561             }
   1562             isDreaming = mDreamManager.isDreaming();
   1563         }
   1564 
   1565         // Update dream state.
   1566         // We might need to stop the dream again if the preconditions changed.
   1567         boolean continueDreaming = false;
   1568         synchronized (mLock) {
   1569             if (isDreaming && canDreamLocked()) {
   1570                 if (mWakefulness == WAKEFULNESS_NAPPING) {
   1571                     mWakefulness = WAKEFULNESS_DREAMING;
   1572                     mDirty |= DIRTY_WAKEFULNESS;
   1573                     mBatteryLevelWhenDreamStarted = mBatteryLevel;
   1574                     updatePowerStateLocked();
   1575                     continueDreaming = true;
   1576                 } else if (mWakefulness == WAKEFULNESS_DREAMING) {
   1577                     if (!isBeingKeptAwakeLocked()
   1578                             && mBatteryLevel < mBatteryLevelWhenDreamStarted
   1579                                     - DREAM_BATTERY_LEVEL_DRAIN_CUTOFF) {
   1580                         // If the user activity timeout expired and the battery appears
   1581                         // to be draining faster than it is charging then stop dreaming
   1582                         // and go to sleep.
   1583                         Slog.i(TAG, "Stopping dream because the battery appears to "
   1584                                 + "be draining faster than it is charging.  "
   1585                                 + "Battery level when dream started: "
   1586                                 + mBatteryLevelWhenDreamStarted + "%.  "
   1587                                 + "Battery level now: " + mBatteryLevel + "%.");
   1588                     } else {
   1589                         continueDreaming = true;
   1590                     }
   1591                 }
   1592             }
   1593             if (!continueDreaming) {
   1594                 handleDreamFinishedLocked();
   1595             }
   1596         }
   1597 
   1598         // Stop dreaming if needed.
   1599         // It's possible that something else changed to make us need to start the dream again.
   1600         // If so, then the power manager will have posted another message to the handler
   1601         // to take care of it later.
   1602         if (mDreamManager != null) {
   1603             if (!continueDreaming) {
   1604                 mDreamManager.stopDream();
   1605             }
   1606         }
   1607     }
   1608 
   1609     /**
   1610      * Returns true if the device is allowed to dream in its current state
   1611      * assuming that it is currently napping or dreaming.
   1612      */
   1613     private boolean canDreamLocked() {
   1614         return mDreamsSupportedConfig
   1615                 && mDreamsEnabledSetting
   1616                 && mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF
   1617                 && mBootCompleted
   1618                 && (mIsPowered || isBeingKeptAwakeLocked());
   1619     }
   1620 
   1621     /**
   1622      * Called when a dream is ending to figure out what to do next.
   1623      */
   1624     private void handleDreamFinishedLocked() {
   1625         if (mWakefulness == WAKEFULNESS_NAPPING
   1626                 || mWakefulness == WAKEFULNESS_DREAMING) {
   1627             if (isItBedTimeYetLocked()) {
   1628                 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
   1629                         PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
   1630                 updatePowerStateLocked();
   1631             } else {
   1632                 wakeUpNoUpdateLocked(SystemClock.uptimeMillis());
   1633                 updatePowerStateLocked();
   1634             }
   1635         }
   1636     }
   1637 
   1638     private void handleScreenOnBlockerReleased() {
   1639         synchronized (mLock) {
   1640             mDirty |= DIRTY_SCREEN_ON_BLOCKER_RELEASED;
   1641             updatePowerStateLocked();
   1642         }
   1643     }
   1644 
   1645     /**
   1646      * Updates the display power state asynchronously.
   1647      * When the update is finished, mDisplayReady will be set to true.  The display
   1648      * controller posts a message to tell us when the actual display power state
   1649      * has been updated so we come back here to double-check and finish up.
   1650      *
   1651      * This function recalculates the display power state each time.
   1652      */
   1653     private void updateDisplayPowerStateLocked(int dirty) {
   1654         if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
   1655                 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
   1656                 | DIRTY_SETTINGS | DIRTY_SCREEN_ON_BLOCKER_RELEASED)) != 0) {
   1657             int newScreenState = getDesiredScreenPowerStateLocked();
   1658             if (newScreenState != mDisplayPowerRequest.screenState) {
   1659                 if (newScreenState == DisplayPowerRequest.SCREEN_STATE_OFF
   1660                         && mDisplayPowerRequest.screenState
   1661                                 != DisplayPowerRequest.SCREEN_STATE_OFF) {
   1662                     mLastScreenOffEventElapsedRealTime = SystemClock.elapsedRealtime();
   1663                 }
   1664 
   1665                 mDisplayPowerRequest.screenState = newScreenState;
   1666                 nativeSetPowerState(
   1667                         newScreenState != DisplayPowerRequest.SCREEN_STATE_OFF,
   1668                         newScreenState == DisplayPowerRequest.SCREEN_STATE_BRIGHT);
   1669             }
   1670 
   1671             int screenBrightness = mScreenBrightnessSettingDefault;
   1672             float screenAutoBrightnessAdjustment = 0.0f;
   1673             boolean autoBrightness = (mScreenBrightnessModeSetting ==
   1674                     Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
   1675             if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
   1676                 screenBrightness = mScreenBrightnessOverrideFromWindowManager;
   1677                 autoBrightness = false;
   1678             } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) {
   1679                 screenBrightness = mTemporaryScreenBrightnessSettingOverride;
   1680             } else if (isValidBrightness(mScreenBrightnessSetting)) {
   1681                 screenBrightness = mScreenBrightnessSetting;
   1682             }
   1683             if (autoBrightness) {
   1684                 screenBrightness = mScreenBrightnessSettingDefault;
   1685                 if (isValidAutoBrightnessAdjustment(
   1686                         mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) {
   1687                     screenAutoBrightnessAdjustment =
   1688                             mTemporaryScreenAutoBrightnessAdjustmentSettingOverride;
   1689                 } else if (isValidAutoBrightnessAdjustment(
   1690                         mScreenAutoBrightnessAdjustmentSetting)) {
   1691                     screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting;
   1692                 }
   1693             }
   1694             screenBrightness = Math.max(Math.min(screenBrightness,
   1695                     mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum);
   1696             screenAutoBrightnessAdjustment = Math.max(Math.min(
   1697                     screenAutoBrightnessAdjustment, 1.0f), -1.0f);
   1698             mDisplayPowerRequest.screenBrightness = screenBrightness;
   1699             mDisplayPowerRequest.screenAutoBrightnessAdjustment =
   1700                     screenAutoBrightnessAdjustment;
   1701             mDisplayPowerRequest.useAutoBrightness = autoBrightness;
   1702 
   1703             mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
   1704 
   1705             mDisplayPowerRequest.blockScreenOn = mScreenOnBlocker.isHeld();
   1706 
   1707             mDisplayReady = mDisplayPowerController.requestPowerState(mDisplayPowerRequest,
   1708                     mRequestWaitForNegativeProximity);
   1709             mRequestWaitForNegativeProximity = false;
   1710 
   1711             if (DEBUG_SPEW) {
   1712                 Slog.d(TAG, "updateScreenStateLocked: mDisplayReady=" + mDisplayReady
   1713                         + ", newScreenState=" + newScreenState
   1714                         + ", mWakefulness=" + mWakefulness
   1715                         + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
   1716                         + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
   1717                         + ", mBootCompleted=" + mBootCompleted);
   1718             }
   1719         }
   1720     }
   1721 
   1722     private static boolean isValidBrightness(int value) {
   1723         return value >= 0 && value <= 255;
   1724     }
   1725 
   1726     private static boolean isValidAutoBrightnessAdjustment(float value) {
   1727         // Handles NaN by always returning false.
   1728         return value >= -1.0f && value <= 1.0f;
   1729     }
   1730 
   1731     private int getDesiredScreenPowerStateLocked() {
   1732         if (mWakefulness == WAKEFULNESS_ASLEEP) {
   1733             return DisplayPowerRequest.SCREEN_STATE_OFF;
   1734         }
   1735 
   1736         if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
   1737                 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
   1738                 || !mBootCompleted) {
   1739             return DisplayPowerRequest.SCREEN_STATE_BRIGHT;
   1740         }
   1741 
   1742         return DisplayPowerRequest.SCREEN_STATE_DIM;
   1743     }
   1744 
   1745     private final DisplayPowerController.Callbacks mDisplayPowerControllerCallbacks =
   1746             new DisplayPowerController.Callbacks() {
   1747         @Override
   1748         public void onStateChanged() {
   1749             synchronized (mLock) {
   1750                 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
   1751                 updatePowerStateLocked();
   1752             }
   1753         }
   1754 
   1755         @Override
   1756         public void onProximityPositive() {
   1757             synchronized (mLock) {
   1758                 mProximityPositive = true;
   1759                 mDirty |= DIRTY_PROXIMITY_POSITIVE;
   1760                 updatePowerStateLocked();
   1761             }
   1762         }
   1763 
   1764         @Override
   1765         public void onProximityNegative() {
   1766             synchronized (mLock) {
   1767                 mProximityPositive = false;
   1768                 mDirty |= DIRTY_PROXIMITY_POSITIVE;
   1769                 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
   1770                         PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
   1771                 updatePowerStateLocked();
   1772             }
   1773         }
   1774     };
   1775 
   1776     private boolean shouldUseProximitySensorLocked() {
   1777         return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
   1778     }
   1779 
   1780     /**
   1781      * Updates the suspend blocker that keeps the CPU alive.
   1782      *
   1783      * This function must have no other side-effects.
   1784      */
   1785     private void updateSuspendBlockerLocked() {
   1786         final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
   1787         final boolean needDisplaySuspendBlocker = needDisplaySuspendBlocker();
   1788 
   1789         // First acquire suspend blockers if needed.
   1790         if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
   1791             mWakeLockSuspendBlocker.acquire();
   1792             mHoldingWakeLockSuspendBlocker = true;
   1793         }
   1794         if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
   1795             mDisplaySuspendBlocker.acquire();
   1796             mHoldingDisplaySuspendBlocker = true;
   1797         }
   1798 
   1799         // Then release suspend blockers if needed.
   1800         if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
   1801             mWakeLockSuspendBlocker.release();
   1802             mHoldingWakeLockSuspendBlocker = false;
   1803         }
   1804         if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
   1805             mDisplaySuspendBlocker.release();
   1806             mHoldingDisplaySuspendBlocker = false;
   1807         }
   1808     }
   1809 
   1810     /**
   1811      * Return true if we must keep a suspend blocker active on behalf of the display.
   1812      * We do so if the screen is on or is in transition between states.
   1813      */
   1814     private boolean needDisplaySuspendBlocker() {
   1815         if (!mDisplayReady) {
   1816             return true;
   1817         }
   1818         if (mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF) {
   1819             // If we asked for the screen to be on but it is off due to the proximity
   1820             // sensor then we may suspend but only if the configuration allows it.
   1821             // On some hardware it may not be safe to suspend because the proximity
   1822             // sensor may not be correctly configured as a wake-up source.
   1823             if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
   1824                     || !mSuspendWhenScreenOffDueToProximityConfig) {
   1825                 return true;
   1826             }
   1827         }
   1828         return false;
   1829     }
   1830 
   1831     @Override // Binder call
   1832     public boolean isScreenOn() {
   1833         final long ident = Binder.clearCallingIdentity();
   1834         try {
   1835             return isScreenOnInternal();
   1836         } finally {
   1837             Binder.restoreCallingIdentity(ident);
   1838         }
   1839     }
   1840 
   1841     private boolean isScreenOnInternal() {
   1842         synchronized (mLock) {
   1843             return !mSystemReady
   1844                     || mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF;
   1845         }
   1846     }
   1847 
   1848     private void handleBatteryStateChangedLocked() {
   1849         mDirty |= DIRTY_BATTERY_STATE;
   1850         updatePowerStateLocked();
   1851     }
   1852 
   1853     private void startWatchingForBootAnimationFinished() {
   1854         mHandler.sendEmptyMessage(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED);
   1855     }
   1856 
   1857     private void checkIfBootAnimationFinished() {
   1858         if (DEBUG) {
   1859             Slog.d(TAG, "Check if boot animation finished...");
   1860         }
   1861 
   1862         if (SystemService.isRunning(BOOT_ANIMATION_SERVICE)) {
   1863             mHandler.sendEmptyMessageDelayed(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED,
   1864                     BOOT_ANIMATION_POLL_INTERVAL);
   1865             return;
   1866         }
   1867 
   1868         synchronized (mLock) {
   1869             if (!mBootCompleted) {
   1870                 Slog.i(TAG, "Boot animation finished.");
   1871                 handleBootCompletedLocked();
   1872             }
   1873         }
   1874     }
   1875 
   1876     private void handleBootCompletedLocked() {
   1877         final long now = SystemClock.uptimeMillis();
   1878         mBootCompleted = true;
   1879         mDirty |= DIRTY_BOOT_COMPLETED;
   1880         userActivityNoUpdateLocked(
   1881                 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
   1882         updatePowerStateLocked();
   1883     }
   1884 
   1885     /**
   1886      * Reboots the device.
   1887      *
   1888      * @param confirm If true, shows a reboot confirmation dialog.
   1889      * @param reason The reason for the reboot, or null if none.
   1890      * @param wait If true, this call waits for the reboot to complete and does not return.
   1891      */
   1892     @Override // Binder call
   1893     public void reboot(boolean confirm, String reason, boolean wait) {
   1894         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
   1895 
   1896         final long ident = Binder.clearCallingIdentity();
   1897         try {
   1898             shutdownOrRebootInternal(false, confirm, reason, wait);
   1899         } finally {
   1900             Binder.restoreCallingIdentity(ident);
   1901         }
   1902     }
   1903 
   1904     /**
   1905      * Shuts down the device.
   1906      *
   1907      * @param confirm If true, shows a shutdown confirmation dialog.
   1908      * @param wait If true, this call waits for the shutdown to complete and does not return.
   1909      */
   1910     @Override // Binder call
   1911     public void shutdown(boolean confirm, boolean wait) {
   1912         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
   1913 
   1914         final long ident = Binder.clearCallingIdentity();
   1915         try {
   1916             shutdownOrRebootInternal(true, confirm, null, wait);
   1917         } finally {
   1918             Binder.restoreCallingIdentity(ident);
   1919         }
   1920     }
   1921 
   1922     private void shutdownOrRebootInternal(final boolean shutdown, final boolean confirm,
   1923             final String reason, boolean wait) {
   1924         if (mHandler == null || !mSystemReady) {
   1925             throw new IllegalStateException("Too early to call shutdown() or reboot()");
   1926         }
   1927 
   1928         Runnable runnable = new Runnable() {
   1929             @Override
   1930             public void run() {
   1931                 synchronized (this) {
   1932                     if (shutdown) {
   1933                         ShutdownThread.shutdown(mContext, confirm);
   1934                     } else {
   1935                         ShutdownThread.reboot(mContext, reason, confirm);
   1936                     }
   1937                 }
   1938             }
   1939         };
   1940 
   1941         // ShutdownThread must run on a looper capable of displaying the UI.
   1942         Message msg = Message.obtain(mHandler, runnable);
   1943         msg.setAsynchronous(true);
   1944         mHandler.sendMessage(msg);
   1945 
   1946         // PowerManager.reboot() is documented not to return so just wait for the inevitable.
   1947         if (wait) {
   1948             synchronized (runnable) {
   1949                 while (true) {
   1950                     try {
   1951                         runnable.wait();
   1952                     } catch (InterruptedException e) {
   1953                     }
   1954                 }
   1955             }
   1956         }
   1957     }
   1958 
   1959     /**
   1960      * Crash the runtime (causing a complete restart of the Android framework).
   1961      * Requires REBOOT permission.  Mostly for testing.  Should not return.
   1962      */
   1963     @Override // Binder call
   1964     public void crash(String message) {
   1965         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
   1966 
   1967         final long ident = Binder.clearCallingIdentity();
   1968         try {
   1969             crashInternal(message);
   1970         } finally {
   1971             Binder.restoreCallingIdentity(ident);
   1972         }
   1973     }
   1974 
   1975     private void crashInternal(final String message) {
   1976         Thread t = new Thread("PowerManagerService.crash()") {
   1977             @Override
   1978             public void run() {
   1979                 throw new RuntimeException(message);
   1980             }
   1981         };
   1982         try {
   1983             t.start();
   1984             t.join();
   1985         } catch (InterruptedException e) {
   1986             Log.wtf(TAG, e);
   1987         }
   1988     }
   1989 
   1990     /**
   1991      * Set the setting that determines whether the device stays on when plugged in.
   1992      * The argument is a bit string, with each bit specifying a power source that,
   1993      * when the device is connected to that source, causes the device to stay on.
   1994      * See {@link android.os.BatteryManager} for the list of power sources that
   1995      * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
   1996      * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
   1997      *
   1998      * Used by "adb shell svc power stayon ..."
   1999      *
   2000      * @param val an {@code int} containing the bits that specify which power sources
   2001      * should cause the device to stay on.
   2002      */
   2003     @Override // Binder call
   2004     public void setStayOnSetting(int val) {
   2005         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
   2006 
   2007         final long ident = Binder.clearCallingIdentity();
   2008         try {
   2009             setStayOnSettingInternal(val);
   2010         } finally {
   2011             Binder.restoreCallingIdentity(ident);
   2012         }
   2013     }
   2014 
   2015     private void setStayOnSettingInternal(int val) {
   2016         Settings.Global.putInt(mContext.getContentResolver(),
   2017                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
   2018     }
   2019 
   2020     /**
   2021      * Used by device administration to set the maximum screen off timeout.
   2022      *
   2023      * This method must only be called by the device administration policy manager.
   2024      */
   2025     @Override // Binder call
   2026     public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) {
   2027         final long ident = Binder.clearCallingIdentity();
   2028         try {
   2029             setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs);
   2030         } finally {
   2031             Binder.restoreCallingIdentity(ident);
   2032         }
   2033     }
   2034 
   2035     private void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) {
   2036         synchronized (mLock) {
   2037             mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
   2038             mDirty |= DIRTY_SETTINGS;
   2039             updatePowerStateLocked();
   2040         }
   2041     }
   2042 
   2043     private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
   2044         return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
   2045                 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE;
   2046     }
   2047 
   2048     /**
   2049      * Used by the phone application to make the attention LED flash when ringing.
   2050      */
   2051     @Override // Binder call
   2052     public void setAttentionLight(boolean on, int color) {
   2053         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
   2054 
   2055         final long ident = Binder.clearCallingIdentity();
   2056         try {
   2057             setAttentionLightInternal(on, color);
   2058         } finally {
   2059             Binder.restoreCallingIdentity(ident);
   2060         }
   2061     }
   2062 
   2063     private void setAttentionLightInternal(boolean on, int color) {
   2064         LightsService.Light light;
   2065         synchronized (mLock) {
   2066             if (!mSystemReady) {
   2067                 return;
   2068             }
   2069             light = mAttentionLight;
   2070         }
   2071 
   2072         // Control light outside of lock.
   2073         light.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
   2074     }
   2075 
   2076     /**
   2077      * Used by the Watchdog.
   2078      */
   2079     public long timeSinceScreenWasLastOn() {
   2080         synchronized (mLock) {
   2081             if (mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF) {
   2082                 return 0;
   2083             }
   2084             return SystemClock.elapsedRealtime() - mLastScreenOffEventElapsedRealTime;
   2085         }
   2086     }
   2087 
   2088     /**
   2089      * Used by the window manager to override the screen brightness based on the
   2090      * current foreground activity.
   2091      *
   2092      * This method must only be called by the window manager.
   2093      *
   2094      * @param brightness The overridden brightness, or -1 to disable the override.
   2095      */
   2096     public void setScreenBrightnessOverrideFromWindowManager(int brightness) {
   2097         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
   2098 
   2099         final long ident = Binder.clearCallingIdentity();
   2100         try {
   2101             setScreenBrightnessOverrideFromWindowManagerInternal(brightness);
   2102         } finally {
   2103             Binder.restoreCallingIdentity(ident);
   2104         }
   2105     }
   2106 
   2107     private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
   2108         synchronized (mLock) {
   2109             if (mScreenBrightnessOverrideFromWindowManager != brightness) {
   2110                 mScreenBrightnessOverrideFromWindowManager = brightness;
   2111                 mDirty |= DIRTY_SETTINGS;
   2112                 updatePowerStateLocked();
   2113             }
   2114         }
   2115     }
   2116 
   2117     /**
   2118      * Used by the window manager to override the button brightness based on the
   2119      * current foreground activity.
   2120      *
   2121      * This method must only be called by the window manager.
   2122      *
   2123      * @param brightness The overridden brightness, or -1 to disable the override.
   2124      */
   2125     public void setButtonBrightnessOverrideFromWindowManager(int brightness) {
   2126         // Do nothing.
   2127         // Button lights are not currently supported in the new implementation.
   2128         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
   2129     }
   2130 
   2131     /**
   2132      * Used by the window manager to override the user activity timeout based on the
   2133      * current foreground activity.  It can only be used to make the timeout shorter
   2134      * than usual, not longer.
   2135      *
   2136      * This method must only be called by the window manager.
   2137      *
   2138      * @param timeoutMillis The overridden timeout, or -1 to disable the override.
   2139      */
   2140     public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
   2141         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
   2142 
   2143         final long ident = Binder.clearCallingIdentity();
   2144         try {
   2145             setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
   2146         } finally {
   2147             Binder.restoreCallingIdentity(ident);
   2148         }
   2149     }
   2150 
   2151     private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
   2152         synchronized (mLock) {
   2153             if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
   2154                 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
   2155                 mDirty |= DIRTY_SETTINGS;
   2156                 updatePowerStateLocked();
   2157             }
   2158         }
   2159     }
   2160 
   2161     /**
   2162      * Used by the settings application and brightness control widgets to
   2163      * temporarily override the current screen brightness setting so that the
   2164      * user can observe the effect of an intended settings change without applying
   2165      * it immediately.
   2166      *
   2167      * The override will be canceled when the setting value is next updated.
   2168      *
   2169      * @param brightness The overridden brightness.
   2170      *
   2171      * @see android.provider.Settings.System#SCREEN_BRIGHTNESS
   2172      */
   2173     @Override // Binder call
   2174     public void setTemporaryScreenBrightnessSettingOverride(int brightness) {
   2175         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
   2176 
   2177         final long ident = Binder.clearCallingIdentity();
   2178         try {
   2179             setTemporaryScreenBrightnessSettingOverrideInternal(brightness);
   2180         } finally {
   2181             Binder.restoreCallingIdentity(ident);
   2182         }
   2183     }
   2184 
   2185     private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) {
   2186         synchronized (mLock) {
   2187             if (mTemporaryScreenBrightnessSettingOverride != brightness) {
   2188                 mTemporaryScreenBrightnessSettingOverride = brightness;
   2189                 mDirty |= DIRTY_SETTINGS;
   2190                 updatePowerStateLocked();
   2191             }
   2192         }
   2193     }
   2194 
   2195     /**
   2196      * Used by the settings application and brightness control widgets to
   2197      * temporarily override the current screen auto-brightness adjustment setting so that the
   2198      * user can observe the effect of an intended settings change without applying
   2199      * it immediately.
   2200      *
   2201      * The override will be canceled when the setting value is next updated.
   2202      *
   2203      * @param adj The overridden brightness, or Float.NaN to disable the override.
   2204      *
   2205      * @see Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ
   2206      */
   2207     @Override // Binder call
   2208     public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) {
   2209         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
   2210 
   2211         final long ident = Binder.clearCallingIdentity();
   2212         try {
   2213             setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj);
   2214         } finally {
   2215             Binder.restoreCallingIdentity(ident);
   2216         }
   2217     }
   2218 
   2219     private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) {
   2220         synchronized (mLock) {
   2221             // Note: This condition handles NaN because NaN is not equal to any other
   2222             // value, including itself.
   2223             if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) {
   2224                 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj;
   2225                 mDirty |= DIRTY_SETTINGS;
   2226                 updatePowerStateLocked();
   2227             }
   2228         }
   2229     }
   2230 
   2231     /**
   2232      * Low-level function turn the device off immediately, without trying
   2233      * to be clean.  Most people should use {@link ShutdownThread} for a clean shutdown.
   2234      */
   2235     public static void lowLevelShutdown() {
   2236         SystemProperties.set("sys.powerctl", "shutdown");
   2237     }
   2238 
   2239     /**
   2240      * Low-level function to reboot the device. On success, this function
   2241      * doesn't return. If more than 5 seconds passes from the time,
   2242      * a reboot is requested, this method returns.
   2243      *
   2244      * @param reason code to pass to the kernel (e.g. "recovery"), or null.
   2245      */
   2246     public static void lowLevelReboot(String reason) {
   2247         if (reason == null) {
   2248             reason = "";
   2249         }
   2250         SystemProperties.set("sys.powerctl", "reboot," + reason);
   2251         try {
   2252             Thread.sleep(20000);
   2253         } catch (InterruptedException e) {
   2254             Thread.currentThread().interrupt();
   2255         }
   2256     }
   2257 
   2258     @Override // Watchdog.Monitor implementation
   2259     public void monitor() {
   2260         // Grab and release lock for watchdog monitor to detect deadlocks.
   2261         synchronized (mLock) {
   2262         }
   2263     }
   2264 
   2265     @Override // Binder call
   2266     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
   2267         if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
   2268                 != PackageManager.PERMISSION_GRANTED) {
   2269             pw.println("Permission Denial: can't dump PowerManager from from pid="
   2270                     + Binder.getCallingPid()
   2271                     + ", uid=" + Binder.getCallingUid());
   2272             return;
   2273         }
   2274 
   2275         pw.println("POWER MANAGER (dumpsys power)\n");
   2276 
   2277         final DisplayPowerController dpc;
   2278         final WirelessChargerDetector wcd;
   2279         synchronized (mLock) {
   2280             pw.println("Power Manager State:");
   2281             pw.println("  mDirty=0x" + Integer.toHexString(mDirty));
   2282             pw.println("  mWakefulness=" + wakefulnessToString(mWakefulness));
   2283             pw.println("  mIsPowered=" + mIsPowered);
   2284             pw.println("  mPlugType=" + mPlugType);
   2285             pw.println("  mBatteryLevel=" + mBatteryLevel);
   2286             pw.println("  mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
   2287             pw.println("  mDockState=" + mDockState);
   2288             pw.println("  mStayOn=" + mStayOn);
   2289             pw.println("  mProximityPositive=" + mProximityPositive);
   2290             pw.println("  mBootCompleted=" + mBootCompleted);
   2291             pw.println("  mSystemReady=" + mSystemReady);
   2292             pw.println("  mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
   2293             pw.println("  mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
   2294             pw.println("  mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
   2295             pw.println("  mSandmanScheduled=" + mSandmanScheduled);
   2296             pw.println("  mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
   2297             pw.println("  mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
   2298             pw.println("  mSendWakeUpFinishedNotificationWhenReady="
   2299                     + mSendWakeUpFinishedNotificationWhenReady);
   2300             pw.println("  mSendGoToSleepFinishedNotificationWhenReady="
   2301                     + mSendGoToSleepFinishedNotificationWhenReady);
   2302             pw.println("  mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
   2303             pw.println("  mLastUserActivityTimeNoChangeLights="
   2304                     + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
   2305             pw.println("  mDisplayReady=" + mDisplayReady);
   2306             pw.println("  mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
   2307             pw.println("  mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
   2308 
   2309             pw.println();
   2310             pw.println("Settings and Configuration:");
   2311             pw.println("  mWakeUpWhenPluggedOrUnpluggedConfig="
   2312                     + mWakeUpWhenPluggedOrUnpluggedConfig);
   2313             pw.println("  mSuspendWhenScreenOffDueToProximityConfig="
   2314                     + mSuspendWhenScreenOffDueToProximityConfig);
   2315             pw.println("  mDreamsSupportedConfig=" + mDreamsSupportedConfig);
   2316             pw.println("  mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
   2317             pw.println("  mDreamsActivatedOnSleepByDefaultConfig="
   2318                     + mDreamsActivatedOnSleepByDefaultConfig);
   2319             pw.println("  mDreamsActivatedOnDockByDefaultConfig="
   2320                     + mDreamsActivatedOnDockByDefaultConfig);
   2321             pw.println("  mDreamsEnabledSetting=" + mDreamsEnabledSetting);
   2322             pw.println("  mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
   2323             pw.println("  mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
   2324             pw.println("  mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
   2325             pw.println("  mMaximumScreenOffTimeoutFromDeviceAdmin="
   2326                     + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
   2327                     + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
   2328             pw.println("  mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
   2329             pw.println("  mScreenBrightnessSetting=" + mScreenBrightnessSetting);
   2330             pw.println("  mScreenAutoBrightnessAdjustmentSetting="
   2331                     + mScreenAutoBrightnessAdjustmentSetting);
   2332             pw.println("  mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
   2333             pw.println("  mScreenBrightnessOverrideFromWindowManager="
   2334                     + mScreenBrightnessOverrideFromWindowManager);
   2335             pw.println("  mUserActivityTimeoutOverrideFromWindowManager="
   2336                     + mUserActivityTimeoutOverrideFromWindowManager);
   2337             pw.println("  mTemporaryScreenBrightnessSettingOverride="
   2338                     + mTemporaryScreenBrightnessSettingOverride);
   2339             pw.println("  mTemporaryScreenAutoBrightnessAdjustmentSettingOverride="
   2340                     + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride);
   2341             pw.println("  mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
   2342             pw.println("  mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
   2343             pw.println("  mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
   2344 
   2345             final int screenOffTimeout = getScreenOffTimeoutLocked();
   2346             final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
   2347             pw.println();
   2348             pw.println("Screen off timeout: " + screenOffTimeout + " ms");
   2349             pw.println("Screen dim duration: " + screenDimDuration + " ms");
   2350 
   2351             pw.println();
   2352             pw.println("Wake Locks: size=" + mWakeLocks.size());
   2353             for (WakeLock wl : mWakeLocks) {
   2354                 pw.println("  " + wl);
   2355             }
   2356 
   2357             pw.println();
   2358             pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
   2359             for (SuspendBlocker sb : mSuspendBlockers) {
   2360                 pw.println("  " + sb);
   2361             }
   2362 
   2363             pw.println();
   2364             pw.println("Screen On Blocker: " + mScreenOnBlocker);
   2365 
   2366             pw.println();
   2367             pw.println("Display Blanker: " + mDisplayBlanker);
   2368 
   2369             dpc = mDisplayPowerController;
   2370             wcd = mWirelessChargerDetector;
   2371         }
   2372 
   2373         if (dpc != null) {
   2374             dpc.dump(pw);
   2375         }
   2376 
   2377         if (wcd != null) {
   2378             wcd.dump(pw);
   2379         }
   2380     }
   2381 
   2382     private SuspendBlocker createSuspendBlockerLocked(String name) {
   2383         SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name);
   2384         mSuspendBlockers.add(suspendBlocker);
   2385         return suspendBlocker;
   2386     }
   2387 
   2388     private static String wakefulnessToString(int wakefulness) {
   2389         switch (wakefulness) {
   2390             case WAKEFULNESS_ASLEEP:
   2391                 return "Asleep";
   2392             case WAKEFULNESS_AWAKE:
   2393                 return "Awake";
   2394             case WAKEFULNESS_DREAMING:
   2395                 return "Dreaming";
   2396             case WAKEFULNESS_NAPPING:
   2397                 return "Napping";
   2398             default:
   2399                 return Integer.toString(wakefulness);
   2400         }
   2401     }
   2402 
   2403     private static WorkSource copyWorkSource(WorkSource workSource) {
   2404         return workSource != null ? new WorkSource(workSource) : null;
   2405     }
   2406 
   2407     private final class BatteryReceiver extends BroadcastReceiver {
   2408         @Override
   2409         public void onReceive(Context context, Intent intent) {
   2410             synchronized (mLock) {
   2411                 handleBatteryStateChangedLocked();
   2412             }
   2413         }
   2414     }
   2415 
   2416     private final class BootCompletedReceiver extends BroadcastReceiver {
   2417         @Override
   2418         public void onReceive(Context context, Intent intent) {
   2419             // This is our early signal that the system thinks it has finished booting.
   2420             // However, the boot animation may still be running for a few more seconds
   2421             // since it is ultimately in charge of when it terminates.
   2422             // Defer transitioning into the boot completed state until the animation exits.
   2423             // We do this so that the screen does not start to dim prematurely before
   2424             // the user has actually had a chance to interact with the device.
   2425             startWatchingForBootAnimationFinished();
   2426         }
   2427     }
   2428 
   2429     private final class DreamReceiver extends BroadcastReceiver {
   2430         @Override
   2431         public void onReceive(Context context, Intent intent) {
   2432             synchronized (mLock) {
   2433                 scheduleSandmanLocked();
   2434             }
   2435         }
   2436     }
   2437 
   2438     private final class UserSwitchedReceiver extends BroadcastReceiver {
   2439         @Override
   2440         public void onReceive(Context context, Intent intent) {
   2441             synchronized (mLock) {
   2442                 handleSettingsChangedLocked();
   2443             }
   2444         }
   2445     }
   2446 
   2447     private final class DockReceiver extends BroadcastReceiver {
   2448         @Override
   2449         public void onReceive(Context context, Intent intent) {
   2450             synchronized (mLock) {
   2451                 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
   2452                         Intent.EXTRA_DOCK_STATE_UNDOCKED);
   2453                 if (mDockState != dockState) {
   2454                     mDockState = dockState;
   2455                     mDirty |= DIRTY_DOCK_STATE;
   2456                     updatePowerStateLocked();
   2457                 }
   2458             }
   2459         }
   2460     }
   2461 
   2462     private final class SettingsObserver extends ContentObserver {
   2463         public SettingsObserver(Handler handler) {
   2464             super(handler);
   2465         }
   2466 
   2467         @Override
   2468         public void onChange(boolean selfChange, Uri uri) {
   2469             synchronized (mLock) {
   2470                 handleSettingsChangedLocked();
   2471             }
   2472         }
   2473     }
   2474 
   2475     /**
   2476      * Handler for asynchronous operations performed by the power manager.
   2477      */
   2478     private final class PowerManagerHandler extends Handler {
   2479         public PowerManagerHandler(Looper looper) {
   2480             super(looper, null, true /*async*/);
   2481         }
   2482 
   2483         @Override
   2484         public void handleMessage(Message msg) {
   2485             switch (msg.what) {
   2486                 case MSG_USER_ACTIVITY_TIMEOUT:
   2487                     handleUserActivityTimeout();
   2488                     break;
   2489                 case MSG_SANDMAN:
   2490                     handleSandman();
   2491                     break;
   2492                 case MSG_SCREEN_ON_BLOCKER_RELEASED:
   2493                     handleScreenOnBlockerReleased();
   2494                     break;
   2495                 case MSG_CHECK_IF_BOOT_ANIMATION_FINISHED:
   2496                     checkIfBootAnimationFinished();
   2497                     break;
   2498             }
   2499         }
   2500     }
   2501 
   2502     /**
   2503      * Represents a wake lock that has been acquired by an application.
   2504      */
   2505     private final class WakeLock implements IBinder.DeathRecipient {
   2506         public final IBinder mLock;
   2507         public int mFlags;
   2508         public String mTag;
   2509         public final String mPackageName;
   2510         public WorkSource mWorkSource;
   2511         public final int mOwnerUid;
   2512         public final int mOwnerPid;
   2513         public boolean mNotifiedAcquired;
   2514 
   2515         public WakeLock(IBinder lock, int flags, String tag, String packageName,
   2516                 WorkSource workSource, int ownerUid, int ownerPid) {
   2517             mLock = lock;
   2518             mFlags = flags;
   2519             mTag = tag;
   2520             mPackageName = packageName;
   2521             mWorkSource = copyWorkSource(workSource);
   2522             mOwnerUid = ownerUid;
   2523             mOwnerPid = ownerPid;
   2524         }
   2525 
   2526         @Override
   2527         public void binderDied() {
   2528             PowerManagerService.this.handleWakeLockDeath(this);
   2529         }
   2530 
   2531         public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
   2532                 int ownerUid, int ownerPid) {
   2533             return mFlags == flags
   2534                     && mTag.equals(tag)
   2535                     && hasSameWorkSource(workSource)
   2536                     && mOwnerUid == ownerUid
   2537                     && mOwnerPid == ownerPid;
   2538         }
   2539 
   2540         public void updateProperties(int flags, String tag, String packageName,
   2541                 WorkSource workSource, int ownerUid, int ownerPid) {
   2542             if (!mPackageName.equals(packageName)) {
   2543                 throw new IllegalStateException("Existing wake lock package name changed: "
   2544                         + mPackageName + " to " + packageName);
   2545             }
   2546             if (mOwnerUid != ownerUid) {
   2547                 throw new IllegalStateException("Existing wake lock uid changed: "
   2548                         + mOwnerUid + " to " + ownerUid);
   2549             }
   2550             if (mOwnerPid != ownerPid) {
   2551                 throw new IllegalStateException("Existing wake lock pid changed: "
   2552                         + mOwnerPid + " to " + ownerPid);
   2553             }
   2554             mFlags = flags;
   2555             mTag = tag;
   2556             updateWorkSource(workSource);
   2557         }
   2558 
   2559         public boolean hasSameWorkSource(WorkSource workSource) {
   2560             return Objects.equal(mWorkSource, workSource);
   2561         }
   2562 
   2563         public void updateWorkSource(WorkSource workSource) {
   2564             mWorkSource = copyWorkSource(workSource);
   2565         }
   2566 
   2567         @Override
   2568         public String toString() {
   2569             return getLockLevelString()
   2570                     + " '" + mTag + "'" + getLockFlagsString()
   2571                     + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")";
   2572         }
   2573 
   2574         private String getLockLevelString() {
   2575             switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
   2576                 case PowerManager.FULL_WAKE_LOCK:
   2577                     return "FULL_WAKE_LOCK                ";
   2578                 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
   2579                     return "SCREEN_BRIGHT_WAKE_LOCK       ";
   2580                 case PowerManager.SCREEN_DIM_WAKE_LOCK:
   2581                     return "SCREEN_DIM_WAKE_LOCK          ";
   2582                 case PowerManager.PARTIAL_WAKE_LOCK:
   2583                     return "PARTIAL_WAKE_LOCK             ";
   2584                 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
   2585                     return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
   2586                 default:
   2587                     return "???                           ";
   2588             }
   2589         }
   2590 
   2591         private String getLockFlagsString() {
   2592             String result = "";
   2593             if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
   2594                 result += " ACQUIRE_CAUSES_WAKEUP";
   2595             }
   2596             if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
   2597                 result += " ON_AFTER_RELEASE";
   2598             }
   2599             return result;
   2600         }
   2601     }
   2602 
   2603     private final class SuspendBlockerImpl implements SuspendBlocker {
   2604         private final String mName;
   2605         private int mReferenceCount;
   2606 
   2607         public SuspendBlockerImpl(String name) {
   2608             mName = name;
   2609         }
   2610 
   2611         @Override
   2612         protected void finalize() throws Throwable {
   2613             try {
   2614                 if (mReferenceCount != 0) {
   2615                     Log.wtf(TAG, "Suspend blocker \"" + mName
   2616                             + "\" was finalized without being released!");
   2617                     mReferenceCount = 0;
   2618                     nativeReleaseSuspendBlocker(mName);
   2619                 }
   2620             } finally {
   2621                 super.finalize();
   2622             }
   2623         }
   2624 
   2625         @Override
   2626         public void acquire() {
   2627             synchronized (this) {
   2628                 mReferenceCount += 1;
   2629                 if (mReferenceCount == 1) {
   2630                     if (DEBUG_SPEW) {
   2631                         Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
   2632                     }
   2633                     nativeAcquireSuspendBlocker(mName);
   2634                 }
   2635             }
   2636         }
   2637 
   2638         @Override
   2639         public void release() {
   2640             synchronized (this) {
   2641                 mReferenceCount -= 1;
   2642                 if (mReferenceCount == 0) {
   2643                     if (DEBUG_SPEW) {
   2644                         Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
   2645                     }
   2646                     nativeReleaseSuspendBlocker(mName);
   2647                 } else if (mReferenceCount < 0) {
   2648                     Log.wtf(TAG, "Suspend blocker \"" + mName
   2649                             + "\" was released without being acquired!", new Throwable());
   2650                     mReferenceCount = 0;
   2651                 }
   2652             }
   2653         }
   2654 
   2655         @Override
   2656         public String toString() {
   2657             synchronized (this) {
   2658                 return mName + ": ref count=" + mReferenceCount;
   2659             }
   2660         }
   2661     }
   2662 
   2663     private final class ScreenOnBlockerImpl implements ScreenOnBlocker {
   2664         private int mNestCount;
   2665 
   2666         public boolean isHeld() {
   2667             synchronized (this) {
   2668                 return mNestCount != 0;
   2669             }
   2670         }
   2671 
   2672         @Override
   2673         public void acquire() {
   2674             synchronized (this) {
   2675                 mNestCount += 1;
   2676                 if (DEBUG) {
   2677                     Slog.d(TAG, "Screen on blocked: mNestCount=" + mNestCount);
   2678                 }
   2679             }
   2680         }
   2681 
   2682         @Override
   2683         public void release() {
   2684             synchronized (this) {
   2685                 mNestCount -= 1;
   2686                 if (mNestCount < 0) {
   2687                     Log.wtf(TAG, "Screen on blocker was released without being acquired!",
   2688                             new Throwable());
   2689                     mNestCount = 0;
   2690                 }
   2691                 if (mNestCount == 0) {
   2692                     mHandler.sendEmptyMessage(MSG_SCREEN_ON_BLOCKER_RELEASED);
   2693                 }
   2694                 if (DEBUG) {
   2695                     Slog.d(TAG, "Screen on unblocked: mNestCount=" + mNestCount);
   2696                 }
   2697             }
   2698         }
   2699 
   2700         @Override
   2701         public String toString() {
   2702             synchronized (this) {
   2703                 return "held=" + (mNestCount != 0) + ", mNestCount=" + mNestCount;
   2704             }
   2705         }
   2706     }
   2707 
   2708     private final class DisplayBlankerImpl implements DisplayBlanker {
   2709         private boolean mBlanked;
   2710 
   2711         @Override
   2712         public void blankAllDisplays() {
   2713             synchronized (this) {
   2714                 mBlanked = true;
   2715                 mDisplayManagerService.blankAllDisplaysFromPowerManager();
   2716                 nativeSetInteractive(false);
   2717                 nativeSetAutoSuspend(true);
   2718             }
   2719         }
   2720 
   2721         @Override
   2722         public void unblankAllDisplays() {
   2723             synchronized (this) {
   2724                 nativeSetAutoSuspend(false);
   2725                 nativeSetInteractive(true);
   2726                 mDisplayManagerService.unblankAllDisplaysFromPowerManager();
   2727                 mBlanked = false;
   2728             }
   2729         }
   2730 
   2731         @Override
   2732         public String toString() {
   2733             synchronized (this) {
   2734                 return "blanked=" + mBlanked;
   2735             }
   2736         }
   2737     }
   2738 }
   2739