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