Home | History | Annotate | Download | only in keyguard
      1 /*
      2  * Copyright (C) 2014 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.systemui.keyguard;
     18 
     19 import android.app.Activity;
     20 import android.app.ActivityManager;
     21 import android.app.ActivityManagerNative;
     22 import android.app.AlarmManager;
     23 import android.app.PendingIntent;
     24 import android.app.SearchManager;
     25 import android.app.StatusBarManager;
     26 import android.app.trust.TrustManager;
     27 import android.content.BroadcastReceiver;
     28 import android.content.ContentResolver;
     29 import android.content.Context;
     30 import android.content.Intent;
     31 import android.content.IntentFilter;
     32 import android.content.pm.UserInfo;
     33 import android.media.AudioManager;
     34 import android.media.SoundPool;
     35 import android.os.Bundle;
     36 import android.os.Handler;
     37 import android.os.Looper;
     38 import android.os.Message;
     39 import android.os.PowerManager;
     40 import android.os.RemoteException;
     41 import android.os.SystemClock;
     42 import android.os.SystemProperties;
     43 import android.os.UserHandle;
     44 import android.os.UserManager;
     45 import android.provider.Settings;
     46 import android.telephony.SubscriptionManager;
     47 import android.telephony.TelephonyManager;
     48 import android.util.EventLog;
     49 import android.util.Log;
     50 import android.util.Slog;
     51 import android.view.IWindowManager;
     52 import android.view.ViewGroup;
     53 import android.view.WindowManagerGlobal;
     54 import android.view.WindowManagerPolicy;
     55 import android.view.animation.Animation;
     56 import android.view.animation.AnimationUtils;
     57 import com.android.internal.policy.IKeyguardExitCallback;
     58 import com.android.internal.policy.IKeyguardShowCallback;
     59 import com.android.internal.policy.IKeyguardStateCallback;
     60 import com.android.internal.telephony.IccCardConstants;
     61 import com.android.internal.widget.LockPatternUtils;
     62 import com.android.keyguard.KeyguardConstants;
     63 import com.android.keyguard.KeyguardDisplayManager;
     64 import com.android.keyguard.KeyguardUpdateMonitor;
     65 import com.android.keyguard.KeyguardUpdateMonitorCallback;
     66 import com.android.keyguard.MultiUserAvatarCache;
     67 import com.android.keyguard.ViewMediatorCallback;
     68 import com.android.systemui.SystemUI;
     69 import com.android.systemui.statusbar.phone.PhoneStatusBar;
     70 import com.android.systemui.statusbar.phone.ScrimController;
     71 import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
     72 import com.android.systemui.statusbar.phone.StatusBarWindowManager;
     73 
     74 import java.util.ArrayList;
     75 import java.util.List;
     76 
     77 import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
     78 
     79 
     80 /**
     81  * Mediates requests related to the keyguard.  This includes queries about the
     82  * state of the keyguard, power management events that effect whether the keyguard
     83  * should be shown or reset, callbacks to the phone window manager to notify
     84  * it of when the keyguard is showing, and events from the keyguard view itself
     85  * stating that the keyguard was succesfully unlocked.
     86  *
     87  * Note that the keyguard view is shown when the screen is off (as appropriate)
     88  * so that once the screen comes on, it will be ready immediately.
     89  *
     90  * Example queries about the keyguard:
     91  * - is {movement, key} one that should wake the keygaurd?
     92  * - is the keyguard showing?
     93  * - are input events restricted due to the state of the keyguard?
     94  *
     95  * Callbacks to the phone window manager:
     96  * - the keyguard is showing
     97  *
     98  * Example external events that translate to keyguard view changes:
     99  * - screen turned off -> reset the keyguard, and show it so it will be ready
    100  *   next time the screen turns on
    101  * - keyboard is slid open -> if the keyguard is not secure, hide it
    102  *
    103  * Events from the keyguard view:
    104  * - user succesfully unlocked keyguard -> hide keyguard view, and no longer
    105  *   restrict input events.
    106  *
    107  * Note: in addition to normal power managment events that effect the state of
    108  * whether the keyguard should be showing, external apps and services may request
    109  * that the keyguard be disabled via {@link #setKeyguardEnabled(boolean)}.  When
    110  * false, this will override all other conditions for turning on the keyguard.
    111  *
    112  * Threading and synchronization:
    113  * This class is created by the initialization routine of the {@link android.view.WindowManagerPolicy},
    114  * and runs on its thread.  The keyguard UI is created from that thread in the
    115  * constructor of this class.  The apis may be called from other threads, including the
    116  * {@link com.android.server.input.InputManagerService}'s and {@link android.view.WindowManager}'s.
    117  * Therefore, methods on this class are synchronized, and any action that is pointed
    118  * directly to the keyguard UI is posted to a {@link android.os.Handler} to ensure it is taken on the UI
    119  * thread of the keyguard.
    120  */
    121 public class KeyguardViewMediator extends SystemUI {
    122     private static final int KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000;
    123     private static final long KEYGUARD_DONE_PENDING_TIMEOUT_MS = 3000;
    124 
    125     private static final boolean DEBUG = KeyguardConstants.DEBUG;
    126     private static final boolean DEBUG_SIM_STATES = KeyguardConstants.DEBUG_SIM_STATES;
    127     private final static boolean DBG_WAKE = false;
    128 
    129     private final static String TAG = "KeyguardViewMediator";
    130 
    131     private static final String DELAYED_KEYGUARD_ACTION =
    132         "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_KEYGUARD";
    133 
    134     // used for handler messages
    135     private static final int SHOW = 2;
    136     private static final int HIDE = 3;
    137     private static final int RESET = 4;
    138     private static final int VERIFY_UNLOCK = 5;
    139     private static final int NOTIFY_SCREEN_OFF = 6;
    140     private static final int NOTIFY_SCREEN_ON = 7;
    141     private static final int KEYGUARD_DONE = 9;
    142     private static final int KEYGUARD_DONE_DRAWING = 10;
    143     private static final int KEYGUARD_DONE_AUTHENTICATING = 11;
    144     private static final int SET_OCCLUDED = 12;
    145     private static final int KEYGUARD_TIMEOUT = 13;
    146     private static final int DISMISS = 17;
    147     private static final int START_KEYGUARD_EXIT_ANIM = 18;
    148     private static final int ON_ACTIVITY_DRAWN = 19;
    149     private static final int KEYGUARD_DONE_PENDING_TIMEOUT = 20;
    150 
    151     /**
    152      * The default amount of time we stay awake (used for all key input)
    153      */
    154     public static final int AWAKE_INTERVAL_DEFAULT_MS = 10000;
    155 
    156     /**
    157      * How long to wait after the screen turns off due to timeout before
    158      * turning on the keyguard (i.e, the user has this much time to turn
    159      * the screen back on without having to face the keyguard).
    160      */
    161     private static final int KEYGUARD_LOCK_AFTER_DELAY_DEFAULT = 5000;
    162 
    163     /**
    164      * How long we'll wait for the {@link ViewMediatorCallback#keyguardDoneDrawing()}
    165      * callback before unblocking a call to {@link #setKeyguardEnabled(boolean)}
    166      * that is reenabling the keyguard.
    167      */
    168     private static final int KEYGUARD_DONE_DRAWING_TIMEOUT_MS = 2000;
    169 
    170     /**
    171      * Secure setting whether analytics are collected on the keyguard.
    172      */
    173     private static final String KEYGUARD_ANALYTICS_SETTING = "keyguard_analytics";
    174 
    175     /** The stream type that the lock sounds are tied to. */
    176     private int mMasterStreamType;
    177 
    178     private AlarmManager mAlarmManager;
    179     private AudioManager mAudioManager;
    180     private StatusBarManager mStatusBarManager;
    181     private boolean mSwitchingUser;
    182 
    183     private boolean mSystemReady;
    184     private boolean mBootCompleted;
    185     private boolean mBootSendUserPresent;
    186 
    187     // Whether the next call to playSounds() should be skipped.  Defaults to
    188     // true because the first lock (on boot) should be silent.
    189     private boolean mSuppressNextLockSound = true;
    190 
    191 
    192     /** High level access to the power manager for WakeLocks */
    193     private PowerManager mPM;
    194 
    195     /** High level access to the window manager for dismissing keyguard animation */
    196     private IWindowManager mWM;
    197 
    198 
    199     /** TrustManager for letting it know when we change visibility */
    200     private TrustManager mTrustManager;
    201 
    202     /** SearchManager for determining whether or not search assistant is available */
    203     private SearchManager mSearchManager;
    204 
    205     /**
    206      * Used to keep the device awake while to ensure the keyguard finishes opening before
    207      * we sleep.
    208      */
    209     private PowerManager.WakeLock mShowKeyguardWakeLock;
    210 
    211     private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
    212 
    213     // these are protected by synchronized (this)
    214 
    215     /**
    216      * External apps (like the phone app) can tell us to disable the keygaurd.
    217      */
    218     private boolean mExternallyEnabled = true;
    219 
    220     /**
    221      * Remember if an external call to {@link #setKeyguardEnabled} with value
    222      * false caused us to hide the keyguard, so that we need to reshow it once
    223      * the keygaurd is reenabled with another call with value true.
    224      */
    225     private boolean mNeedToReshowWhenReenabled = false;
    226 
    227     // cached value of whether we are showing (need to know this to quickly
    228     // answer whether the input should be restricted)
    229     private boolean mShowing;
    230 
    231     /** Cached value of #isInputRestricted */
    232     private boolean mInputRestricted;
    233 
    234     // true if the keyguard is hidden by another window
    235     private boolean mOccluded = false;
    236 
    237     /**
    238      * Helps remember whether the screen has turned on since the last time
    239      * it turned off due to timeout. see {@link #onScreenTurnedOff(int)}
    240      */
    241     private int mDelayedShowingSequence;
    242 
    243     /**
    244      * If the user has disabled the keyguard, then requests to exit, this is
    245      * how we'll ultimately let them know whether it was successful.  We use this
    246      * var being non-null as an indicator that there is an in progress request.
    247      */
    248     private IKeyguardExitCallback mExitSecureCallback;
    249 
    250     // the properties of the keyguard
    251 
    252     private KeyguardUpdateMonitor mUpdateMonitor;
    253 
    254     private boolean mScreenOn;
    255 
    256     // last known state of the cellular connection
    257     private String mPhoneState = TelephonyManager.EXTRA_STATE_IDLE;
    258 
    259     /**
    260      * Whether a hide is pending an we are just waiting for #startKeyguardExitAnimation to be
    261      * called.
    262      * */
    263     private boolean mHiding;
    264 
    265     /**
    266      * we send this intent when the keyguard is dismissed.
    267      */
    268     private static final Intent USER_PRESENT_INTENT = new Intent(Intent.ACTION_USER_PRESENT)
    269             .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
    270                     | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
    271 
    272     /**
    273      * {@link #setKeyguardEnabled} waits on this condition when it reenables
    274      * the keyguard.
    275      */
    276     private boolean mWaitingUntilKeyguardVisible = false;
    277     private LockPatternUtils mLockPatternUtils;
    278     private boolean mKeyguardDonePending = false;
    279     private boolean mHideAnimationRun = false;
    280 
    281     private SoundPool mLockSounds;
    282     private int mLockSoundId;
    283     private int mUnlockSoundId;
    284     private int mTrustedSoundId;
    285     private int mLockSoundStreamId;
    286 
    287     /**
    288      * The animation used for hiding keyguard. This is used to fetch the animation timings if
    289      * WindowManager is not providing us with them.
    290      */
    291     private Animation mHideAnimation;
    292 
    293     /**
    294      * The volume applied to the lock/unlock sounds.
    295      */
    296     private float mLockSoundVolume;
    297 
    298     /**
    299      * For managing external displays
    300      */
    301     private KeyguardDisplayManager mKeyguardDisplayManager;
    302 
    303     private final ArrayList<IKeyguardStateCallback> mKeyguardStateCallbacks = new ArrayList<>();
    304 
    305     KeyguardUpdateMonitorCallback mUpdateCallback = new KeyguardUpdateMonitorCallback() {
    306 
    307         @Override
    308         public void onUserSwitching(int userId) {
    309             // Note that the mLockPatternUtils user has already been updated from setCurrentUser.
    310             // We need to force a reset of the views, since lockNow (called by
    311             // ActivityManagerService) will not reconstruct the keyguard if it is already showing.
    312             synchronized (KeyguardViewMediator.this) {
    313                 mSwitchingUser = true;
    314                 resetKeyguardDonePendingLocked();
    315                 resetStateLocked();
    316                 adjustStatusBarLocked();
    317                 // When we switch users we want to bring the new user to the biometric unlock even
    318                 // if the current user has gone to the backup.
    319                 KeyguardUpdateMonitor.getInstance(mContext).setAlternateUnlockEnabled(true);
    320             }
    321         }
    322 
    323         @Override
    324         public void onUserSwitchComplete(int userId) {
    325             mSwitchingUser = false;
    326             if (userId != UserHandle.USER_OWNER) {
    327                 UserInfo info = UserManager.get(mContext).getUserInfo(userId);
    328                 if (info != null && info.isGuest()) {
    329                     // If we just switched to a guest, try to dismiss keyguard.
    330                     dismiss();
    331                 }
    332             }
    333         }
    334 
    335         @Override
    336         public void onUserRemoved(int userId) {
    337             mLockPatternUtils.removeUser(userId);
    338             MultiUserAvatarCache.getInstance().clear(userId);
    339         }
    340 
    341         @Override
    342         public void onUserInfoChanged(int userId) {
    343             MultiUserAvatarCache.getInstance().clear(userId);
    344         }
    345 
    346         @Override
    347         public void onPhoneStateChanged(int phoneState) {
    348             synchronized (KeyguardViewMediator.this) {
    349                 if (TelephonyManager.CALL_STATE_IDLE == phoneState  // call ending
    350                         && !mScreenOn                           // screen off
    351                         && mExternallyEnabled) {                // not disabled by any app
    352 
    353                     // note: this is a way to gracefully reenable the keyguard when the call
    354                     // ends and the screen is off without always reenabling the keyguard
    355                     // each time the screen turns off while in call (and having an occasional ugly
    356                     // flicker while turning back on the screen and disabling the keyguard again).
    357                     if (DEBUG) Log.d(TAG, "screen is off and call ended, let's make sure the "
    358                             + "keyguard is showing");
    359                     doKeyguardLocked(null);
    360                 }
    361             }
    362         }
    363 
    364         @Override
    365         public void onClockVisibilityChanged() {
    366             adjustStatusBarLocked();
    367         }
    368 
    369         @Override
    370         public void onDeviceProvisioned() {
    371             sendUserPresentBroadcast();
    372             updateInputRestricted();
    373         }
    374 
    375         @Override
    376         public void onSimStateChanged(int subId, int slotId, IccCardConstants.State simState) {
    377 
    378             if (DEBUG_SIM_STATES) {
    379                 Log.d(TAG, "onSimStateChanged(subId=" + subId + ", slotId=" + slotId
    380                         + ",state=" + simState + ")");
    381             }
    382 
    383             try {
    384                 int size = mKeyguardStateCallbacks.size();
    385                 boolean simPinSecure = mUpdateMonitor.isSimPinSecure();
    386                 for (int i = 0; i < size; i++) {
    387                     mKeyguardStateCallbacks.get(i).onSimSecureStateChanged(simPinSecure);
    388                 }
    389             } catch (RemoteException e) {
    390                 Slog.w(TAG, "Failed to call onSimSecureStateChanged", e);
    391             }
    392 
    393             switch (simState) {
    394                 case NOT_READY:
    395                 case ABSENT:
    396                     // only force lock screen in case of missing sim if user hasn't
    397                     // gone through setup wizard
    398                     synchronized (this) {
    399                         if (shouldWaitForProvisioning()) {
    400                             if (!mShowing) {
    401                                 if (DEBUG_SIM_STATES) Log.d(TAG, "ICC_ABSENT isn't showing,"
    402                                         + " we need to show the keyguard since the "
    403                                         + "device isn't provisioned yet.");
    404                                 doKeyguardLocked(null);
    405                             } else {
    406                                 resetStateLocked();
    407                             }
    408                         }
    409                     }
    410                     break;
    411                 case PIN_REQUIRED:
    412                 case PUK_REQUIRED:
    413                     synchronized (this) {
    414                         if (!mShowing) {
    415                             if (DEBUG_SIM_STATES) Log.d(TAG,
    416                                     "INTENT_VALUE_ICC_LOCKED and keygaurd isn't "
    417                                     + "showing; need to show keyguard so user can enter sim pin");
    418                             doKeyguardLocked(null);
    419                         } else {
    420                             resetStateLocked();
    421                         }
    422                     }
    423                     break;
    424                 case PERM_DISABLED:
    425                     synchronized (this) {
    426                         if (!mShowing) {
    427                             if (DEBUG_SIM_STATES) Log.d(TAG, "PERM_DISABLED and "
    428                                   + "keygaurd isn't showing.");
    429                             doKeyguardLocked(null);
    430                         } else {
    431                             if (DEBUG_SIM_STATES) Log.d(TAG, "PERM_DISABLED, resetStateLocked to"
    432                                   + "show permanently disabled message in lockscreen.");
    433                             resetStateLocked();
    434                         }
    435                     }
    436                     break;
    437                 case READY:
    438                     synchronized (this) {
    439                         if (mShowing) {
    440                             resetStateLocked();
    441                         }
    442                     }
    443                     break;
    444                 default:
    445                     if (DEBUG_SIM_STATES) Log.v(TAG, "Ignoring state: " + simState);
    446                     break;
    447             }
    448         }
    449 
    450         public void onFingerprintRecognized(int userId) {
    451             if (mStatusBarKeyguardViewManager.isBouncerShowing()) {
    452                 mViewMediatorCallback.keyguardDone(true);
    453             }
    454         };
    455 
    456     };
    457 
    458     ViewMediatorCallback mViewMediatorCallback = new ViewMediatorCallback() {
    459 
    460         public void userActivity() {
    461             KeyguardViewMediator.this.userActivity();
    462         }
    463 
    464         public void keyguardDone(boolean authenticated) {
    465             if (!mKeyguardDonePending) {
    466                 KeyguardViewMediator.this.keyguardDone(authenticated, true);
    467             }
    468         }
    469 
    470         public void keyguardDoneDrawing() {
    471             mHandler.sendEmptyMessage(KEYGUARD_DONE_DRAWING);
    472         }
    473 
    474         @Override
    475         public void setNeedsInput(boolean needsInput) {
    476             mStatusBarKeyguardViewManager.setNeedsInput(needsInput);
    477         }
    478 
    479         @Override
    480         public void onUserActivityTimeoutChanged() {
    481             mStatusBarKeyguardViewManager.updateUserActivityTimeout();
    482         }
    483 
    484         @Override
    485         public void keyguardDonePending() {
    486             mKeyguardDonePending = true;
    487             mHideAnimationRun = true;
    488             mStatusBarKeyguardViewManager.startPreHideAnimation(null /* finishRunnable */);
    489             mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_PENDING_TIMEOUT,
    490                     KEYGUARD_DONE_PENDING_TIMEOUT_MS);
    491         }
    492 
    493         @Override
    494         public void keyguardGone() {
    495             mKeyguardDisplayManager.hide();
    496         }
    497 
    498         @Override
    499         public void readyForKeyguardDone() {
    500             if (mKeyguardDonePending) {
    501                 // Somebody has called keyguardDonePending before, which means that we are
    502                 // authenticated
    503                 KeyguardViewMediator.this.keyguardDone(true /* authenticated */, true /* wakeUp */);
    504             }
    505         }
    506 
    507         @Override
    508         public void playTrustedSound() {
    509             KeyguardViewMediator.this.playTrustedSound();
    510         }
    511 
    512         @Override
    513         public boolean isInputRestricted() {
    514             return KeyguardViewMediator.this.isInputRestricted();
    515         }
    516     };
    517 
    518     public void userActivity() {
    519         mPM.userActivity(SystemClock.uptimeMillis(), false);
    520     }
    521 
    522     private void setupLocked() {
    523         mPM = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
    524         mWM = WindowManagerGlobal.getWindowManagerService();
    525         mTrustManager = (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
    526 
    527         mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "show keyguard");
    528         mShowKeyguardWakeLock.setReferenceCounted(false);
    529 
    530         mContext.registerReceiver(mBroadcastReceiver, new IntentFilter(DELAYED_KEYGUARD_ACTION));
    531 
    532         mKeyguardDisplayManager = new KeyguardDisplayManager(mContext);
    533 
    534         mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    535 
    536         mUpdateMonitor = KeyguardUpdateMonitor.getInstance(mContext);
    537 
    538         mLockPatternUtils = new LockPatternUtils(mContext);
    539         mLockPatternUtils.setCurrentUser(ActivityManager.getCurrentUser());
    540 
    541         // Assume keyguard is showing (unless it's disabled) until we know for sure...
    542         setShowingLocked(!shouldWaitForProvisioning() && !mLockPatternUtils.isLockScreenDisabled());
    543         mTrustManager.reportKeyguardShowingChanged();
    544 
    545         mStatusBarKeyguardViewManager = new StatusBarKeyguardViewManager(mContext,
    546                 mViewMediatorCallback, mLockPatternUtils);
    547         final ContentResolver cr = mContext.getContentResolver();
    548 
    549         mScreenOn = mPM.isScreenOn();
    550 
    551         mLockSounds = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
    552         String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND);
    553         if (soundPath != null) {
    554             mLockSoundId = mLockSounds.load(soundPath, 1);
    555         }
    556         if (soundPath == null || mLockSoundId == 0) {
    557             Log.w(TAG, "failed to load lock sound from " + soundPath);
    558         }
    559         soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND);
    560         if (soundPath != null) {
    561             mUnlockSoundId = mLockSounds.load(soundPath, 1);
    562         }
    563         if (soundPath == null || mUnlockSoundId == 0) {
    564             Log.w(TAG, "failed to load unlock sound from " + soundPath);
    565         }
    566         soundPath = Settings.Global.getString(cr, Settings.Global.TRUSTED_SOUND);
    567         if (soundPath != null) {
    568             mTrustedSoundId = mLockSounds.load(soundPath, 1);
    569         }
    570         if (soundPath == null || mTrustedSoundId == 0) {
    571             Log.w(TAG, "failed to load trusted sound from " + soundPath);
    572         }
    573 
    574         int lockSoundDefaultAttenuation = mContext.getResources().getInteger(
    575                 com.android.internal.R.integer.config_lockSoundVolumeDb);
    576         mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20);
    577 
    578         mHideAnimation = AnimationUtils.loadAnimation(mContext,
    579                 com.android.internal.R.anim.lock_screen_behind_enter);
    580     }
    581 
    582     @Override
    583     public void start() {
    584         synchronized (this) {
    585             setupLocked();
    586         }
    587         putComponent(KeyguardViewMediator.class, this);
    588     }
    589 
    590     /**
    591      * Let us know that the system is ready after startup.
    592      */
    593     public void onSystemReady() {
    594         mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
    595         synchronized (this) {
    596             if (DEBUG) Log.d(TAG, "onSystemReady");
    597             mSystemReady = true;
    598             mUpdateMonitor.registerCallback(mUpdateCallback);
    599 
    600             // Suppress biometric unlock right after boot until things have settled if it is the
    601             // selected security method, otherwise unsuppress it.  It must be unsuppressed if it is
    602             // not the selected security method for the following reason:  if the user starts
    603             // without a screen lock selected, the biometric unlock would be suppressed the first
    604             // time they try to use it.
    605             //
    606             // Note that the biometric unlock will still not show if it is not the selected method.
    607             // Calling setAlternateUnlockEnabled(true) simply says don't suppress it if it is the
    608             // selected method.
    609             if (mLockPatternUtils.usingBiometricWeak()
    610                     && mLockPatternUtils.isBiometricWeakInstalled()) {
    611                 if (DEBUG) Log.d(TAG, "suppressing biometric unlock during boot");
    612                 mUpdateMonitor.setAlternateUnlockEnabled(false);
    613             } else {
    614                 mUpdateMonitor.setAlternateUnlockEnabled(true);
    615             }
    616 
    617             doKeyguardLocked(null);
    618         }
    619         // Most services aren't available until the system reaches the ready state, so we
    620         // send it here when the device first boots.
    621         maybeSendUserPresentBroadcast();
    622     }
    623 
    624     /**
    625      * Called to let us know the screen was turned off.
    626      * @param why either {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_USER} or
    627      *   {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT}.
    628      */
    629     public void onScreenTurnedOff(int why) {
    630         synchronized (this) {
    631             mScreenOn = false;
    632             if (DEBUG) Log.d(TAG, "onScreenTurnedOff(" + why + ")");
    633 
    634             resetKeyguardDonePendingLocked();
    635             mHideAnimationRun = false;
    636 
    637             // Lock immediately based on setting if secure (user has a pin/pattern/password).
    638             // This also "locks" the device when not secure to provide easy access to the
    639             // camera while preventing unwanted input.
    640             final boolean lockImmediately =
    641                 mLockPatternUtils.getPowerButtonInstantlyLocks() || !mLockPatternUtils.isSecure();
    642 
    643             notifyScreenOffLocked();
    644 
    645             if (mExitSecureCallback != null) {
    646                 if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
    647                 try {
    648                     mExitSecureCallback.onKeyguardExitResult(false);
    649                 } catch (RemoteException e) {
    650                     Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
    651                 }
    652                 mExitSecureCallback = null;
    653                 if (!mExternallyEnabled) {
    654                     hideLocked();
    655                 }
    656             } else if (mShowing) {
    657                 resetStateLocked();
    658             } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT
    659                    || (why == WindowManagerPolicy.OFF_BECAUSE_OF_USER && !lockImmediately)) {
    660                 doKeyguardLaterLocked();
    661             } else {
    662                 doKeyguardLocked(null);
    663             }
    664         }
    665         KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurndOff(why);
    666     }
    667 
    668     private void doKeyguardLaterLocked() {
    669         // if the screen turned off because of timeout or the user hit the power button
    670         // and we don't need to lock immediately, set an alarm
    671         // to enable it a little bit later (i.e, give the user a chance
    672         // to turn the screen back on within a certain window without
    673         // having to unlock the screen)
    674         final ContentResolver cr = mContext.getContentResolver();
    675 
    676         // From DisplaySettings
    677         long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
    678                 KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);
    679 
    680         // From SecuritySettings
    681         final long lockAfterTimeout = Settings.Secure.getInt(cr,
    682                 Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
    683                 KEYGUARD_LOCK_AFTER_DELAY_DEFAULT);
    684 
    685         // From DevicePolicyAdmin
    686         final long policyTimeout = mLockPatternUtils.getDevicePolicyManager()
    687                 .getMaximumTimeToLock(null, mLockPatternUtils.getCurrentUser());
    688 
    689         long timeout;
    690         if (policyTimeout > 0) {
    691             // policy in effect. Make sure we don't go beyond policy limit.
    692             displayTimeout = Math.max(displayTimeout, 0); // ignore negative values
    693             timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);
    694         } else {
    695             timeout = lockAfterTimeout;
    696         }
    697 
    698         if (timeout <= 0) {
    699             // Lock now
    700             mSuppressNextLockSound = true;
    701             doKeyguardLocked(null);
    702         } else {
    703             // Lock in the future
    704             long when = SystemClock.elapsedRealtime() + timeout;
    705             Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
    706             intent.putExtra("seq", mDelayedShowingSequence);
    707             PendingIntent sender = PendingIntent.getBroadcast(mContext,
    708                     0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    709             mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender);
    710             if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = "
    711                              + mDelayedShowingSequence);
    712         }
    713     }
    714 
    715     private void cancelDoKeyguardLaterLocked() {
    716         mDelayedShowingSequence++;
    717     }
    718 
    719     /**
    720      * Let's us know the screen was turned on.
    721      */
    722     public void onScreenTurnedOn(IKeyguardShowCallback callback) {
    723         synchronized (this) {
    724             mScreenOn = true;
    725             cancelDoKeyguardLaterLocked();
    726             if (DEBUG) Log.d(TAG, "onScreenTurnedOn, seq = " + mDelayedShowingSequence);
    727             if (callback != null) {
    728                 notifyScreenOnLocked(callback);
    729             }
    730         }
    731         KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurnedOn();
    732         maybeSendUserPresentBroadcast();
    733     }
    734 
    735     private void maybeSendUserPresentBroadcast() {
    736         if (mSystemReady && mLockPatternUtils.isLockScreenDisabled()) {
    737             // Lock screen is disabled because the user has set the preference to "None".
    738             // In this case, send out ACTION_USER_PRESENT here instead of in
    739             // handleKeyguardDone()
    740             sendUserPresentBroadcast();
    741         }
    742     }
    743 
    744     /**
    745      * A dream started.  We should lock after the usual screen-off lock timeout but only
    746      * if there is a secure lock pattern.
    747      */
    748     public void onDreamingStarted() {
    749         synchronized (this) {
    750             if (mScreenOn && mLockPatternUtils.isSecure()) {
    751                 doKeyguardLaterLocked();
    752             }
    753         }
    754     }
    755 
    756     /**
    757      * A dream stopped.
    758      */
    759     public void onDreamingStopped() {
    760         synchronized (this) {
    761             if (mScreenOn) {
    762                 cancelDoKeyguardLaterLocked();
    763             }
    764         }
    765     }
    766 
    767     /**
    768      * Same semantics as {@link android.view.WindowManagerPolicy#enableKeyguard}; provide
    769      * a way for external stuff to override normal keyguard behavior.  For instance
    770      * the phone app disables the keyguard when it receives incoming calls.
    771      */
    772     public void setKeyguardEnabled(boolean enabled) {
    773         synchronized (this) {
    774             if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
    775 
    776             mExternallyEnabled = enabled;
    777 
    778             if (!enabled && mShowing) {
    779                 if (mExitSecureCallback != null) {
    780                     if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
    781                     // we're in the process of handling a request to verify the user
    782                     // can get past the keyguard. ignore extraneous requests to disable / reenable
    783                     return;
    784                 }
    785 
    786                 // hiding keyguard that is showing, remember to reshow later
    787                 if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
    788                         + "disabling status bar expansion");
    789                 mNeedToReshowWhenReenabled = true;
    790                 updateInputRestrictedLocked();
    791                 hideLocked();
    792             } else if (enabled && mNeedToReshowWhenReenabled) {
    793                 // reenabled after previously hidden, reshow
    794                 if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
    795                         + "status bar expansion");
    796                 mNeedToReshowWhenReenabled = false;
    797                 updateInputRestrictedLocked();
    798 
    799                 if (mExitSecureCallback != null) {
    800                     if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
    801                     try {
    802                         mExitSecureCallback.onKeyguardExitResult(false);
    803                     } catch (RemoteException e) {
    804                         Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
    805                     }
    806                     mExitSecureCallback = null;
    807                     resetStateLocked();
    808                 } else {
    809                     showLocked(null);
    810 
    811                     // block until we know the keygaurd is done drawing (and post a message
    812                     // to unblock us after a timeout so we don't risk blocking too long
    813                     // and causing an ANR).
    814                     mWaitingUntilKeyguardVisible = true;
    815                     mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
    816                     if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
    817                     while (mWaitingUntilKeyguardVisible) {
    818                         try {
    819                             wait();
    820                         } catch (InterruptedException e) {
    821                             Thread.currentThread().interrupt();
    822                         }
    823                     }
    824                     if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
    825                 }
    826             }
    827         }
    828     }
    829 
    830     /**
    831      * @see android.app.KeyguardManager#exitKeyguardSecurely
    832      */
    833     public void verifyUnlock(IKeyguardExitCallback callback) {
    834         synchronized (this) {
    835             if (DEBUG) Log.d(TAG, "verifyUnlock");
    836             if (shouldWaitForProvisioning()) {
    837                 // don't allow this api when the device isn't provisioned
    838                 if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
    839                 try {
    840                     callback.onKeyguardExitResult(false);
    841                 } catch (RemoteException e) {
    842                     Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
    843                 }
    844             } else if (mExternallyEnabled) {
    845                 // this only applies when the user has externally disabled the
    846                 // keyguard.  this is unexpected and means the user is not
    847                 // using the api properly.
    848                 Log.w(TAG, "verifyUnlock called when not externally disabled");
    849                 try {
    850                     callback.onKeyguardExitResult(false);
    851                 } catch (RemoteException e) {
    852                     Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
    853                 }
    854             } else if (mExitSecureCallback != null) {
    855                 // already in progress with someone else
    856                 try {
    857                     callback.onKeyguardExitResult(false);
    858                 } catch (RemoteException e) {
    859                     Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
    860                 }
    861             } else {
    862                 mExitSecureCallback = callback;
    863                 verifyUnlockLocked();
    864             }
    865         }
    866     }
    867 
    868     /**
    869      * Is the keyguard currently showing and not being force hidden?
    870      */
    871     public boolean isShowingAndNotOccluded() {
    872         return mShowing && !mOccluded;
    873     }
    874 
    875     /**
    876      * Notify us when the keyguard is occluded by another window
    877      */
    878     public void setOccluded(boolean isOccluded) {
    879         if (DEBUG) Log.d(TAG, "setOccluded " + isOccluded);
    880         mHandler.removeMessages(SET_OCCLUDED);
    881         Message msg = mHandler.obtainMessage(SET_OCCLUDED, (isOccluded ? 1 : 0), 0);
    882         mHandler.sendMessage(msg);
    883     }
    884 
    885     /**
    886      * Handles SET_OCCLUDED message sent by setOccluded()
    887      */
    888     private void handleSetOccluded(boolean isOccluded) {
    889         synchronized (KeyguardViewMediator.this) {
    890             if (mOccluded != isOccluded) {
    891                 mOccluded = isOccluded;
    892                 mStatusBarKeyguardViewManager.setOccluded(isOccluded);
    893                 updateActivityLockScreenState();
    894                 adjustStatusBarLocked();
    895             }
    896         }
    897     }
    898 
    899     /**
    900      * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout.
    901      * This must be safe to call from any thread and with any window manager locks held.
    902      */
    903     public void doKeyguardTimeout(Bundle options) {
    904         mHandler.removeMessages(KEYGUARD_TIMEOUT);
    905         Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
    906         mHandler.sendMessage(msg);
    907     }
    908 
    909     /**
    910      * Given the state of the keyguard, is the input restricted?
    911      * Input is restricted when the keyguard is showing, or when the keyguard
    912      * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.
    913      */
    914     public boolean isInputRestricted() {
    915         return mShowing || mNeedToReshowWhenReenabled || shouldWaitForProvisioning();
    916     }
    917 
    918     private void updateInputRestricted() {
    919         synchronized (this) {
    920             updateInputRestrictedLocked();
    921         }
    922     }
    923     private void updateInputRestrictedLocked() {
    924         boolean inputRestricted = isInputRestricted();
    925         if (mInputRestricted != inputRestricted) {
    926             mInputRestricted = inputRestricted;
    927             try {
    928                 int size = mKeyguardStateCallbacks.size();
    929                 for (int i = 0; i < size; i++) {
    930                     mKeyguardStateCallbacks.get(i).onInputRestrictedStateChanged(inputRestricted);
    931                 }
    932             } catch (RemoteException e) {
    933                 Slog.w(TAG, "Failed to call onDeviceProvisioned", e);
    934             }
    935         }
    936     }
    937 
    938     /**
    939      * Enable the keyguard if the settings are appropriate.
    940      */
    941     private void doKeyguardLocked(Bundle options) {
    942         // if another app is disabling us, don't show
    943         if (!mExternallyEnabled) {
    944             if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");
    945 
    946             // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes
    947             // for an occasional ugly flicker in this situation:
    948             // 1) receive a call with the screen on (no keyguard) or make a call
    949             // 2) screen times out
    950             // 3) user hits key to turn screen back on
    951             // instead, we reenable the keyguard when we know the screen is off and the call
    952             // ends (see the broadcast receiver below)
    953             // TODO: clean this up when we have better support at the window manager level
    954             // for apps that wish to be on top of the keyguard
    955             return;
    956         }
    957 
    958         // if the keyguard is already showing, don't bother
    959         if (mStatusBarKeyguardViewManager.isShowing()) {
    960             if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
    961             resetStateLocked();
    962             return;
    963         }
    964 
    965         // if the setup wizard hasn't run yet, don't show
    966         final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim", false);
    967         final boolean absent = SubscriptionManager.isValidSubscriptionId(
    968                 mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.ABSENT));
    969         final boolean disabled = SubscriptionManager.isValidSubscriptionId(
    970                 mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.PERM_DISABLED));
    971         final boolean lockedOrMissing = mUpdateMonitor.isSimPinSecure()
    972                 || ((absent || disabled) && requireSim);
    973 
    974         if (!lockedOrMissing && shouldWaitForProvisioning()) {
    975             if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
    976                     + " and the sim is not locked or missing");
    977             return;
    978         }
    979 
    980         if (mLockPatternUtils.isLockScreenDisabled() && !lockedOrMissing) {
    981             if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
    982             return;
    983         }
    984 
    985         if (mLockPatternUtils.checkVoldPassword()) {
    986             if (DEBUG) Log.d(TAG, "Not showing lock screen since just decrypted");
    987             // Without this, settings is not enabled until the lock screen first appears
    988             setShowingLocked(false);
    989             hideLocked();
    990             return;
    991         }
    992 
    993         if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
    994         showLocked(options);
    995     }
    996 
    997     private boolean shouldWaitForProvisioning() {
    998         return !mUpdateMonitor.isDeviceProvisioned() && !isSecure();
    999     }
   1000 
   1001     /**
   1002      * Dismiss the keyguard through the security layers.
   1003      */
   1004     public void handleDismiss() {
   1005         if (mShowing && !mOccluded) {
   1006             mStatusBarKeyguardViewManager.dismiss();
   1007         }
   1008     }
   1009 
   1010     public void dismiss() {
   1011         mHandler.sendEmptyMessage(DISMISS);
   1012     }
   1013 
   1014     /**
   1015      * Send message to keyguard telling it to reset its state.
   1016      * @see #handleReset
   1017      */
   1018     private void resetStateLocked() {
   1019         if (DEBUG) Log.e(TAG, "resetStateLocked");
   1020         Message msg = mHandler.obtainMessage(RESET);
   1021         mHandler.sendMessage(msg);
   1022     }
   1023 
   1024     /**
   1025      * Send message to keyguard telling it to verify unlock
   1026      * @see #handleVerifyUnlock()
   1027      */
   1028     private void verifyUnlockLocked() {
   1029         if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
   1030         mHandler.sendEmptyMessage(VERIFY_UNLOCK);
   1031     }
   1032 
   1033 
   1034     /**
   1035      * Send a message to keyguard telling it the screen just turned on.
   1036      * @see #onScreenTurnedOff(int)
   1037      * @see #handleNotifyScreenOff
   1038      */
   1039     private void notifyScreenOffLocked() {
   1040         if (DEBUG) Log.d(TAG, "notifyScreenOffLocked");
   1041         mHandler.sendEmptyMessage(NOTIFY_SCREEN_OFF);
   1042     }
   1043 
   1044     /**
   1045      * Send a message to keyguard telling it the screen just turned on.
   1046      * @see #onScreenTurnedOn
   1047      * @see #handleNotifyScreenOn
   1048      */
   1049     private void notifyScreenOnLocked(IKeyguardShowCallback result) {
   1050         if (DEBUG) Log.d(TAG, "notifyScreenOnLocked");
   1051         Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_ON, result);
   1052         mHandler.sendMessage(msg);
   1053     }
   1054 
   1055     /**
   1056      * Send message to keyguard telling it to show itself
   1057      * @see #handleShow
   1058      */
   1059     private void showLocked(Bundle options) {
   1060         if (DEBUG) Log.d(TAG, "showLocked");
   1061         // ensure we stay awake until we are finished displaying the keyguard
   1062         mShowKeyguardWakeLock.acquire();
   1063         Message msg = mHandler.obtainMessage(SHOW, options);
   1064         mHandler.sendMessage(msg);
   1065     }
   1066 
   1067     /**
   1068      * Send message to keyguard telling it to hide itself
   1069      * @see #handleHide()
   1070      */
   1071     private void hideLocked() {
   1072         if (DEBUG) Log.d(TAG, "hideLocked");
   1073         Message msg = mHandler.obtainMessage(HIDE);
   1074         mHandler.sendMessage(msg);
   1075     }
   1076 
   1077     public boolean isSecure() {
   1078         return mLockPatternUtils.isSecure()
   1079             || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
   1080     }
   1081 
   1082     /**
   1083      * Update the newUserId. Call while holding WindowManagerService lock.
   1084      * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.
   1085      *
   1086      * @param newUserId The id of the incoming user.
   1087      */
   1088     public void setCurrentUser(int newUserId) {
   1089         mLockPatternUtils.setCurrentUser(newUserId);
   1090     }
   1091 
   1092     private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
   1093         @Override
   1094         public void onReceive(Context context, Intent intent) {
   1095             if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {
   1096                 final int sequence = intent.getIntExtra("seq", 0);
   1097                 if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
   1098                         + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
   1099                 synchronized (KeyguardViewMediator.this) {
   1100                     if (mDelayedShowingSequence == sequence) {
   1101                         // Don't play lockscreen SFX if the screen went off due to timeout.
   1102                         mSuppressNextLockSound = true;
   1103                         doKeyguardLocked(null);
   1104                     }
   1105                 }
   1106             }
   1107         }
   1108     };
   1109 
   1110     public void keyguardDone(boolean authenticated, boolean wakeup) {
   1111         if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated + ")");
   1112         EventLog.writeEvent(70000, 2);
   1113         Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0, wakeup ? 1 : 0);
   1114         mHandler.sendMessage(msg);
   1115     }
   1116 
   1117     /**
   1118      * This handler will be associated with the policy thread, which will also
   1119      * be the UI thread of the keyguard.  Since the apis of the policy, and therefore
   1120      * this class, can be called by other threads, any action that directly
   1121      * interacts with the keyguard ui should be posted to this handler, rather
   1122      * than called directly.
   1123      */
   1124     private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
   1125         @Override
   1126         public void handleMessage(Message msg) {
   1127             switch (msg.what) {
   1128                 case SHOW:
   1129                     handleShow((Bundle) msg.obj);
   1130                     break;
   1131                 case HIDE:
   1132                     handleHide();
   1133                     break;
   1134                 case RESET:
   1135                     handleReset();
   1136                     break;
   1137                 case VERIFY_UNLOCK:
   1138                     handleVerifyUnlock();
   1139                     break;
   1140                 case NOTIFY_SCREEN_OFF:
   1141                     handleNotifyScreenOff();
   1142                     break;
   1143                 case NOTIFY_SCREEN_ON:
   1144                     handleNotifyScreenOn((IKeyguardShowCallback) msg.obj);
   1145                     break;
   1146                 case KEYGUARD_DONE:
   1147                     handleKeyguardDone(msg.arg1 != 0, msg.arg2 != 0);
   1148                     break;
   1149                 case KEYGUARD_DONE_DRAWING:
   1150                     handleKeyguardDoneDrawing();
   1151                     break;
   1152                 case KEYGUARD_DONE_AUTHENTICATING:
   1153                     keyguardDone(true, true);
   1154                     break;
   1155                 case SET_OCCLUDED:
   1156                     handleSetOccluded(msg.arg1 != 0);
   1157                     break;
   1158                 case KEYGUARD_TIMEOUT:
   1159                     synchronized (KeyguardViewMediator.this) {
   1160                         doKeyguardLocked((Bundle) msg.obj);
   1161                     }
   1162                     break;
   1163                 case DISMISS:
   1164                     handleDismiss();
   1165                     break;
   1166                 case START_KEYGUARD_EXIT_ANIM:
   1167                     StartKeyguardExitAnimParams params = (StartKeyguardExitAnimParams) msg.obj;
   1168                     handleStartKeyguardExitAnimation(params.startTime, params.fadeoutDuration);
   1169                     break;
   1170                 case KEYGUARD_DONE_PENDING_TIMEOUT:
   1171                     Log.w(TAG, "Timeout while waiting for activity drawn!");
   1172                     // Fall through.
   1173                 case ON_ACTIVITY_DRAWN:
   1174                     handleOnActivityDrawn();
   1175                     break;
   1176             }
   1177         }
   1178     };
   1179 
   1180     /**
   1181      * @see #keyguardDone
   1182      * @see #KEYGUARD_DONE
   1183      */
   1184     private void handleKeyguardDone(boolean authenticated, boolean wakeup) {
   1185         if (DEBUG) Log.d(TAG, "handleKeyguardDone");
   1186         synchronized (this) {
   1187             resetKeyguardDonePendingLocked();
   1188         }
   1189 
   1190         if (authenticated) {
   1191             mUpdateMonitor.clearFailedUnlockAttempts();
   1192         }
   1193         mUpdateMonitor.clearFingerprintRecognized();
   1194 
   1195         if (mExitSecureCallback != null) {
   1196             try {
   1197                 mExitSecureCallback.onKeyguardExitResult(authenticated);
   1198             } catch (RemoteException e) {
   1199                 Slog.w(TAG, "Failed to call onKeyguardExitResult(" + authenticated + ")", e);
   1200             }
   1201 
   1202             mExitSecureCallback = null;
   1203 
   1204             if (authenticated) {
   1205                 // after succesfully exiting securely, no need to reshow
   1206                 // the keyguard when they've released the lock
   1207                 mExternallyEnabled = true;
   1208                 mNeedToReshowWhenReenabled = false;
   1209                 updateInputRestricted();
   1210             }
   1211         }
   1212 
   1213         handleHide();
   1214     }
   1215 
   1216     private void sendUserPresentBroadcast() {
   1217         synchronized (this) {
   1218             if (mBootCompleted) {
   1219                 final UserHandle currentUser = new UserHandle(mLockPatternUtils.getCurrentUser());
   1220                 final UserManager um = (UserManager) mContext.getSystemService(
   1221                         Context.USER_SERVICE);
   1222                 List <UserInfo> userHandles = um.getProfiles(currentUser.getIdentifier());
   1223                 for (UserInfo ui : userHandles) {
   1224                     mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, ui.getUserHandle());
   1225                 }
   1226             } else {
   1227                 mBootSendUserPresent = true;
   1228             }
   1229         }
   1230     }
   1231 
   1232     /**
   1233      * @see #keyguardDone
   1234      * @see #KEYGUARD_DONE_DRAWING
   1235      */
   1236     private void handleKeyguardDoneDrawing() {
   1237         synchronized(this) {
   1238             if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing");
   1239             if (mWaitingUntilKeyguardVisible) {
   1240                 if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
   1241                 mWaitingUntilKeyguardVisible = false;
   1242                 notifyAll();
   1243 
   1244                 // there will usually be two of these sent, one as a timeout, and one
   1245                 // as a result of the callback, so remove any remaining messages from
   1246                 // the queue
   1247                 mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
   1248             }
   1249         }
   1250     }
   1251 
   1252     private void playSounds(boolean locked) {
   1253         // User feedback for keyguard.
   1254 
   1255         if (mSuppressNextLockSound) {
   1256             mSuppressNextLockSound = false;
   1257             return;
   1258         }
   1259 
   1260         playSound(locked ? mLockSoundId : mUnlockSoundId);
   1261     }
   1262 
   1263     private void playSound(int soundId) {
   1264         if (soundId == 0) return;
   1265         final ContentResolver cr = mContext.getContentResolver();
   1266         if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
   1267 
   1268             mLockSounds.stop(mLockSoundStreamId);
   1269             // Init mAudioManager
   1270             if (mAudioManager == null) {
   1271                 mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
   1272                 if (mAudioManager == null) return;
   1273                 mMasterStreamType = mAudioManager.getMasterStreamType();
   1274             }
   1275             // If the stream is muted, don't play the sound
   1276             if (mAudioManager.isStreamMute(mMasterStreamType)) return;
   1277 
   1278             mLockSoundStreamId = mLockSounds.play(soundId,
   1279                     mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
   1280         }
   1281     }
   1282 
   1283     private void playTrustedSound() {
   1284         if (mSuppressNextLockSound) {
   1285             return;
   1286         }
   1287         playSound(mTrustedSoundId);
   1288     }
   1289 
   1290     private void updateActivityLockScreenState() {
   1291         try {
   1292             ActivityManagerNative.getDefault().setLockScreenShown(mShowing && !mOccluded);
   1293         } catch (RemoteException e) {
   1294         }
   1295     }
   1296 
   1297     /**
   1298      * Handle message sent by {@link #showLocked}.
   1299      * @see #SHOW
   1300      */
   1301     private void handleShow(Bundle options) {
   1302         synchronized (KeyguardViewMediator.this) {
   1303             if (!mSystemReady) {
   1304                 if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready.");
   1305                 return;
   1306             } else {
   1307                 if (DEBUG) Log.d(TAG, "handleShow");
   1308             }
   1309 
   1310             setShowingLocked(true);
   1311             mStatusBarKeyguardViewManager.show(options);
   1312             mHiding = false;
   1313             resetKeyguardDonePendingLocked();
   1314             mHideAnimationRun = false;
   1315             updateActivityLockScreenState();
   1316             adjustStatusBarLocked();
   1317             userActivity();
   1318 
   1319             // Do this at the end to not slow down display of the keyguard.
   1320             playSounds(true);
   1321 
   1322             mShowKeyguardWakeLock.release();
   1323         }
   1324         mKeyguardDisplayManager.show();
   1325     }
   1326 
   1327     private final Runnable mKeyguardGoingAwayRunnable = new Runnable() {
   1328         @Override
   1329         public void run() {
   1330             try {
   1331                 // Don't actually hide the Keyguard at the moment, wait for window
   1332                 // manager until it tells us it's safe to do so with
   1333                 // startKeyguardExitAnimation.
   1334                 mWM.keyguardGoingAway(
   1335                         mStatusBarKeyguardViewManager.shouldDisableWindowAnimationsForUnlock(),
   1336                         mStatusBarKeyguardViewManager.isGoingToNotificationShade());
   1337             } catch (RemoteException e) {
   1338                 Log.e(TAG, "Error while calling WindowManager", e);
   1339             }
   1340         }
   1341     };
   1342 
   1343     /**
   1344      * Handle message sent by {@link #hideLocked()}
   1345      * @see #HIDE
   1346      */
   1347     private void handleHide() {
   1348         synchronized (KeyguardViewMediator.this) {
   1349             if (DEBUG) Log.d(TAG, "handleHide");
   1350 
   1351             mHiding = true;
   1352             if (mShowing && !mOccluded) {
   1353                 if (!mHideAnimationRun) {
   1354                     mStatusBarKeyguardViewManager.startPreHideAnimation(mKeyguardGoingAwayRunnable);
   1355                 } else {
   1356                     mKeyguardGoingAwayRunnable.run();
   1357                 }
   1358             } else {
   1359 
   1360                 // Don't try to rely on WindowManager - if Keyguard wasn't showing, window
   1361                 // manager won't start the exit animation.
   1362                 handleStartKeyguardExitAnimation(
   1363                         SystemClock.uptimeMillis() + mHideAnimation.getStartOffset(),
   1364                         mHideAnimation.getDuration());
   1365             }
   1366         }
   1367     }
   1368 
   1369     private void handleOnActivityDrawn() {
   1370         if (DEBUG) Log.d(TAG, "handleOnActivityDrawn: mKeyguardDonePending=" + mKeyguardDonePending);
   1371         if (mKeyguardDonePending) {
   1372             mStatusBarKeyguardViewManager.onActivityDrawn();
   1373         }
   1374     }
   1375 
   1376     private void handleStartKeyguardExitAnimation(long startTime, long fadeoutDuration) {
   1377         synchronized (KeyguardViewMediator.this) {
   1378 
   1379             if (!mHiding) {
   1380                 return;
   1381             }
   1382             mHiding = false;
   1383 
   1384             // only play "unlock" noises if not on a call (since the incall UI
   1385             // disables the keyguard)
   1386             if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
   1387                 playSounds(false);
   1388             }
   1389 
   1390             setShowingLocked(false);
   1391             mStatusBarKeyguardViewManager.hide(startTime, fadeoutDuration);
   1392             resetKeyguardDonePendingLocked();
   1393             mHideAnimationRun = false;
   1394             updateActivityLockScreenState();
   1395             adjustStatusBarLocked();
   1396             sendUserPresentBroadcast();
   1397         }
   1398     }
   1399 
   1400     private void adjustStatusBarLocked() {
   1401         if (mStatusBarManager == null) {
   1402             mStatusBarManager = (StatusBarManager)
   1403                     mContext.getSystemService(Context.STATUS_BAR_SERVICE);
   1404         }
   1405         if (mStatusBarManager == null) {
   1406             Log.w(TAG, "Could not get status bar manager");
   1407         } else {
   1408             // Disable aspects of the system/status/navigation bars that must not be re-enabled by
   1409             // windows that appear on top, ever
   1410             int flags = StatusBarManager.DISABLE_NONE;
   1411             if (mShowing) {
   1412                 // Permanently disable components not available when keyguard is enabled
   1413                 // (like recents). Temporary enable/disable (e.g. the "back" button) are
   1414                 // done in KeyguardHostView.
   1415                 flags |= StatusBarManager.DISABLE_RECENT;
   1416                 flags |= StatusBarManager.DISABLE_SEARCH;
   1417             }
   1418             if (isShowingAndNotOccluded()) {
   1419                 flags |= StatusBarManager.DISABLE_HOME;
   1420             }
   1421 
   1422             if (DEBUG) {
   1423                 Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mOccluded=" + mOccluded
   1424                         + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
   1425             }
   1426 
   1427             if (!(mContext instanceof Activity)) {
   1428                 mStatusBarManager.disable(flags);
   1429             }
   1430         }
   1431     }
   1432 
   1433     /**
   1434      * Handle message sent by {@link #resetStateLocked}
   1435      * @see #RESET
   1436      */
   1437     private void handleReset() {
   1438         synchronized (KeyguardViewMediator.this) {
   1439             if (DEBUG) Log.d(TAG, "handleReset");
   1440             mStatusBarKeyguardViewManager.reset();
   1441         }
   1442     }
   1443 
   1444     /**
   1445      * Handle message sent by {@link #verifyUnlock}
   1446      * @see #VERIFY_UNLOCK
   1447      */
   1448     private void handleVerifyUnlock() {
   1449         synchronized (KeyguardViewMediator.this) {
   1450             if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
   1451             setShowingLocked(true);
   1452             mStatusBarKeyguardViewManager.verifyUnlock();
   1453             updateActivityLockScreenState();
   1454         }
   1455     }
   1456 
   1457     /**
   1458      * Handle message sent by {@link #notifyScreenOffLocked()}
   1459      * @see #NOTIFY_SCREEN_OFF
   1460      */
   1461     private void handleNotifyScreenOff() {
   1462         synchronized (KeyguardViewMediator.this) {
   1463             if (DEBUG) Log.d(TAG, "handleNotifyScreenOff");
   1464             mStatusBarKeyguardViewManager.onScreenTurnedOff();
   1465         }
   1466     }
   1467 
   1468     /**
   1469      * Handle message sent by {@link #notifyScreenOnLocked}
   1470      * @see #NOTIFY_SCREEN_ON
   1471      */
   1472     private void handleNotifyScreenOn(IKeyguardShowCallback callback) {
   1473         synchronized (KeyguardViewMediator.this) {
   1474             if (DEBUG) Log.d(TAG, "handleNotifyScreenOn");
   1475             mStatusBarKeyguardViewManager.onScreenTurnedOn(callback);
   1476         }
   1477     }
   1478 
   1479     private void resetKeyguardDonePendingLocked() {
   1480         mKeyguardDonePending = false;
   1481         mHandler.removeMessages(KEYGUARD_DONE_PENDING_TIMEOUT);
   1482     }
   1483 
   1484     public void onBootCompleted() {
   1485         mUpdateMonitor.dispatchBootCompleted();
   1486         synchronized (this) {
   1487             mBootCompleted = true;
   1488             if (mBootSendUserPresent) {
   1489                 sendUserPresentBroadcast();
   1490             }
   1491         }
   1492     }
   1493 
   1494     public StatusBarKeyguardViewManager registerStatusBar(PhoneStatusBar phoneStatusBar,
   1495             ViewGroup container, StatusBarWindowManager statusBarWindowManager,
   1496             ScrimController scrimController) {
   1497         mStatusBarKeyguardViewManager.registerStatusBar(phoneStatusBar, container,
   1498                 statusBarWindowManager, scrimController);
   1499         return mStatusBarKeyguardViewManager;
   1500     }
   1501 
   1502     public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
   1503         Message msg = mHandler.obtainMessage(START_KEYGUARD_EXIT_ANIM,
   1504                 new StartKeyguardExitAnimParams(startTime, fadeoutDuration));
   1505         mHandler.sendMessage(msg);
   1506     }
   1507 
   1508     public void onActivityDrawn() {
   1509         mHandler.sendEmptyMessage(ON_ACTIVITY_DRAWN);
   1510     }
   1511     public ViewMediatorCallback getViewMediatorCallback() {
   1512         return mViewMediatorCallback;
   1513     }
   1514 
   1515     private static class StartKeyguardExitAnimParams {
   1516 
   1517         long startTime;
   1518         long fadeoutDuration;
   1519 
   1520         private StartKeyguardExitAnimParams(long startTime, long fadeoutDuration) {
   1521             this.startTime = startTime;
   1522             this.fadeoutDuration = fadeoutDuration;
   1523         }
   1524     }
   1525 
   1526     private void setShowingLocked(boolean showing) {
   1527         if (showing != mShowing) {
   1528             mShowing = showing;
   1529             try {
   1530                 int size = mKeyguardStateCallbacks.size();
   1531                 for (int i = 0; i < size; i++) {
   1532                     mKeyguardStateCallbacks.get(i).onShowingStateChanged(showing);
   1533                 }
   1534             } catch (RemoteException e) {
   1535                 Slog.w(TAG, "Failed to call onShowingStateChanged", e);
   1536             }
   1537             updateInputRestrictedLocked();
   1538             mTrustManager.reportKeyguardShowingChanged();
   1539         }
   1540     }
   1541 
   1542     public void addStateMonitorCallback(IKeyguardStateCallback callback) {
   1543         synchronized (this) {
   1544             mKeyguardStateCallbacks.add(callback);
   1545             try {
   1546                 callback.onSimSecureStateChanged(mUpdateMonitor.isSimPinSecure());
   1547                 callback.onShowingStateChanged(mShowing);
   1548             } catch (RemoteException e) {
   1549                 Slog.w(TAG, "Failed to call onShowingStateChanged or onSimSecureStateChanged", e);
   1550             }
   1551         }
   1552     }
   1553 }
   1554