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