KeyguardViewMediator.java revision caf24fc2c4bb9747eb80138bf3ce0be067851749
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.MotionEvent;
53import android.view.WindowManager;
54import android.view.WindowManagerPolicy;
55
56import com.android.internal.telephony.IccCardConstants;
57import com.android.internal.widget.LockPatternUtils;
58
59
60/**
61 * Mediates requests related to the keyguard.  This includes queries about the
62 * state of the keyguard, power management events that effect whether the keyguard
63 * should be shown or reset, callbacks to the phone window manager to notify
64 * it of when the keyguard is showing, and events from the keyguard view itself
65 * stating that the keyguard was succesfully unlocked.
66 *
67 * Note that the keyguard view is shown when the screen is off (as appropriate)
68 * so that once the screen comes on, it will be ready immediately.
69 *
70 * Example queries about the keyguard:
71 * - is {movement, key} one that should wake the keygaurd?
72 * - is the keyguard showing?
73 * - are input events restricted due to the state of the keyguard?
74 *
75 * Callbacks to the phone window manager:
76 * - the keyguard is showing
77 *
78 * Example external events that translate to keyguard view changes:
79 * - screen turned off -> reset the keyguard, and show it so it will be ready
80 *   next time the screen turns on
81 * - keyboard is slid open -> if the keyguard is not secure, hide it
82 *
83 * Events from the keyguard view:
84 * - user succesfully unlocked keyguard -> hide keyguard view, and no longer
85 *   restrict input events.
86 *
87 * Note: in addition to normal power managment events that effect the state of
88 * whether the keyguard should be showing, external apps and services may request
89 * that the keyguard be disabled via {@link #setKeyguardEnabled(boolean)}.  When
90 * false, this will override all other conditions for turning on the keyguard.
91 *
92 * Threading and synchronization:
93 * This class is created by the initialization routine of the {@link WindowManagerPolicy},
94 * and runs on its thread.  The keyguard UI is created from that thread in the
95 * constructor of this class.  The apis may be called from other threads, including the
96 * {@link com.android.server.input.InputManagerService}'s and {@link android.view.WindowManager}'s.
97 * Therefore, methods on this class are synchronized, and any action that is pointed
98 * directly to the keyguard UI is posted to a {@link Handler} to ensure it is taken on the UI
99 * thread of the keyguard.
100 */
101public class KeyguardViewMediator {
102    private static final int KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000;
103    final static boolean DEBUG = false;
104    private final static boolean DBG_WAKE = false;
105
106    private final static String TAG = "KeyguardViewMediator";
107
108    private static final String DELAYED_KEYGUARD_ACTION =
109        "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_KEYGUARD";
110
111    // used for handler messages
112    private static final int SHOW = 2;
113    private static final int HIDE = 3;
114    private static final int RESET = 4;
115    private static final int VERIFY_UNLOCK = 5;
116    private static final int NOTIFY_SCREEN_OFF = 6;
117    private static final int NOTIFY_SCREEN_ON = 7;
118    private static final int KEYGUARD_DONE = 9;
119    private static final int KEYGUARD_DONE_DRAWING = 10;
120    private static final int KEYGUARD_DONE_AUTHENTICATING = 11;
121    private static final int SET_HIDDEN = 12;
122    private static final int KEYGUARD_TIMEOUT = 13;
123    private static final int SHOW_ASSISTANT = 14;
124    private static final int DISPATCH_EVENT = 15;
125
126    /**
127     * The default amount of time we stay awake (used for all key input)
128     */
129    protected static final int AWAKE_INTERVAL_DEFAULT_MS = 10000;
130
131    /**
132     * How long to wait after the screen turns off due to timeout before
133     * turning on the keyguard (i.e, the user has this much time to turn
134     * the screen back on without having to face the keyguard).
135     */
136    private static final int KEYGUARD_LOCK_AFTER_DELAY_DEFAULT = 5000;
137
138    /**
139     * How long we'll wait for the {@link ViewMediatorCallback#keyguardDoneDrawing()}
140     * callback before unblocking a call to {@link #setKeyguardEnabled(boolean)}
141     * that is reenabling the keyguard.
142     */
143    private static final int KEYGUARD_DONE_DRAWING_TIMEOUT_MS = 2000;
144
145    /**
146     * Allow the user to expand the status bar when the keyguard is engaged
147     * (without a pattern or password).
148     */
149    private static final boolean ENABLE_INSECURE_STATUS_BAR_EXPAND = true;
150
151    /** The stream type that the lock sounds are tied to. */
152    private int mMasterStreamType;
153
154    private Context mContext;
155    private AlarmManager mAlarmManager;
156    private AudioManager mAudioManager;
157    private StatusBarManager mStatusBarManager;
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
498        mScreenOn = mPM.isScreenOn();
499
500        mLockSounds = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
501        String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND);
502        if (soundPath != null) {
503            mLockSoundId = mLockSounds.load(soundPath, 1);
504        }
505        if (soundPath == null || mLockSoundId == 0) {
506            Log.w(TAG, "failed to load lock sound from " + soundPath);
507        }
508        soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND);
509        if (soundPath != null) {
510            mUnlockSoundId = mLockSounds.load(soundPath, 1);
511        }
512        if (soundPath == null || mUnlockSoundId == 0) {
513            Log.w(TAG, "failed to load unlock sound from " + soundPath);
514        }
515        int lockSoundDefaultAttenuation = context.getResources().getInteger(
516                com.android.internal.R.integer.config_lockSoundVolumeDb);
517        mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20);
518    }
519
520    /**
521     * Let us know that the system is ready after startup.
522     */
523    public void onSystemReady() {
524        mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
525        synchronized (this) {
526            if (DEBUG) Log.d(TAG, "onSystemReady");
527            mSystemReady = true;
528            mUpdateMonitor.registerCallback(mUpdateCallback);
529
530            // Suppress biometric unlock right after boot until things have settled if it is the
531            // selected security method, otherwise unsuppress it.  It must be unsuppressed if it is
532            // not the selected security method for the following reason:  if the user starts
533            // without a screen lock selected, the biometric unlock would be suppressed the first
534            // time they try to use it.
535            //
536            // Note that the biometric unlock will still not show if it is not the selected method.
537            // Calling setAlternateUnlockEnabled(true) simply says don't suppress it if it is the
538            // selected method.
539            if (mLockPatternUtils.usingBiometricWeak()
540                    && mLockPatternUtils.isBiometricWeakInstalled()) {
541                if (DEBUG) Log.d(TAG, "suppressing biometric unlock during boot");
542                mUpdateMonitor.setAlternateUnlockEnabled(false);
543            } else {
544                mUpdateMonitor.setAlternateUnlockEnabled(true);
545            }
546
547            doKeyguardLocked(null);
548        }
549        // Most services aren't available until the system reaches the ready state, so we
550        // send it here when the device first boots.
551        maybeSendUserPresentBroadcast();
552    }
553
554    /**
555     * Called to let us know the screen was turned off.
556     * @param why either {@link WindowManagerPolicy#OFF_BECAUSE_OF_USER},
557     *   {@link WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT} or
558     *   {@link WindowManagerPolicy#OFF_BECAUSE_OF_PROX_SENSOR}.
559     */
560    public void onScreenTurnedOff(int why) {
561        synchronized (this) {
562            mScreenOn = false;
563            if (DEBUG) Log.d(TAG, "onScreenTurnedOff(" + why + ")");
564
565            mKeyguardDonePending = false;
566
567            // Lock immediately based on setting if secure (user has a pin/pattern/password).
568            // This also "locks" the device when not secure to provide easy access to the
569            // camera while preventing unwanted input.
570            final boolean lockImmediately =
571                mLockPatternUtils.getPowerButtonInstantlyLocks() || !mLockPatternUtils.isSecure();
572
573            if (mExitSecureCallback != null) {
574                if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
575                try {
576                    mExitSecureCallback.onKeyguardExitResult(false);
577                } catch (RemoteException e) {
578                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
579                }
580                mExitSecureCallback = null;
581                if (!mExternallyEnabled) {
582                    hideLocked();
583                }
584            } else if (mShowing) {
585                notifyScreenOffLocked();
586                resetStateLocked(null);
587            } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT
588                   || (why == WindowManagerPolicy.OFF_BECAUSE_OF_USER && !lockImmediately)) {
589                doKeyguardLaterLocked();
590            } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
591                // Do not enable the keyguard if the prox sensor forced the screen off.
592            } else {
593                doKeyguardLocked(null);
594            }
595        }
596    }
597
598    private void doKeyguardLaterLocked() {
599        // if the screen turned off because of timeout or the user hit the power button
600        // and we don't need to lock immediately, set an alarm
601        // to enable it a little bit later (i.e, give the user a chance
602        // to turn the screen back on within a certain window without
603        // having to unlock the screen)
604        final ContentResolver cr = mContext.getContentResolver();
605
606        // From DisplaySettings
607        long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
608                KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);
609
610        // From SecuritySettings
611        final long lockAfterTimeout = Settings.Secure.getInt(cr,
612                Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
613                KEYGUARD_LOCK_AFTER_DELAY_DEFAULT);
614
615        // From DevicePolicyAdmin
616        final long policyTimeout = mLockPatternUtils.getDevicePolicyManager()
617                .getMaximumTimeToLock(null, mLockPatternUtils.getCurrentUser());
618
619        long timeout;
620        if (policyTimeout > 0) {
621            // policy in effect. Make sure we don't go beyond policy limit.
622            displayTimeout = Math.max(displayTimeout, 0); // ignore negative values
623            timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);
624        } else {
625            timeout = lockAfterTimeout;
626        }
627
628        if (timeout <= 0) {
629            // Lock now
630            mSuppressNextLockSound = true;
631            doKeyguardLocked(null);
632        } else {
633            // Lock in the future
634            long when = SystemClock.elapsedRealtime() + timeout;
635            Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
636            intent.putExtra("seq", mDelayedShowingSequence);
637            PendingIntent sender = PendingIntent.getBroadcast(mContext,
638                    0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
639            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender);
640            if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = "
641                             + mDelayedShowingSequence);
642        }
643    }
644
645    private void cancelDoKeyguardLaterLocked() {
646        mDelayedShowingSequence++;
647    }
648
649    /**
650     * Let's us know the screen was turned on.
651     */
652    public void onScreenTurnedOn(IKeyguardShowCallback callback) {
653        synchronized (this) {
654            mScreenOn = true;
655            cancelDoKeyguardLaterLocked();
656            if (DEBUG) Log.d(TAG, "onScreenTurnedOn, seq = " + mDelayedShowingSequence);
657            if (callback != null) {
658                notifyScreenOnLocked(callback);
659            }
660        }
661        maybeSendUserPresentBroadcast();
662    }
663
664    private void maybeSendUserPresentBroadcast() {
665        if (mSystemReady && mLockPatternUtils.isLockScreenDisabled()
666                && mUserManager.getUsers(true).size() == 1) {
667            // Lock screen is disabled because the user has set the preference to "None".
668            // In this case, send out ACTION_USER_PRESENT here instead of in
669            // handleKeyguardDone()
670            sendUserPresentBroadcast();
671        }
672    }
673
674    /**
675     * A dream started.  We should lock after the usual screen-off lock timeout but only
676     * if there is a secure lock pattern.
677     */
678    public void onDreamingStarted() {
679        synchronized (this) {
680            if (mScreenOn && mLockPatternUtils.isSecure()) {
681                doKeyguardLaterLocked();
682            }
683        }
684    }
685
686    /**
687     * A dream stopped.
688     */
689    public void onDreamingStopped() {
690        synchronized (this) {
691            if (mScreenOn) {
692                cancelDoKeyguardLaterLocked();
693            }
694        }
695    }
696
697    /**
698     * Same semantics as {@link WindowManagerPolicy#enableKeyguard}; provide
699     * a way for external stuff to override normal keyguard behavior.  For instance
700     * the phone app disables the keyguard when it receives incoming calls.
701     */
702    public void setKeyguardEnabled(boolean enabled) {
703        synchronized (this) {
704            if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
705
706            mExternallyEnabled = enabled;
707
708            if (!enabled && mShowing) {
709                if (mExitSecureCallback != null) {
710                    if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
711                    // we're in the process of handling a request to verify the user
712                    // can get past the keyguard. ignore extraneous requests to disable / reenable
713                    return;
714                }
715
716                // hiding keyguard that is showing, remember to reshow later
717                if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
718                        + "disabling status bar expansion");
719                mNeedToReshowWhenReenabled = true;
720                hideLocked();
721            } else if (enabled && mNeedToReshowWhenReenabled) {
722                // reenabled after previously hidden, reshow
723                if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
724                        + "status bar expansion");
725                mNeedToReshowWhenReenabled = false;
726
727                if (mExitSecureCallback != null) {
728                    if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
729                    try {
730                        mExitSecureCallback.onKeyguardExitResult(false);
731                    } catch (RemoteException e) {
732                        Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
733                    }
734                    mExitSecureCallback = null;
735                    resetStateLocked(null);
736                } else {
737                    showLocked(null);
738
739                    // block until we know the keygaurd is done drawing (and post a message
740                    // to unblock us after a timeout so we don't risk blocking too long
741                    // and causing an ANR).
742                    mWaitingUntilKeyguardVisible = true;
743                    mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
744                    if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
745                    while (mWaitingUntilKeyguardVisible) {
746                        try {
747                            wait();
748                        } catch (InterruptedException e) {
749                            Thread.currentThread().interrupt();
750                        }
751                    }
752                    if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
753                }
754            }
755        }
756    }
757
758    /**
759     * @see android.app.KeyguardManager#exitKeyguardSecurely
760     */
761    public void verifyUnlock(IKeyguardExitCallback callback) {
762        synchronized (this) {
763            if (DEBUG) Log.d(TAG, "verifyUnlock");
764            if (!mUpdateMonitor.isDeviceProvisioned()) {
765                // don't allow this api when the device isn't provisioned
766                if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
767                try {
768                    callback.onKeyguardExitResult(false);
769                } catch (RemoteException e) {
770                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
771                }
772            } else if (mExternallyEnabled) {
773                // this only applies when the user has externally disabled the
774                // keyguard.  this is unexpected and means the user is not
775                // using the api properly.
776                Log.w(TAG, "verifyUnlock called when not externally disabled");
777                try {
778                    callback.onKeyguardExitResult(false);
779                } catch (RemoteException e) {
780                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
781                }
782            } else if (mExitSecureCallback != null) {
783                // already in progress with someone else
784                try {
785                    callback.onKeyguardExitResult(false);
786                } catch (RemoteException e) {
787                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
788                }
789            } else {
790                mExitSecureCallback = callback;
791                verifyUnlockLocked();
792            }
793        }
794    }
795
796    /**
797     * Is the keyguard currently showing?
798     */
799    public boolean isShowing() {
800        return mShowing;
801    }
802
803    /**
804     * Is the keyguard currently showing and not being force hidden?
805     */
806    public boolean isShowingAndNotHidden() {
807        return mShowing && !mHidden;
808    }
809
810    /**
811     * Notify us when the keyguard is hidden by another window
812     */
813    public void setHidden(boolean isHidden) {
814        if (DEBUG) Log.d(TAG, "setHidden " + isHidden);
815        mUpdateMonitor.sendKeyguardVisibilityChanged(!isHidden);
816        mHandler.removeMessages(SET_HIDDEN);
817        Message msg = mHandler.obtainMessage(SET_HIDDEN, (isHidden ? 1 : 0), 0);
818        mHandler.sendMessage(msg);
819    }
820
821    /**
822     * Handles SET_HIDDEN message sent by setHidden()
823     */
824    private void handleSetHidden(boolean isHidden) {
825        synchronized (KeyguardViewMediator.this) {
826            if (mHidden != isHidden) {
827                mHidden = isHidden;
828                updateActivityLockScreenState();
829                adjustStatusBarLocked();
830            }
831        }
832    }
833
834    /**
835     * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout.
836     * This must be safe to call from any thread and with any window manager locks held.
837     */
838    public void doKeyguardTimeout(Bundle options) {
839        mHandler.removeMessages(KEYGUARD_TIMEOUT);
840        Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
841        mHandler.sendMessage(msg);
842    }
843
844    /**
845     * Given the state of the keyguard, is the input restricted?
846     * Input is restricted when the keyguard is showing, or when the keyguard
847     * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.
848     */
849    public boolean isInputRestricted() {
850        return mShowing || mNeedToReshowWhenReenabled || !mUpdateMonitor.isDeviceProvisioned();
851    }
852
853    /**
854     * Enable the keyguard if the settings are appropriate.
855     */
856    private void doKeyguardLocked(Bundle options) {
857        // if another app is disabling us, don't show
858        if (!mExternallyEnabled) {
859            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");
860
861            // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes
862            // for an occasional ugly flicker in this situation:
863            // 1) receive a call with the screen on (no keyguard) or make a call
864            // 2) screen times out
865            // 3) user hits key to turn screen back on
866            // instead, we reenable the keyguard when we know the screen is off and the call
867            // ends (see the broadcast receiver below)
868            // TODO: clean this up when we have better support at the window manager level
869            // for apps that wish to be on top of the keyguard
870            return;
871        }
872
873        // if the keyguard is already showing, don't bother
874        if (mKeyguardViewManager.isShowing()) {
875            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
876            return;
877        }
878
879        // if the setup wizard hasn't run yet, don't show
880        final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim",
881                false);
882        final boolean provisioned = mUpdateMonitor.isDeviceProvisioned();
883        final IccCardConstants.State state = mUpdateMonitor.getSimState();
884        final boolean lockedOrMissing = state.isPinLocked()
885                || ((state == IccCardConstants.State.ABSENT
886                || state == IccCardConstants.State.PERM_DISABLED)
887                && requireSim);
888
889        if (!lockedOrMissing && !provisioned) {
890            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
891                    + " and the sim is not locked or missing");
892            return;
893        }
894
895        if (mUserManager.getUsers(true).size() < 2
896                && mLockPatternUtils.isLockScreenDisabled() && !lockedOrMissing) {
897            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
898            return;
899        }
900
901        if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
902        showLocked(options);
903    }
904
905    /**
906     * Dismiss the keyguard through the security layers.
907     */
908    public void dismiss() {
909        if (mShowing && !mHidden) {
910            mKeyguardViewManager.dismiss();
911        }
912    }
913
914    /**
915     * Send message to keyguard telling it to reset its state.
916     * @param options options about how to show the keyguard
917     * @see #handleReset()
918     */
919    private void resetStateLocked(Bundle options) {
920        if (DEBUG) Log.e(TAG, "resetStateLocked");
921        Message msg = mHandler.obtainMessage(RESET, options);
922        mHandler.sendMessage(msg);
923    }
924
925    /**
926     * Send message to keyguard telling it to verify unlock
927     * @see #handleVerifyUnlock()
928     */
929    private void verifyUnlockLocked() {
930        if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
931        mHandler.sendEmptyMessage(VERIFY_UNLOCK);
932    }
933
934
935    /**
936     * Send a message to keyguard telling it the screen just turned on.
937     * @see #onScreenTurnedOff(int)
938     * @see #handleNotifyScreenOff
939     */
940    private void notifyScreenOffLocked() {
941        if (DEBUG) Log.d(TAG, "notifyScreenOffLocked");
942        mHandler.sendEmptyMessage(NOTIFY_SCREEN_OFF);
943    }
944
945    /**
946     * Send a message to keyguard telling it the screen just turned on.
947     * @see #onScreenTurnedOn()
948     * @see #handleNotifyScreenOn
949     */
950    private void notifyScreenOnLocked(IKeyguardShowCallback result) {
951        if (DEBUG) Log.d(TAG, "notifyScreenOnLocked");
952        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_ON, result);
953        mHandler.sendMessage(msg);
954    }
955
956    /**
957     * Send message to keyguard telling it to show itself
958     * @see #handleShow()
959     */
960    private void showLocked(Bundle options) {
961        if (DEBUG) Log.d(TAG, "showLocked");
962        // ensure we stay awake until we are finished displaying the keyguard
963        mShowKeyguardWakeLock.acquire();
964        Message msg = mHandler.obtainMessage(SHOW, options);
965        mHandler.sendMessage(msg);
966    }
967
968    /**
969     * Send message to keyguard telling it to hide itself
970     * @see #handleHide()
971     */
972    private void hideLocked() {
973        if (DEBUG) Log.d(TAG, "hideLocked");
974        Message msg = mHandler.obtainMessage(HIDE);
975        mHandler.sendMessage(msg);
976    }
977
978    public boolean isSecure() {
979        return mLockPatternUtils.isSecure()
980            || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
981    }
982
983    /**
984     * Update the newUserId. Call while holding WindowManagerService lock.
985     * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.
986     *
987     * @param newUserId The id of the incoming user.
988     */
989    public void setCurrentUser(int newUserId) {
990        mLockPatternUtils.setCurrentUser(newUserId);
991    }
992
993    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
994        @Override
995        public void onReceive(Context context, Intent intent) {
996            if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {
997                final int sequence = intent.getIntExtra("seq", 0);
998                if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
999                        + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
1000                synchronized (KeyguardViewMediator.this) {
1001                    if (mDelayedShowingSequence == sequence) {
1002                        // Don't play lockscreen SFX if the screen went off due to timeout.
1003                        mSuppressNextLockSound = true;
1004                        doKeyguardLocked(null);
1005                    }
1006                }
1007            }
1008        }
1009    };
1010
1011    public void keyguardDone(boolean authenticated, boolean wakeup) {
1012        mKeyguardDonePending = false;
1013        synchronized (this) {
1014            EventLog.writeEvent(70000, 2);
1015            if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated + ")");
1016            Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0,
1017                    wakeup ? 1 : 0);
1018            mHandler.sendMessage(msg);
1019        }
1020    }
1021
1022    /**
1023     * This handler will be associated with the policy thread, which will also
1024     * be the UI thread of the keyguard.  Since the apis of the policy, and therefore
1025     * this class, can be called by other threads, any action that directly
1026     * interacts with the keyguard ui should be posted to this handler, rather
1027     * than called directly.
1028     */
1029    private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
1030        @Override
1031        public void handleMessage(Message msg) {
1032            switch (msg.what) {
1033                case SHOW:
1034                    handleShow((Bundle) msg.obj);
1035                    return ;
1036                case HIDE:
1037                    handleHide();
1038                    return ;
1039                case RESET:
1040                    handleReset((Bundle) msg.obj);
1041                    return ;
1042                case VERIFY_UNLOCK:
1043                    handleVerifyUnlock();
1044                    return;
1045                case NOTIFY_SCREEN_OFF:
1046                    handleNotifyScreenOff();
1047                    return;
1048                case NOTIFY_SCREEN_ON:
1049                    handleNotifyScreenOn((IKeyguardShowCallback) msg.obj);
1050                    return;
1051                case KEYGUARD_DONE:
1052                    handleKeyguardDone(msg.arg1 != 0, msg.arg2 != 0);
1053                    return;
1054                case KEYGUARD_DONE_DRAWING:
1055                    handleKeyguardDoneDrawing();
1056                    return;
1057                case KEYGUARD_DONE_AUTHENTICATING:
1058                    keyguardDone(true, true);
1059                    return;
1060                case SET_HIDDEN:
1061                    handleSetHidden(msg.arg1 != 0);
1062                    break;
1063                case KEYGUARD_TIMEOUT:
1064                    synchronized (KeyguardViewMediator.this) {
1065                        doKeyguardLocked((Bundle) msg.obj);
1066                    }
1067                    break;
1068                case SHOW_ASSISTANT:
1069                    handleShowAssistant();
1070                    break;
1071                case DISPATCH_EVENT:
1072                    handleDispatchEvent((MotionEvent) msg.obj);
1073                    break;
1074            }
1075        }
1076    };
1077
1078    /**
1079     * @see #keyguardDone
1080     * @see #KEYGUARD_DONE
1081     */
1082    private void handleKeyguardDone(boolean authenticated, boolean wakeup) {
1083        if (DEBUG) Log.d(TAG, "handleKeyguardDone");
1084
1085        if (authenticated) {
1086            mUpdateMonitor.clearFailedUnlockAttempts();
1087        }
1088
1089        if (mExitSecureCallback != null) {
1090            try {
1091                mExitSecureCallback.onKeyguardExitResult(authenticated);
1092            } catch (RemoteException e) {
1093                Slog.w(TAG, "Failed to call onKeyguardExitResult(" + authenticated + ")", e);
1094            }
1095
1096            mExitSecureCallback = null;
1097
1098            if (authenticated) {
1099                // after succesfully exiting securely, no need to reshow
1100                // the keyguard when they've released the lock
1101                mExternallyEnabled = true;
1102                mNeedToReshowWhenReenabled = false;
1103            }
1104        }
1105
1106        handleHide();
1107        sendUserPresentBroadcast();
1108    }
1109
1110    protected void handleDispatchEvent(MotionEvent event) {
1111        mKeyguardViewManager.dispatch(event);
1112    }
1113
1114    private void sendUserPresentBroadcast() {
1115        final UserHandle currentUser = new UserHandle(mLockPatternUtils.getCurrentUser());
1116        mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, currentUser);
1117    }
1118
1119    /**
1120     * @see #keyguardDoneDrawing
1121     * @see #KEYGUARD_DONE_DRAWING
1122     */
1123    private void handleKeyguardDoneDrawing() {
1124        synchronized(this) {
1125            if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing");
1126            if (mWaitingUntilKeyguardVisible) {
1127                if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
1128                mWaitingUntilKeyguardVisible = false;
1129                notifyAll();
1130
1131                // there will usually be two of these sent, one as a timeout, and one
1132                // as a result of the callback, so remove any remaining messages from
1133                // the queue
1134                mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
1135            }
1136        }
1137    }
1138
1139    private void playSounds(boolean locked) {
1140        // User feedback for keyguard.
1141
1142        if (mSuppressNextLockSound) {
1143            mSuppressNextLockSound = false;
1144            return;
1145        }
1146
1147        final ContentResolver cr = mContext.getContentResolver();
1148        if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
1149            final int whichSound = locked
1150                ? mLockSoundId
1151                : mUnlockSoundId;
1152            mLockSounds.stop(mLockSoundStreamId);
1153            // Init mAudioManager
1154            if (mAudioManager == null) {
1155                mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
1156                if (mAudioManager == null) return;
1157                mMasterStreamType = mAudioManager.getMasterStreamType();
1158            }
1159            // If the stream is muted, don't play the sound
1160            if (mAudioManager.isStreamMute(mMasterStreamType)) return;
1161
1162            mLockSoundStreamId = mLockSounds.play(whichSound,
1163                    mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
1164        }
1165    }
1166
1167    private void updateActivityLockScreenState() {
1168        try {
1169            ActivityManagerNative.getDefault().setLockScreenShown(
1170                    mShowing && !mHidden);
1171        } catch (RemoteException e) {
1172        }
1173    }
1174
1175    /**
1176     * Handle message sent by {@link #showLocked}.
1177     * @see #SHOW
1178     */
1179    private void handleShow(Bundle options) {
1180        synchronized (KeyguardViewMediator.this) {
1181            if (!mSystemReady) {
1182                if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready.");
1183                return;
1184            } else {
1185                if (DEBUG) Log.d(TAG, "handleShow");
1186            }
1187
1188            mKeyguardViewManager.show(options);
1189            mShowing = true;
1190            mKeyguardDonePending = false;
1191            updateActivityLockScreenState();
1192            adjustStatusBarLocked();
1193            userActivity();
1194            try {
1195                ActivityManagerNative.getDefault().closeSystemDialogs("lock");
1196            } catch (RemoteException e) {
1197            }
1198
1199            // Do this at the end to not slow down display of the keyguard.
1200            playSounds(true);
1201
1202            mShowKeyguardWakeLock.release();
1203        }
1204    }
1205
1206    /**
1207     * Handle message sent by {@link #hideLocked()}
1208     * @see #HIDE
1209     */
1210    private void handleHide() {
1211        synchronized (KeyguardViewMediator.this) {
1212            if (DEBUG) Log.d(TAG, "handleHide");
1213
1214            // only play "unlock" noises if not on a call (since the incall UI
1215            // disables the keyguard)
1216            if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
1217                playSounds(false);
1218            }
1219
1220            mKeyguardViewManager.hide();
1221            mShowing = false;
1222            mKeyguardDonePending = false;
1223            updateActivityLockScreenState();
1224            adjustStatusBarLocked();
1225        }
1226    }
1227
1228    private void adjustStatusBarLocked() {
1229        if (mStatusBarManager == null) {
1230            mStatusBarManager = (StatusBarManager)
1231                    mContext.getSystemService(Context.STATUS_BAR_SERVICE);
1232        }
1233        if (mStatusBarManager == null) {
1234            Log.w(TAG, "Could not get status bar manager");
1235        } else {
1236            // Disable aspects of the system/status/navigation bars that must not be re-enabled by
1237            // windows that appear on top, ever
1238            int flags = StatusBarManager.DISABLE_NONE;
1239            if (mShowing) {
1240                // Permanently disable components not available when keyguard is enabled
1241                // (like recents). Temporary enable/disable (e.g. the "back" button) are
1242                // done in KeyguardHostView.
1243                flags |= StatusBarManager.DISABLE_RECENT;
1244                if (isSecure() || !ENABLE_INSECURE_STATUS_BAR_EXPAND) {
1245                    // showing secure lockscreen; disable expanding.
1246                    flags |= StatusBarManager.DISABLE_EXPAND;
1247                }
1248                if (isSecure()) {
1249                    // showing secure lockscreen; disable ticker.
1250                    flags |= StatusBarManager.DISABLE_NOTIFICATION_TICKER;
1251                }
1252                if (!isAssistantAvailable()) {
1253                    flags |= StatusBarManager.DISABLE_SEARCH;
1254                }
1255            }
1256
1257            if (DEBUG) {
1258                Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mHidden=" + mHidden
1259                        + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
1260            }
1261
1262            if (!(mContext instanceof Activity)) {
1263                mStatusBarManager.disable(flags);
1264            }
1265        }
1266    }
1267
1268    /**
1269     * Handle message sent by {@link #resetStateLocked(Bundle)}
1270     * @see #RESET
1271     */
1272    private void handleReset(Bundle options) {
1273        if (options == null) {
1274            options = new Bundle();
1275        }
1276        options.putBoolean(KeyguardViewManager.IS_SWITCHING_USER, mSwitchingUser);
1277        synchronized (KeyguardViewMediator.this) {
1278            if (DEBUG) Log.d(TAG, "handleReset");
1279            mKeyguardViewManager.reset(options);
1280        }
1281    }
1282
1283    /**
1284     * Handle message sent by {@link #verifyUnlock}
1285     * @see #VERIFY_UNLOCK
1286     */
1287    private void handleVerifyUnlock() {
1288        synchronized (KeyguardViewMediator.this) {
1289            if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
1290            mKeyguardViewManager.verifyUnlock();
1291            mShowing = true;
1292            updateActivityLockScreenState();
1293        }
1294    }
1295
1296    /**
1297     * Handle message sent by {@link #notifyScreenOffLocked()}
1298     * @see #NOTIFY_SCREEN_OFF
1299     */
1300    private void handleNotifyScreenOff() {
1301        synchronized (KeyguardViewMediator.this) {
1302            if (DEBUG) Log.d(TAG, "handleNotifyScreenOff");
1303            mKeyguardViewManager.onScreenTurnedOff();
1304        }
1305    }
1306
1307    /**
1308     * Handle message sent by {@link #notifyScreenOnLocked()}
1309     * @see #NOTIFY_SCREEN_ON
1310     */
1311    private void handleNotifyScreenOn(IKeyguardShowCallback callback) {
1312        synchronized (KeyguardViewMediator.this) {
1313            if (DEBUG) Log.d(TAG, "handleNotifyScreenOn");
1314            mKeyguardViewManager.onScreenTurnedOn(callback);
1315        }
1316    }
1317
1318    public boolean isDismissable() {
1319        return mKeyguardDonePending || !isSecure();
1320    }
1321
1322    public void showAssistant() {
1323        Message msg = mHandler.obtainMessage(SHOW_ASSISTANT);
1324        mHandler.sendMessage(msg);
1325    }
1326
1327    public void handleShowAssistant() {
1328        mKeyguardViewManager.showAssistant();
1329    }
1330
1331    private boolean isAssistantAvailable() {
1332        return mSearchManager != null
1333                && mSearchManager.getAssistIntent(mContext, false, UserHandle.USER_CURRENT) != null;
1334    }
1335
1336    public static MultiUserAvatarCache getAvatarCache() {
1337        return sMultiUserAvatarCache;
1338    }
1339
1340    public void dispatch(MotionEvent event) {
1341        Message msg = mHandler.obtainMessage(DISPATCH_EVENT, event);
1342        mHandler.sendMessage(msg);
1343    }
1344}
1345