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