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