FileDocCategorySizeDatePackage
KeyguardViewMediator.javaAPI DocAndroid 5.1 API60374Thu Mar 12 22:22:42 GMT 2015com.android.systemui.keyguard

KeyguardViewMediator

public class KeyguardViewMediator extends com.android.systemui.SystemUI
Mediates requests related to the keyguard. This includes queries about the state of the keyguard, power management events that effect whether the keyguard should be shown or reset, callbacks to the phone window manager to notify it of when the keyguard is showing, and events from the keyguard view itself stating that the keyguard was succesfully unlocked. Note that the keyguard view is shown when the screen is off (as appropriate) so that once the screen comes on, it will be ready immediately. Example queries about the keyguard: - is {movement, key} one that should wake the keygaurd? - is the keyguard showing? - are input events restricted due to the state of the keyguard? Callbacks to the phone window manager: - the keyguard is showing Example external events that translate to keyguard view changes: - screen turned off -> reset the keyguard, and show it so it will be ready next time the screen turns on - keyboard is slid open -> if the keyguard is not secure, hide it Events from the keyguard view: - user succesfully unlocked keyguard -> hide keyguard view, and no longer restrict input events. Note: in addition to normal power managment events that effect the state of whether the keyguard should be showing, external apps and services may request that the keyguard be disabled via {@link #setKeyguardEnabled(boolean)}. When false, this will override all other conditions for turning on the keyguard. Threading and synchronization: This class is created by the initialization routine of the {@link android.view.WindowManagerPolicy}, and runs on its thread. The keyguard UI is created from that thread in the constructor of this class. The apis may be called from other threads, including the {@link com.android.server.input.InputManagerService}'s and {@link android.view.WindowManager}'s. Therefore, methods on this class are synchronized, and any action that is pointed directly to the keyguard UI is posted to a {@link android.os.Handler} to ensure it is taken on the UI thread of the keyguard.

Fields Summary
private static final int
KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT
private static final long
KEYGUARD_DONE_PENDING_TIMEOUT_MS
private static final boolean
DEBUG
private static final boolean
DEBUG_SIM_STATES
private static final boolean
DBG_WAKE
private static final String
TAG
private static final String
DELAYED_KEYGUARD_ACTION
private static final int
SHOW
private static final int
HIDE
private static final int
RESET
private static final int
VERIFY_UNLOCK
private static final int
NOTIFY_SCREEN_OFF
private static final int
NOTIFY_SCREEN_ON
private static final int
KEYGUARD_DONE
private static final int
KEYGUARD_DONE_DRAWING
private static final int
KEYGUARD_DONE_AUTHENTICATING
private static final int
SET_OCCLUDED
private static final int
KEYGUARD_TIMEOUT
private static final int
DISMISS
private static final int
START_KEYGUARD_EXIT_ANIM
private static final int
ON_ACTIVITY_DRAWN
private static final int
KEYGUARD_DONE_PENDING_TIMEOUT
public static final int
AWAKE_INTERVAL_DEFAULT_MS
The default amount of time we stay awake (used for all key input)
private static final int
KEYGUARD_LOCK_AFTER_DELAY_DEFAULT
How long to wait after the screen turns off due to timeout before turning on the keyguard (i.e, the user has this much time to turn the screen back on without having to face the keyguard).
private static final int
KEYGUARD_DONE_DRAWING_TIMEOUT_MS
How long we'll wait for the {@link ViewMediatorCallback#keyguardDoneDrawing()} callback before unblocking a call to {@link #setKeyguardEnabled(boolean)} that is reenabling the keyguard.
private static final String
KEYGUARD_ANALYTICS_SETTING
Secure setting whether analytics are collected on the keyguard.
private int
mMasterStreamType
The stream type that the lock sounds are tied to.
private android.app.AlarmManager
mAlarmManager
private android.media.AudioManager
mAudioManager
private android.app.StatusBarManager
mStatusBarManager
private boolean
mSwitchingUser
private boolean
mSystemReady
private boolean
mBootCompleted
private boolean
mBootSendUserPresent
private boolean
mSuppressNextLockSound
private android.os.PowerManager
mPM
High level access to the power manager for WakeLocks
private android.view.IWindowManager
mWM
High level access to the window manager for dismissing keyguard animation
private android.app.trust.TrustManager
mTrustManager
TrustManager for letting it know when we change visibility
private android.app.SearchManager
mSearchManager
SearchManager for determining whether or not search assistant is available
private PowerManager.WakeLock
mShowKeyguardWakeLock
Used to keep the device awake while to ensure the keyguard finishes opening before we sleep.
private com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager
mStatusBarKeyguardViewManager
private boolean
mExternallyEnabled
External apps (like the phone app) can tell us to disable the keygaurd.
private boolean
mNeedToReshowWhenReenabled
Remember if an external call to {@link #setKeyguardEnabled} with value false caused us to hide the keyguard, so that we need to reshow it once the keygaurd is reenabled with another call with value true.
private boolean
mShowing
private boolean
mInputRestricted
Cached value of #isInputRestricted
private boolean
mOccluded
private int
mDelayedShowingSequence
Helps remember whether the screen has turned on since the last time it turned off due to timeout. see {@link #onScreenTurnedOff(int)}
private com.android.internal.policy.IKeyguardExitCallback
mExitSecureCallback
If the user has disabled the keyguard, then requests to exit, this is how we'll ultimately let them know whether it was successful. We use this var being non-null as an indicator that there is an in progress request.
private com.android.keyguard.KeyguardUpdateMonitor
mUpdateMonitor
private boolean
mScreenOn
private String
mPhoneState
private boolean
mHiding
Whether a hide is pending an we are just waiting for #startKeyguardExitAnimation to be called.
private static final android.content.Intent
USER_PRESENT_INTENT
we send this intent when the keyguard is dismissed.
private boolean
mWaitingUntilKeyguardVisible
{@link #setKeyguardEnabled} waits on this condition when it reenables the keyguard.
private com.android.internal.widget.LockPatternUtils
mLockPatternUtils
private boolean
mKeyguardDonePending
private boolean
mHideAnimationRun
private android.media.SoundPool
mLockSounds
private int
mLockSoundId
private int
mUnlockSoundId
private int
mTrustedSoundId
private int
mLockSoundStreamId
private android.view.animation.Animation
mHideAnimation
The animation used for hiding keyguard. This is used to fetch the animation timings if WindowManager is not providing us with them.
private float
mLockSoundVolume
The volume applied to the lock/unlock sounds.
private com.android.keyguard.KeyguardDisplayManager
mKeyguardDisplayManager
For managing external displays
private final ArrayList
mKeyguardStateCallbacks
com.android.keyguard.KeyguardUpdateMonitorCallback
mUpdateCallback
com.android.keyguard.ViewMediatorCallback
mViewMediatorCallback
private final android.content.BroadcastReceiver
mBroadcastReceiver
private android.os.Handler
mHandler
This handler will be associated with the policy thread, which will also be the UI thread of the keyguard. Since the apis of the policy, and therefore this class, can be called by other threads, any action that directly interacts with the keyguard ui should be posted to this handler, rather than called directly.
private final Runnable
mKeyguardGoingAwayRunnable
Constructors Summary
Methods Summary
public voidaddStateMonitorCallback(com.android.internal.policy.IKeyguardStateCallback callback)

        synchronized (this) {
            mKeyguardStateCallbacks.add(callback);
            try {
                callback.onSimSecureStateChanged(mUpdateMonitor.isSimPinSecure());
                callback.onShowingStateChanged(mShowing);
            } catch (RemoteException e) {
                Slog.w(TAG, "Failed to call onShowingStateChanged or onSimSecureStateChanged", e);
            }
        }
    
private voidadjustStatusBarLocked()

        if (mStatusBarManager == null) {
            mStatusBarManager = (StatusBarManager)
                    mContext.getSystemService(Context.STATUS_BAR_SERVICE);
        }
        if (mStatusBarManager == null) {
            Log.w(TAG, "Could not get status bar manager");
        } else {
            // Disable aspects of the system/status/navigation bars that must not be re-enabled by
            // windows that appear on top, ever
            int flags = StatusBarManager.DISABLE_NONE;
            if (mShowing) {
                // Permanently disable components not available when keyguard is enabled
                // (like recents). Temporary enable/disable (e.g. the "back" button) are
                // done in KeyguardHostView.
                flags |= StatusBarManager.DISABLE_RECENT;
                flags |= StatusBarManager.DISABLE_SEARCH;
            }
            if (isShowingAndNotOccluded()) {
                flags |= StatusBarManager.DISABLE_HOME;
            }

            if (DEBUG) {
                Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mOccluded=" + mOccluded
                        + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
            }

            if (!(mContext instanceof Activity)) {
                mStatusBarManager.disable(flags);
            }
        }
    
private voidcancelDoKeyguardLaterLocked()

        mDelayedShowingSequence++;
    
public voiddismiss()

        mHandler.sendEmptyMessage(DISMISS);
    
private voiddoKeyguardLaterLocked()

        // if the screen turned off because of timeout or the user hit the power button
        // and we don't need to lock immediately, set an alarm
        // to enable it a little bit later (i.e, give the user a chance
        // to turn the screen back on within a certain window without
        // having to unlock the screen)
        final ContentResolver cr = mContext.getContentResolver();

        // From DisplaySettings
        long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
                KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);

        // From SecuritySettings
        final long lockAfterTimeout = Settings.Secure.getInt(cr,
                Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
                KEYGUARD_LOCK_AFTER_DELAY_DEFAULT);

        // From DevicePolicyAdmin
        final long policyTimeout = mLockPatternUtils.getDevicePolicyManager()
                .getMaximumTimeToLock(null, mLockPatternUtils.getCurrentUser());

        long timeout;
        if (policyTimeout > 0) {
            // policy in effect. Make sure we don't go beyond policy limit.
            displayTimeout = Math.max(displayTimeout, 0); // ignore negative values
            timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);
        } else {
            timeout = lockAfterTimeout;
        }

        if (timeout <= 0) {
            // Lock now
            mSuppressNextLockSound = true;
            doKeyguardLocked(null);
        } else {
            // Lock in the future
            long when = SystemClock.elapsedRealtime() + timeout;
            Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
            intent.putExtra("seq", mDelayedShowingSequence);
            PendingIntent sender = PendingIntent.getBroadcast(mContext,
                    0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender);
            if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = "
                             + mDelayedShowingSequence);
        }
    
private voiddoKeyguardLocked(android.os.Bundle options)
Enable the keyguard if the settings are appropriate.

        // if another app is disabling us, don't show
        if (!mExternallyEnabled) {
            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");

            // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes
            // for an occasional ugly flicker in this situation:
            // 1) receive a call with the screen on (no keyguard) or make a call
            // 2) screen times out
            // 3) user hits key to turn screen back on
            // instead, we reenable the keyguard when we know the screen is off and the call
            // ends (see the broadcast receiver below)
            // TODO: clean this up when we have better support at the window manager level
            // for apps that wish to be on top of the keyguard
            return;
        }

        // if the keyguard is already showing, don't bother
        if (mStatusBarKeyguardViewManager.isShowing()) {
            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
            resetStateLocked();
            return;
        }

        // if the setup wizard hasn't run yet, don't show
        final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim", false);
        final boolean absent = SubscriptionManager.isValidSubscriptionId(
                mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.ABSENT));
        final boolean disabled = SubscriptionManager.isValidSubscriptionId(
                mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.PERM_DISABLED));
        final boolean lockedOrMissing = mUpdateMonitor.isSimPinSecure()
                || ((absent || disabled) && requireSim);

        if (!lockedOrMissing && shouldWaitForProvisioning()) {
            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
                    + " and the sim is not locked or missing");
            return;
        }

        if (mLockPatternUtils.isLockScreenDisabled() && !lockedOrMissing) {
            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
            return;
        }

        if (mLockPatternUtils.checkVoldPassword()) {
            if (DEBUG) Log.d(TAG, "Not showing lock screen since just decrypted");
            // Without this, settings is not enabled until the lock screen first appears
            setShowingLocked(false);
            hideLocked();
            return;
        }

        if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
        showLocked(options);
    
public voiddoKeyguardTimeout(android.os.Bundle options)
Used by PhoneWindowManager to enable the keyguard due to a user activity timeout. This must be safe to call from any thread and with any window manager locks held.

        mHandler.removeMessages(KEYGUARD_TIMEOUT);
        Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
        mHandler.sendMessage(msg);
    
public com.android.keyguard.ViewMediatorCallbackgetViewMediatorCallback()

        return mViewMediatorCallback;
    
public voidhandleDismiss()
Dismiss the keyguard through the security layers.

        if (mShowing && !mOccluded) {
            mStatusBarKeyguardViewManager.dismiss();
        }
    
private voidhandleHide()
Handle message sent by {@link #hideLocked()}

see
#HIDE


                 
       
        synchronized (KeyguardViewMediator.this) {
            if (DEBUG) Log.d(TAG, "handleHide");

            mHiding = true;
            if (mShowing && !mOccluded) {
                if (!mHideAnimationRun) {
                    mStatusBarKeyguardViewManager.startPreHideAnimation(mKeyguardGoingAwayRunnable);
                } else {
                    mKeyguardGoingAwayRunnable.run();
                }
            } else {

                // Don't try to rely on WindowManager - if Keyguard wasn't showing, window
                // manager won't start the exit animation.
                handleStartKeyguardExitAnimation(
                        SystemClock.uptimeMillis() + mHideAnimation.getStartOffset(),
                        mHideAnimation.getDuration());
            }
        }
    
private voidhandleKeyguardDone(boolean authenticated, boolean wakeup)

see
#keyguardDone
see
#KEYGUARD_DONE


             
          
        if (DEBUG) Log.d(TAG, "handleKeyguardDone");
        synchronized (this) {
            resetKeyguardDonePendingLocked();
        }

        if (authenticated) {
            mUpdateMonitor.clearFailedUnlockAttempts();
        }
        mUpdateMonitor.clearFingerprintRecognized();

        if (mExitSecureCallback != null) {
            try {
                mExitSecureCallback.onKeyguardExitResult(authenticated);
            } catch (RemoteException e) {
                Slog.w(TAG, "Failed to call onKeyguardExitResult(" + authenticated + ")", e);
            }

            mExitSecureCallback = null;

            if (authenticated) {
                // after succesfully exiting securely, no need to reshow
                // the keyguard when they've released the lock
                mExternallyEnabled = true;
                mNeedToReshowWhenReenabled = false;
                updateInputRestricted();
            }
        }

        handleHide();
    
private voidhandleKeyguardDoneDrawing()

see
#keyguardDone
see
#KEYGUARD_DONE_DRAWING

        synchronized(this) {
            if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing");
            if (mWaitingUntilKeyguardVisible) {
                if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
                mWaitingUntilKeyguardVisible = false;
                notifyAll();

                // there will usually be two of these sent, one as a timeout, and one
                // as a result of the callback, so remove any remaining messages from
                // the queue
                mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
            }
        }
    
private voidhandleNotifyScreenOff()
Handle message sent by {@link #notifyScreenOffLocked()}

see
#NOTIFY_SCREEN_OFF

        synchronized (KeyguardViewMediator.this) {
            if (DEBUG) Log.d(TAG, "handleNotifyScreenOff");
            mStatusBarKeyguardViewManager.onScreenTurnedOff();
        }
    
private voidhandleNotifyScreenOn(com.android.internal.policy.IKeyguardShowCallback callback)
Handle message sent by {@link #notifyScreenOnLocked}

see
#NOTIFY_SCREEN_ON

        synchronized (KeyguardViewMediator.this) {
            if (DEBUG) Log.d(TAG, "handleNotifyScreenOn");
            mStatusBarKeyguardViewManager.onScreenTurnedOn(callback);
        }
    
private voidhandleOnActivityDrawn()

        if (DEBUG) Log.d(TAG, "handleOnActivityDrawn: mKeyguardDonePending=" + mKeyguardDonePending);
        if (mKeyguardDonePending) {
            mStatusBarKeyguardViewManager.onActivityDrawn();
        }
    
private voidhandleReset()
Handle message sent by {@link #resetStateLocked}

see
#RESET

        synchronized (KeyguardViewMediator.this) {
            if (DEBUG) Log.d(TAG, "handleReset");
            mStatusBarKeyguardViewManager.reset();
        }
    
private voidhandleSetOccluded(boolean isOccluded)
Handles SET_OCCLUDED message sent by setOccluded()

        synchronized (KeyguardViewMediator.this) {
            if (mOccluded != isOccluded) {
                mOccluded = isOccluded;
                mStatusBarKeyguardViewManager.setOccluded(isOccluded);
                updateActivityLockScreenState();
                adjustStatusBarLocked();
            }
        }
    
private voidhandleShow(android.os.Bundle options)
Handle message sent by {@link #showLocked}.

see
#SHOW

        synchronized (KeyguardViewMediator.this) {
            if (!mSystemReady) {
                if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready.");
                return;
            } else {
                if (DEBUG) Log.d(TAG, "handleShow");
            }

            setShowingLocked(true);
            mStatusBarKeyguardViewManager.show(options);
            mHiding = false;
            resetKeyguardDonePendingLocked();
            mHideAnimationRun = false;
            updateActivityLockScreenState();
            adjustStatusBarLocked();
            userActivity();

            // Do this at the end to not slow down display of the keyguard.
            playSounds(true);

            mShowKeyguardWakeLock.release();
        }
        mKeyguardDisplayManager.show();
    
private voidhandleStartKeyguardExitAnimation(long startTime, long fadeoutDuration)

        synchronized (KeyguardViewMediator.this) {

            if (!mHiding) {
                return;
            }
            mHiding = false;

            // only play "unlock" noises if not on a call (since the incall UI
            // disables the keyguard)
            if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
                playSounds(false);
            }

            setShowingLocked(false);
            mStatusBarKeyguardViewManager.hide(startTime, fadeoutDuration);
            resetKeyguardDonePendingLocked();
            mHideAnimationRun = false;
            updateActivityLockScreenState();
            adjustStatusBarLocked();
            sendUserPresentBroadcast();
        }
    
private voidhandleVerifyUnlock()
Handle message sent by {@link #verifyUnlock}

see
#VERIFY_UNLOCK

        synchronized (KeyguardViewMediator.this) {
            if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
            setShowingLocked(true);
            mStatusBarKeyguardViewManager.verifyUnlock();
            updateActivityLockScreenState();
        }
    
private voidhideLocked()
Send message to keyguard telling it to hide itself

see
#handleHide()

        if (DEBUG) Log.d(TAG, "hideLocked");
        Message msg = mHandler.obtainMessage(HIDE);
        mHandler.sendMessage(msg);
    
public booleanisInputRestricted()
Given the state of the keyguard, is the input restricted? Input is restricted when the keyguard is showing, or when the keyguard was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.

        return mShowing || mNeedToReshowWhenReenabled || shouldWaitForProvisioning();
    
public booleanisSecure()

        return mLockPatternUtils.isSecure()
            || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
    
public booleanisShowingAndNotOccluded()
Is the keyguard currently showing and not being force hidden?

        return mShowing && !mOccluded;
    
public voidkeyguardDone(boolean authenticated, boolean wakeup)


          
        if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated + ")");
        EventLog.writeEvent(70000, 2);
        Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0, wakeup ? 1 : 0);
        mHandler.sendMessage(msg);
    
private voidmaybeSendUserPresentBroadcast()

        if (mSystemReady && mLockPatternUtils.isLockScreenDisabled()) {
            // Lock screen is disabled because the user has set the preference to "None".
            // In this case, send out ACTION_USER_PRESENT here instead of in
            // handleKeyguardDone()
            sendUserPresentBroadcast();
        }
    
private voidnotifyScreenOffLocked()
Send a message to keyguard telling it the screen just turned on.

see
#onScreenTurnedOff(int)
see
#handleNotifyScreenOff

        if (DEBUG) Log.d(TAG, "notifyScreenOffLocked");
        mHandler.sendEmptyMessage(NOTIFY_SCREEN_OFF);
    
private voidnotifyScreenOnLocked(com.android.internal.policy.IKeyguardShowCallback result)
Send a message to keyguard telling it the screen just turned on.

see
#onScreenTurnedOn
see
#handleNotifyScreenOn

        if (DEBUG) Log.d(TAG, "notifyScreenOnLocked");
        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_ON, result);
        mHandler.sendMessage(msg);
    
public voidonActivityDrawn()

        mHandler.sendEmptyMessage(ON_ACTIVITY_DRAWN);
    
public voidonBootCompleted()

        mUpdateMonitor.dispatchBootCompleted();
        synchronized (this) {
            mBootCompleted = true;
            if (mBootSendUserPresent) {
                sendUserPresentBroadcast();
            }
        }
    
public voidonDreamingStarted()
A dream started. We should lock after the usual screen-off lock timeout but only if there is a secure lock pattern.

        synchronized (this) {
            if (mScreenOn && mLockPatternUtils.isSecure()) {
                doKeyguardLaterLocked();
            }
        }
    
public voidonDreamingStopped()
A dream stopped.

        synchronized (this) {
            if (mScreenOn) {
                cancelDoKeyguardLaterLocked();
            }
        }
    
public voidonScreenTurnedOff(int why)
Called to let us know the screen was turned off.

param
why either {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_USER} or {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT}.

        synchronized (this) {
            mScreenOn = false;
            if (DEBUG) Log.d(TAG, "onScreenTurnedOff(" + why + ")");

            resetKeyguardDonePendingLocked();
            mHideAnimationRun = false;

            // Lock immediately based on setting if secure (user has a pin/pattern/password).
            // This also "locks" the device when not secure to provide easy access to the
            // camera while preventing unwanted input.
            final boolean lockImmediately =
                mLockPatternUtils.getPowerButtonInstantlyLocks() || !mLockPatternUtils.isSecure();

            notifyScreenOffLocked();

            if (mExitSecureCallback != null) {
                if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
                try {
                    mExitSecureCallback.onKeyguardExitResult(false);
                } catch (RemoteException e) {
                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
                }
                mExitSecureCallback = null;
                if (!mExternallyEnabled) {
                    hideLocked();
                }
            } else if (mShowing) {
                resetStateLocked();
            } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT
                   || (why == WindowManagerPolicy.OFF_BECAUSE_OF_USER && !lockImmediately)) {
                doKeyguardLaterLocked();
            } else {
                doKeyguardLocked(null);
            }
        }
        KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurndOff(why);
    
public voidonScreenTurnedOn(com.android.internal.policy.IKeyguardShowCallback callback)
Let's us know the screen was turned on.

        synchronized (this) {
            mScreenOn = true;
            cancelDoKeyguardLaterLocked();
            if (DEBUG) Log.d(TAG, "onScreenTurnedOn, seq = " + mDelayedShowingSequence);
            if (callback != null) {
                notifyScreenOnLocked(callback);
            }
        }
        KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurnedOn();
        maybeSendUserPresentBroadcast();
    
public voidonSystemReady()
Let us know that the system is ready after startup.

        mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
        synchronized (this) {
            if (DEBUG) Log.d(TAG, "onSystemReady");
            mSystemReady = true;
            mUpdateMonitor.registerCallback(mUpdateCallback);

            // Suppress biometric unlock right after boot until things have settled if it is the
            // selected security method, otherwise unsuppress it.  It must be unsuppressed if it is
            // not the selected security method for the following reason:  if the user starts
            // without a screen lock selected, the biometric unlock would be suppressed the first
            // time they try to use it.
            //
            // Note that the biometric unlock will still not show if it is not the selected method.
            // Calling setAlternateUnlockEnabled(true) simply says don't suppress it if it is the
            // selected method.
            if (mLockPatternUtils.usingBiometricWeak()
                    && mLockPatternUtils.isBiometricWeakInstalled()) {
                if (DEBUG) Log.d(TAG, "suppressing biometric unlock during boot");
                mUpdateMonitor.setAlternateUnlockEnabled(false);
            } else {
                mUpdateMonitor.setAlternateUnlockEnabled(true);
            }

            doKeyguardLocked(null);
        }
        // Most services aren't available until the system reaches the ready state, so we
        // send it here when the device first boots.
        maybeSendUserPresentBroadcast();
    
private voidplaySound(int soundId)

        if (soundId == 0) return;
        final ContentResolver cr = mContext.getContentResolver();
        if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {

            mLockSounds.stop(mLockSoundStreamId);
            // Init mAudioManager
            if (mAudioManager == null) {
                mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
                if (mAudioManager == null) return;
                mMasterStreamType = mAudioManager.getMasterStreamType();
            }
            // If the stream is muted, don't play the sound
            if (mAudioManager.isStreamMute(mMasterStreamType)) return;

            mLockSoundStreamId = mLockSounds.play(soundId,
                    mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
        }
    
private voidplaySounds(boolean locked)

        // User feedback for keyguard.

        if (mSuppressNextLockSound) {
            mSuppressNextLockSound = false;
            return;
        }

        playSound(locked ? mLockSoundId : mUnlockSoundId);
    
private voidplayTrustedSound()

        if (mSuppressNextLockSound) {
            return;
        }
        playSound(mTrustedSoundId);
    
public com.android.systemui.statusbar.phone.StatusBarKeyguardViewManagerregisterStatusBar(com.android.systemui.statusbar.phone.PhoneStatusBar phoneStatusBar, android.view.ViewGroup container, com.android.systemui.statusbar.phone.StatusBarWindowManager statusBarWindowManager, com.android.systemui.statusbar.phone.ScrimController scrimController)

        mStatusBarKeyguardViewManager.registerStatusBar(phoneStatusBar, container,
                statusBarWindowManager, scrimController);
        return mStatusBarKeyguardViewManager;
    
private voidresetKeyguardDonePendingLocked()

        mKeyguardDonePending = false;
        mHandler.removeMessages(KEYGUARD_DONE_PENDING_TIMEOUT);
    
private voidresetStateLocked()
Send message to keyguard telling it to reset its state.

see
#handleReset

        if (DEBUG) Log.e(TAG, "resetStateLocked");
        Message msg = mHandler.obtainMessage(RESET);
        mHandler.sendMessage(msg);
    
private voidsendUserPresentBroadcast()

        synchronized (this) {
            if (mBootCompleted) {
                final UserHandle currentUser = new UserHandle(mLockPatternUtils.getCurrentUser());
                final UserManager um = (UserManager) mContext.getSystemService(
                        Context.USER_SERVICE);
                List <UserInfo> userHandles = um.getProfiles(currentUser.getIdentifier());
                for (UserInfo ui : userHandles) {
                    mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, ui.getUserHandle());
                }
            } else {
                mBootSendUserPresent = true;
            }
        }
    
public voidsetCurrentUser(int newUserId)
Update the newUserId. Call while holding WindowManagerService lock. NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.

param
newUserId The id of the incoming user.

        mLockPatternUtils.setCurrentUser(newUserId);
    
public voidsetKeyguardEnabled(boolean enabled)
Same semantics as {@link android.view.WindowManagerPolicy#enableKeyguard}; provide a way for external stuff to override normal keyguard behavior. For instance the phone app disables the keyguard when it receives incoming calls.

        synchronized (this) {
            if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");

            mExternallyEnabled = enabled;

            if (!enabled && mShowing) {
                if (mExitSecureCallback != null) {
                    if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
                    // we're in the process of handling a request to verify the user
                    // can get past the keyguard. ignore extraneous requests to disable / reenable
                    return;
                }

                // hiding keyguard that is showing, remember to reshow later
                if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
                        + "disabling status bar expansion");
                mNeedToReshowWhenReenabled = true;
                updateInputRestrictedLocked();
                hideLocked();
            } else if (enabled && mNeedToReshowWhenReenabled) {
                // reenabled after previously hidden, reshow
                if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
                        + "status bar expansion");
                mNeedToReshowWhenReenabled = false;
                updateInputRestrictedLocked();

                if (mExitSecureCallback != null) {
                    if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
                    try {
                        mExitSecureCallback.onKeyguardExitResult(false);
                    } catch (RemoteException e) {
                        Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
                    }
                    mExitSecureCallback = null;
                    resetStateLocked();
                } else {
                    showLocked(null);

                    // block until we know the keygaurd is done drawing (and post a message
                    // to unblock us after a timeout so we don't risk blocking too long
                    // and causing an ANR).
                    mWaitingUntilKeyguardVisible = true;
                    mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
                    if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
                    while (mWaitingUntilKeyguardVisible) {
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                    if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
                }
            }
        }
    
public voidsetOccluded(boolean isOccluded)
Notify us when the keyguard is occluded by another window

        if (DEBUG) Log.d(TAG, "setOccluded " + isOccluded);
        mHandler.removeMessages(SET_OCCLUDED);
        Message msg = mHandler.obtainMessage(SET_OCCLUDED, (isOccluded ? 1 : 0), 0);
        mHandler.sendMessage(msg);
    
private voidsetShowingLocked(boolean showing)

        if (showing != mShowing) {
            mShowing = showing;
            try {
                int size = mKeyguardStateCallbacks.size();
                for (int i = 0; i < size; i++) {
                    mKeyguardStateCallbacks.get(i).onShowingStateChanged(showing);
                }
            } catch (RemoteException e) {
                Slog.w(TAG, "Failed to call onShowingStateChanged", e);
            }
            updateInputRestrictedLocked();
            mTrustManager.reportKeyguardShowingChanged();
        }
    
private voidsetupLocked()

        mPM = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        mWM = WindowManagerGlobal.getWindowManagerService();
        mTrustManager = (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);

        mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "show keyguard");
        mShowKeyguardWakeLock.setReferenceCounted(false);

        mContext.registerReceiver(mBroadcastReceiver, new IntentFilter(DELAYED_KEYGUARD_ACTION));

        mKeyguardDisplayManager = new KeyguardDisplayManager(mContext);

        mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);

        mUpdateMonitor = KeyguardUpdateMonitor.getInstance(mContext);

        mLockPatternUtils = new LockPatternUtils(mContext);
        mLockPatternUtils.setCurrentUser(ActivityManager.getCurrentUser());

        // Assume keyguard is showing (unless it's disabled) until we know for sure...
        setShowingLocked(!shouldWaitForProvisioning() && !mLockPatternUtils.isLockScreenDisabled());
        mTrustManager.reportKeyguardShowingChanged();

        mStatusBarKeyguardViewManager = new StatusBarKeyguardViewManager(mContext,
                mViewMediatorCallback, mLockPatternUtils);
        final ContentResolver cr = mContext.getContentResolver();

        mScreenOn = mPM.isScreenOn();

        mLockSounds = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
        String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND);
        if (soundPath != null) {
            mLockSoundId = mLockSounds.load(soundPath, 1);
        }
        if (soundPath == null || mLockSoundId == 0) {
            Log.w(TAG, "failed to load lock sound from " + soundPath);
        }
        soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND);
        if (soundPath != null) {
            mUnlockSoundId = mLockSounds.load(soundPath, 1);
        }
        if (soundPath == null || mUnlockSoundId == 0) {
            Log.w(TAG, "failed to load unlock sound from " + soundPath);
        }
        soundPath = Settings.Global.getString(cr, Settings.Global.TRUSTED_SOUND);
        if (soundPath != null) {
            mTrustedSoundId = mLockSounds.load(soundPath, 1);
        }
        if (soundPath == null || mTrustedSoundId == 0) {
            Log.w(TAG, "failed to load trusted sound from " + soundPath);
        }

        int lockSoundDefaultAttenuation = mContext.getResources().getInteger(
                com.android.internal.R.integer.config_lockSoundVolumeDb);
        mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20);

        mHideAnimation = AnimationUtils.loadAnimation(mContext,
                com.android.internal.R.anim.lock_screen_behind_enter);
    
private booleanshouldWaitForProvisioning()

        return !mUpdateMonitor.isDeviceProvisioned() && !isSecure();
    
private voidshowLocked(android.os.Bundle options)
Send message to keyguard telling it to show itself

see
#handleShow

        if (DEBUG) Log.d(TAG, "showLocked");
        // ensure we stay awake until we are finished displaying the keyguard
        mShowKeyguardWakeLock.acquire();
        Message msg = mHandler.obtainMessage(SHOW, options);
        mHandler.sendMessage(msg);
    
public voidstart()

        synchronized (this) {
            setupLocked();
        }
        putComponent(KeyguardViewMediator.class, this);
    
public voidstartKeyguardExitAnimation(long startTime, long fadeoutDuration)

        Message msg = mHandler.obtainMessage(START_KEYGUARD_EXIT_ANIM,
                new StartKeyguardExitAnimParams(startTime, fadeoutDuration));
        mHandler.sendMessage(msg);
    
private voidupdateActivityLockScreenState()

        try {
            ActivityManagerNative.getDefault().setLockScreenShown(mShowing && !mOccluded);
        } catch (RemoteException e) {
        }
    
private voidupdateInputRestricted()

        synchronized (this) {
            updateInputRestrictedLocked();
        }
    
private voidupdateInputRestrictedLocked()

        boolean inputRestricted = isInputRestricted();
        if (mInputRestricted != inputRestricted) {
            mInputRestricted = inputRestricted;
            try {
                int size = mKeyguardStateCallbacks.size();
                for (int i = 0; i < size; i++) {
                    mKeyguardStateCallbacks.get(i).onInputRestrictedStateChanged(inputRestricted);
                }
            } catch (RemoteException e) {
                Slog.w(TAG, "Failed to call onDeviceProvisioned", e);
            }
        }
    
public voiduserActivity()


       
        mPM.userActivity(SystemClock.uptimeMillis(), false);
    
public voidverifyUnlock(com.android.internal.policy.IKeyguardExitCallback callback)

see
android.app.KeyguardManager#exitKeyguardSecurely

        synchronized (this) {
            if (DEBUG) Log.d(TAG, "verifyUnlock");
            if (shouldWaitForProvisioning()) {
                // don't allow this api when the device isn't provisioned
                if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
                try {
                    callback.onKeyguardExitResult(false);
                } catch (RemoteException e) {
                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
                }
            } else if (mExternallyEnabled) {
                // this only applies when the user has externally disabled the
                // keyguard.  this is unexpected and means the user is not
                // using the api properly.
                Log.w(TAG, "verifyUnlock called when not externally disabled");
                try {
                    callback.onKeyguardExitResult(false);
                } catch (RemoteException e) {
                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
                }
            } else if (mExitSecureCallback != null) {
                // already in progress with someone else
                try {
                    callback.onKeyguardExitResult(false);
                } catch (RemoteException e) {
                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
                }
            } else {
                mExitSecureCallback = callback;
                verifyUnlockLocked();
            }
        }
    
private voidverifyUnlockLocked()
Send message to keyguard telling it to verify unlock

see
#handleVerifyUnlock()

        if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
        mHandler.sendEmptyMessage(VERIFY_UNLOCK);