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