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