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