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