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