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