KeyguardViewMediator.java revision ce7eb6daf06a88129da365eb2112537ce0bb1b75
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 mUiSoundsStreamType;
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        @Override
440        public void onFingerprintAuthenticated(int userId) {
441            if (mStatusBarKeyguardViewManager.isBouncerShowing()) {
442                mViewMediatorCallback.keyguardDone(true);
443            } else {
444                mStatusBarKeyguardViewManager.animateCollapsePanels();
445            }
446        };
447
448    };
449
450    ViewMediatorCallback mViewMediatorCallback = new ViewMediatorCallback() {
451
452        public void userActivity() {
453            KeyguardViewMediator.this.userActivity();
454        }
455
456        public void keyguardDone(boolean authenticated) {
457            if (!mKeyguardDonePending) {
458                KeyguardViewMediator.this.keyguardDone(authenticated, true);
459            }
460        }
461
462        public void keyguardDoneDrawing() {
463            mHandler.sendEmptyMessage(KEYGUARD_DONE_DRAWING);
464        }
465
466        @Override
467        public void setNeedsInput(boolean needsInput) {
468            mStatusBarKeyguardViewManager.setNeedsInput(needsInput);
469        }
470
471        @Override
472        public void keyguardDonePending() {
473            mKeyguardDonePending = true;
474            mHideAnimationRun = true;
475            mStatusBarKeyguardViewManager.startPreHideAnimation(null /* finishRunnable */);
476            mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_PENDING_TIMEOUT,
477                    KEYGUARD_DONE_PENDING_TIMEOUT_MS);
478        }
479
480        @Override
481        public void keyguardGone() {
482            mKeyguardDisplayManager.hide();
483        }
484
485        @Override
486        public void readyForKeyguardDone() {
487            if (mKeyguardDonePending) {
488                // Somebody has called keyguardDonePending before, which means that we are
489                // authenticated
490                KeyguardViewMediator.this.keyguardDone(true /* authenticated */, true /* wakeUp */);
491            }
492        }
493
494        @Override
495        public void resetKeyguard() {
496            resetStateLocked();
497        }
498
499        @Override
500        public void playTrustedSound() {
501            KeyguardViewMediator.this.playTrustedSound();
502        }
503
504        @Override
505        public boolean isInputRestricted() {
506            return KeyguardViewMediator.this.isInputRestricted();
507        }
508    };
509
510    public void userActivity() {
511        mPM.userActivity(SystemClock.uptimeMillis(), false);
512    }
513
514    private void setupLocked() {
515        mPM = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
516        mWM = WindowManagerGlobal.getWindowManagerService();
517        mTrustManager = (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
518
519        mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "show keyguard");
520        mShowKeyguardWakeLock.setReferenceCounted(false);
521
522        mContext.registerReceiver(mBroadcastReceiver, new IntentFilter(DELAYED_KEYGUARD_ACTION));
523
524        mKeyguardDisplayManager = new KeyguardDisplayManager(mContext);
525
526        mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
527
528        mUpdateMonitor = KeyguardUpdateMonitor.getInstance(mContext);
529
530        mLockPatternUtils = new LockPatternUtils(mContext);
531        mLockPatternUtils.setCurrentUser(ActivityManager.getCurrentUser());
532
533        // Assume keyguard is showing (unless it's disabled) until we know for sure...
534        setShowingLocked(!shouldWaitForProvisioning() && !mLockPatternUtils.isLockScreenDisabled());
535        mTrustManager.reportKeyguardShowingChanged();
536
537        mStatusBarKeyguardViewManager = new StatusBarKeyguardViewManager(mContext,
538                mViewMediatorCallback, mLockPatternUtils);
539        final ContentResolver cr = mContext.getContentResolver();
540
541        mScreenOn = mPM.isScreenOn();
542
543        mLockSounds = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
544        String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND);
545        if (soundPath != null) {
546            mLockSoundId = mLockSounds.load(soundPath, 1);
547        }
548        if (soundPath == null || mLockSoundId == 0) {
549            Log.w(TAG, "failed to load lock sound from " + soundPath);
550        }
551        soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND);
552        if (soundPath != null) {
553            mUnlockSoundId = mLockSounds.load(soundPath, 1);
554        }
555        if (soundPath == null || mUnlockSoundId == 0) {
556            Log.w(TAG, "failed to load unlock sound from " + soundPath);
557        }
558        soundPath = Settings.Global.getString(cr, Settings.Global.TRUSTED_SOUND);
559        if (soundPath != null) {
560            mTrustedSoundId = mLockSounds.load(soundPath, 1);
561        }
562        if (soundPath == null || mTrustedSoundId == 0) {
563            Log.w(TAG, "failed to load trusted sound from " + soundPath);
564        }
565
566        int lockSoundDefaultAttenuation = mContext.getResources().getInteger(
567                com.android.internal.R.integer.config_lockSoundVolumeDb);
568        mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20);
569
570        mHideAnimation = AnimationUtils.loadAnimation(mContext,
571                com.android.internal.R.anim.lock_screen_behind_enter);
572    }
573
574    @Override
575    public void start() {
576        synchronized (this) {
577            setupLocked();
578        }
579        putComponent(KeyguardViewMediator.class, this);
580    }
581
582    /**
583     * Let us know that the system is ready after startup.
584     */
585    public void onSystemReady() {
586        mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
587        synchronized (this) {
588            if (DEBUG) Log.d(TAG, "onSystemReady");
589            mSystemReady = true;
590            mUpdateMonitor.registerCallback(mUpdateCallback);
591
592            doKeyguardLocked(null);
593        }
594        // Most services aren't available until the system reaches the ready state, so we
595        // send it here when the device first boots.
596        maybeSendUserPresentBroadcast();
597    }
598
599    /**
600     * Called to let us know the screen was turned off.
601     * @param why either {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_USER} or
602     *   {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT}.
603     */
604    public void onScreenTurnedOff(int why) {
605        synchronized (this) {
606            mScreenOn = false;
607            if (DEBUG) Log.d(TAG, "onScreenTurnedOff(" + why + ")");
608
609            resetKeyguardDonePendingLocked();
610            mHideAnimationRun = false;
611
612            // Lock immediately based on setting if secure (user has a pin/pattern/password).
613            // This also "locks" the device when not secure to provide easy access to the
614            // camera while preventing unwanted input.
615            final boolean lockImmediately =
616                mLockPatternUtils.getPowerButtonInstantlyLocks() || !mLockPatternUtils.isSecure();
617
618            notifyScreenOffLocked();
619
620            if (mExitSecureCallback != null) {
621                if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
622                try {
623                    mExitSecureCallback.onKeyguardExitResult(false);
624                } catch (RemoteException e) {
625                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
626                }
627                mExitSecureCallback = null;
628                if (!mExternallyEnabled) {
629                    hideLocked();
630                }
631            } else if (mShowing) {
632                resetStateLocked();
633            } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT
634                   || (why == WindowManagerPolicy.OFF_BECAUSE_OF_USER && !lockImmediately)) {
635                doKeyguardLaterLocked();
636            } else {
637                doKeyguardLocked(null);
638            }
639        }
640        KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurnedOff(why);
641    }
642
643    private void doKeyguardLaterLocked() {
644        // if the screen turned off because of timeout or the user hit the power button
645        // and we don't need to lock immediately, set an alarm
646        // to enable it a little bit later (i.e, give the user a chance
647        // to turn the screen back on within a certain window without
648        // having to unlock the screen)
649        final ContentResolver cr = mContext.getContentResolver();
650
651        // From DisplaySettings
652        long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
653                KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);
654
655        // From SecuritySettings
656        final long lockAfterTimeout = Settings.Secure.getInt(cr,
657                Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
658                KEYGUARD_LOCK_AFTER_DELAY_DEFAULT);
659
660        // From DevicePolicyAdmin
661        final long policyTimeout = mLockPatternUtils.getDevicePolicyManager()
662                .getMaximumTimeToLock(null, mLockPatternUtils.getCurrentUser());
663
664        long timeout;
665        if (policyTimeout > 0) {
666            // policy in effect. Make sure we don't go beyond policy limit.
667            displayTimeout = Math.max(displayTimeout, 0); // ignore negative values
668            timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);
669        } else {
670            timeout = lockAfterTimeout;
671        }
672
673        if (timeout <= 0) {
674            // Lock now
675            mSuppressNextLockSound = true;
676            doKeyguardLocked(null);
677        } else {
678            // Lock in the future
679            long when = SystemClock.elapsedRealtime() + timeout;
680            Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
681            intent.putExtra("seq", mDelayedShowingSequence);
682            PendingIntent sender = PendingIntent.getBroadcast(mContext,
683                    0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
684            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender);
685            if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = "
686                             + mDelayedShowingSequence);
687        }
688    }
689
690    private void cancelDoKeyguardLaterLocked() {
691        mDelayedShowingSequence++;
692    }
693
694    /**
695     * Let's us know the screen was turned on.
696     */
697    public void onScreenTurnedOn(IKeyguardShowCallback callback) {
698        synchronized (this) {
699            mScreenOn = true;
700            cancelDoKeyguardLaterLocked();
701            if (DEBUG) Log.d(TAG, "onScreenTurnedOn, seq = " + mDelayedShowingSequence);
702            if (callback != null) {
703                notifyScreenOnLocked(callback);
704            }
705        }
706        KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurnedOn();
707        maybeSendUserPresentBroadcast();
708    }
709
710    private void maybeSendUserPresentBroadcast() {
711        if (mSystemReady && mLockPatternUtils.isLockScreenDisabled()) {
712            // Lock screen is disabled because the user has set the preference to "None".
713            // In this case, send out ACTION_USER_PRESENT here instead of in
714            // handleKeyguardDone()
715            sendUserPresentBroadcast();
716        }
717    }
718
719    /**
720     * A dream started.  We should lock after the usual screen-off lock timeout but only
721     * if there is a secure lock pattern.
722     */
723    public void onDreamingStarted() {
724        synchronized (this) {
725            if (mScreenOn && mLockPatternUtils.isSecure()) {
726                doKeyguardLaterLocked();
727            }
728        }
729    }
730
731    /**
732     * A dream stopped.
733     */
734    public void onDreamingStopped() {
735        synchronized (this) {
736            if (mScreenOn) {
737                cancelDoKeyguardLaterLocked();
738            }
739        }
740    }
741
742    /**
743     * Same semantics as {@link android.view.WindowManagerPolicy#enableKeyguard}; provide
744     * a way for external stuff to override normal keyguard behavior.  For instance
745     * the phone app disables the keyguard when it receives incoming calls.
746     */
747    public void setKeyguardEnabled(boolean enabled) {
748        synchronized (this) {
749            if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
750
751            if (isSecure()) {
752                Log.d(TAG, "current mode is SecurityMode, ignore hide keyguard");
753                return;
754            }
755
756            mExternallyEnabled = enabled;
757
758            if (!enabled && mShowing) {
759                if (mExitSecureCallback != null) {
760                    if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
761                    // we're in the process of handling a request to verify the user
762                    // can get past the keyguard. ignore extraneous requests to disable / reenable
763                    return;
764                }
765
766                // hiding keyguard that is showing, remember to reshow later
767                if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
768                        + "disabling status bar expansion");
769                mNeedToReshowWhenReenabled = true;
770                updateInputRestrictedLocked();
771                hideLocked();
772            } else if (enabled && mNeedToReshowWhenReenabled) {
773                // reenabled after previously hidden, reshow
774                if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
775                        + "status bar expansion");
776                mNeedToReshowWhenReenabled = false;
777                updateInputRestrictedLocked();
778
779                if (mExitSecureCallback != null) {
780                    if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
781                    try {
782                        mExitSecureCallback.onKeyguardExitResult(false);
783                    } catch (RemoteException e) {
784                        Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
785                    }
786                    mExitSecureCallback = null;
787                    resetStateLocked();
788                } else {
789                    showLocked(null);
790
791                    // block until we know the keygaurd is done drawing (and post a message
792                    // to unblock us after a timeout so we don't risk blocking too long
793                    // and causing an ANR).
794                    mWaitingUntilKeyguardVisible = true;
795                    mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
796                    if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
797                    while (mWaitingUntilKeyguardVisible) {
798                        try {
799                            wait();
800                        } catch (InterruptedException e) {
801                            Thread.currentThread().interrupt();
802                        }
803                    }
804                    if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
805                }
806            }
807        }
808    }
809
810    /**
811     * @see android.app.KeyguardManager#exitKeyguardSecurely
812     */
813    public void verifyUnlock(IKeyguardExitCallback callback) {
814        synchronized (this) {
815            if (DEBUG) Log.d(TAG, "verifyUnlock");
816            if (shouldWaitForProvisioning()) {
817                // don't allow this api when the device isn't provisioned
818                if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
819                try {
820                    callback.onKeyguardExitResult(false);
821                } catch (RemoteException e) {
822                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
823                }
824            } else if (mExternallyEnabled) {
825                // this only applies when the user has externally disabled the
826                // keyguard.  this is unexpected and means the user is not
827                // using the api properly.
828                Log.w(TAG, "verifyUnlock called when not externally disabled");
829                try {
830                    callback.onKeyguardExitResult(false);
831                } catch (RemoteException e) {
832                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
833                }
834            } else if (mExitSecureCallback != null) {
835                // already in progress with someone else
836                try {
837                    callback.onKeyguardExitResult(false);
838                } catch (RemoteException e) {
839                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
840                }
841            } else {
842                mExitSecureCallback = callback;
843                verifyUnlockLocked();
844            }
845        }
846    }
847
848    /**
849     * Is the keyguard currently showing and not being force hidden?
850     */
851    public boolean isShowingAndNotOccluded() {
852        return mShowing && !mOccluded;
853    }
854
855    /**
856     * Notify us when the keyguard is occluded by another window
857     */
858    public void setOccluded(boolean isOccluded) {
859        if (DEBUG) Log.d(TAG, "setOccluded " + isOccluded);
860        mHandler.removeMessages(SET_OCCLUDED);
861        Message msg = mHandler.obtainMessage(SET_OCCLUDED, (isOccluded ? 1 : 0), 0);
862        mHandler.sendMessage(msg);
863    }
864
865    /**
866     * Handles SET_OCCLUDED message sent by setOccluded()
867     */
868    private void handleSetOccluded(boolean isOccluded) {
869        synchronized (KeyguardViewMediator.this) {
870            if (mOccluded != isOccluded) {
871                mOccluded = isOccluded;
872                mStatusBarKeyguardViewManager.setOccluded(isOccluded);
873                updateActivityLockScreenState();
874                adjustStatusBarLocked();
875            }
876        }
877    }
878
879    /**
880     * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout.
881     * This must be safe to call from any thread and with any window manager locks held.
882     */
883    public void doKeyguardTimeout(Bundle options) {
884        mHandler.removeMessages(KEYGUARD_TIMEOUT);
885        Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
886        mHandler.sendMessage(msg);
887    }
888
889    /**
890     * Given the state of the keyguard, is the input restricted?
891     * Input is restricted when the keyguard is showing, or when the keyguard
892     * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.
893     */
894    public boolean isInputRestricted() {
895        return mShowing || mNeedToReshowWhenReenabled || shouldWaitForProvisioning();
896    }
897
898    private void updateInputRestricted() {
899        synchronized (this) {
900            updateInputRestrictedLocked();
901        }
902    }
903    private void updateInputRestrictedLocked() {
904        boolean inputRestricted = isInputRestricted();
905        if (mInputRestricted != inputRestricted) {
906            mInputRestricted = inputRestricted;
907            try {
908                int size = mKeyguardStateCallbacks.size();
909                for (int i = 0; i < size; i++) {
910                    mKeyguardStateCallbacks.get(i).onInputRestrictedStateChanged(inputRestricted);
911                }
912            } catch (RemoteException e) {
913                Slog.w(TAG, "Failed to call onDeviceProvisioned", e);
914            }
915        }
916    }
917
918    /**
919     * Enable the keyguard if the settings are appropriate.
920     */
921    private void doKeyguardLocked(Bundle options) {
922        // if another app is disabling us, don't show
923        if (!mExternallyEnabled) {
924            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");
925
926            // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes
927            // for an occasional ugly flicker in this situation:
928            // 1) receive a call with the screen on (no keyguard) or make a call
929            // 2) screen times out
930            // 3) user hits key to turn screen back on
931            // instead, we reenable the keyguard when we know the screen is off and the call
932            // ends (see the broadcast receiver below)
933            // TODO: clean this up when we have better support at the window manager level
934            // for apps that wish to be on top of the keyguard
935            return;
936        }
937
938        // if the keyguard is already showing, don't bother
939        if (mStatusBarKeyguardViewManager.isShowing()) {
940            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
941            resetStateLocked();
942            return;
943        }
944
945        // if the setup wizard hasn't run yet, don't show
946        final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim", false);
947        final boolean absent = SubscriptionManager.isValidSubscriptionId(
948                mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.ABSENT));
949        final boolean disabled = SubscriptionManager.isValidSubscriptionId(
950                mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.PERM_DISABLED));
951        final boolean lockedOrMissing = mUpdateMonitor.isSimPinSecure()
952                || ((absent || disabled) && requireSim);
953
954        if (!lockedOrMissing && shouldWaitForProvisioning()) {
955            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
956                    + " and the sim is not locked or missing");
957            return;
958        }
959
960        if (mLockPatternUtils.isLockScreenDisabled() && !lockedOrMissing) {
961            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
962            return;
963        }
964
965        if (mLockPatternUtils.checkVoldPassword()) {
966            if (DEBUG) Log.d(TAG, "Not showing lock screen since just decrypted");
967            // Without this, settings is not enabled until the lock screen first appears
968            setShowingLocked(false);
969            hideLocked();
970            return;
971        }
972
973        if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
974        showLocked(options);
975    }
976
977    private boolean shouldWaitForProvisioning() {
978        return !mUpdateMonitor.isDeviceProvisioned() && !isSecure();
979    }
980
981    /**
982     * Dismiss the keyguard through the security layers.
983     */
984    public void handleDismiss() {
985        if (mShowing && !mOccluded) {
986            mStatusBarKeyguardViewManager.dismiss();
987        }
988    }
989
990    public void dismiss() {
991        mHandler.sendEmptyMessage(DISMISS);
992    }
993
994    /**
995     * Send message to keyguard telling it to reset its state.
996     * @see #handleReset
997     */
998    private void resetStateLocked() {
999        if (DEBUG) Log.e(TAG, "resetStateLocked");
1000        Message msg = mHandler.obtainMessage(RESET);
1001        mHandler.sendMessage(msg);
1002    }
1003
1004    /**
1005     * Send message to keyguard telling it to verify unlock
1006     * @see #handleVerifyUnlock()
1007     */
1008    private void verifyUnlockLocked() {
1009        if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
1010        mHandler.sendEmptyMessage(VERIFY_UNLOCK);
1011    }
1012
1013
1014    /**
1015     * Send a message to keyguard telling it the screen just turned on.
1016     * @see #onScreenTurnedOff(int)
1017     * @see #handleNotifyScreenOff
1018     */
1019    private void notifyScreenOffLocked() {
1020        if (DEBUG) Log.d(TAG, "notifyScreenOffLocked");
1021        mHandler.sendEmptyMessage(NOTIFY_SCREEN_OFF);
1022    }
1023
1024    /**
1025     * Send a message to keyguard telling it the screen just turned on.
1026     * @see #onScreenTurnedOn
1027     * @see #handleNotifyScreenOn
1028     */
1029    private void notifyScreenOnLocked(IKeyguardShowCallback result) {
1030        if (DEBUG) Log.d(TAG, "notifyScreenOnLocked");
1031        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_ON, result);
1032        mHandler.sendMessage(msg);
1033    }
1034
1035    /**
1036     * Send message to keyguard telling it to show itself
1037     * @see #handleShow
1038     */
1039    private void showLocked(Bundle options) {
1040        if (DEBUG) Log.d(TAG, "showLocked");
1041        // ensure we stay awake until we are finished displaying the keyguard
1042        mShowKeyguardWakeLock.acquire();
1043        Message msg = mHandler.obtainMessage(SHOW, options);
1044        mHandler.sendMessage(msg);
1045    }
1046
1047    /**
1048     * Send message to keyguard telling it to hide itself
1049     * @see #handleHide()
1050     */
1051    private void hideLocked() {
1052        if (DEBUG) Log.d(TAG, "hideLocked");
1053        Message msg = mHandler.obtainMessage(HIDE);
1054        mHandler.sendMessage(msg);
1055    }
1056
1057    public boolean isSecure() {
1058        return mLockPatternUtils.isSecure()
1059            || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
1060    }
1061
1062    /**
1063     * Update the newUserId. Call while holding WindowManagerService lock.
1064     * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.
1065     *
1066     * @param newUserId The id of the incoming user.
1067     */
1068    public void setCurrentUser(int newUserId) {
1069        mLockPatternUtils.setCurrentUser(newUserId);
1070    }
1071
1072    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1073        @Override
1074        public void onReceive(Context context, Intent intent) {
1075            if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {
1076                final int sequence = intent.getIntExtra("seq", 0);
1077                if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
1078                        + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
1079                synchronized (KeyguardViewMediator.this) {
1080                    if (mDelayedShowingSequence == sequence) {
1081                        // Don't play lockscreen SFX if the screen went off due to timeout.
1082                        mSuppressNextLockSound = true;
1083                        doKeyguardLocked(null);
1084                    }
1085                }
1086            }
1087        }
1088    };
1089
1090    public void keyguardDone(boolean authenticated, boolean wakeup) {
1091        if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated + ")");
1092        EventLog.writeEvent(70000, 2);
1093        Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0, wakeup ? 1 : 0);
1094        mHandler.sendMessage(msg);
1095    }
1096
1097    /**
1098     * This handler will be associated with the policy thread, which will also
1099     * be the UI thread of the keyguard.  Since the apis of the policy, and therefore
1100     * this class, can be called by other threads, any action that directly
1101     * interacts with the keyguard ui should be posted to this handler, rather
1102     * than called directly.
1103     */
1104    private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
1105        @Override
1106        public void handleMessage(Message msg) {
1107            switch (msg.what) {
1108                case SHOW:
1109                    handleShow((Bundle) msg.obj);
1110                    break;
1111                case HIDE:
1112                    handleHide();
1113                    break;
1114                case RESET:
1115                    handleReset();
1116                    break;
1117                case VERIFY_UNLOCK:
1118                    handleVerifyUnlock();
1119                    break;
1120                case NOTIFY_SCREEN_OFF:
1121                    handleNotifyScreenOff();
1122                    break;
1123                case NOTIFY_SCREEN_ON:
1124                    handleNotifyScreenOn((IKeyguardShowCallback) msg.obj);
1125                    break;
1126                case KEYGUARD_DONE:
1127                    handleKeyguardDone(msg.arg1 != 0, msg.arg2 != 0);
1128                    break;
1129                case KEYGUARD_DONE_DRAWING:
1130                    handleKeyguardDoneDrawing();
1131                    break;
1132                case KEYGUARD_DONE_AUTHENTICATING:
1133                    keyguardDone(true, true);
1134                    break;
1135                case SET_OCCLUDED:
1136                    handleSetOccluded(msg.arg1 != 0);
1137                    break;
1138                case KEYGUARD_TIMEOUT:
1139                    synchronized (KeyguardViewMediator.this) {
1140                        doKeyguardLocked((Bundle) msg.obj);
1141                    }
1142                    break;
1143                case DISMISS:
1144                    handleDismiss();
1145                    break;
1146                case START_KEYGUARD_EXIT_ANIM:
1147                    StartKeyguardExitAnimParams params = (StartKeyguardExitAnimParams) msg.obj;
1148                    handleStartKeyguardExitAnimation(params.startTime, params.fadeoutDuration);
1149                    break;
1150                case KEYGUARD_DONE_PENDING_TIMEOUT:
1151                    Log.w(TAG, "Timeout while waiting for activity drawn!");
1152                    // Fall through.
1153                case ON_ACTIVITY_DRAWN:
1154                    handleOnActivityDrawn();
1155                    break;
1156            }
1157        }
1158    };
1159
1160    /**
1161     * @see #keyguardDone
1162     * @see #KEYGUARD_DONE
1163     */
1164    private void handleKeyguardDone(boolean authenticated, boolean wakeup) {
1165        if (DEBUG) Log.d(TAG, "handleKeyguardDone");
1166        synchronized (this) {
1167            resetKeyguardDonePendingLocked();
1168        }
1169
1170        if (authenticated) {
1171            mUpdateMonitor.clearFailedUnlockAttempts();
1172        }
1173        mUpdateMonitor.clearFingerprintRecognized();
1174
1175        if (mExitSecureCallback != null) {
1176            try {
1177                mExitSecureCallback.onKeyguardExitResult(authenticated);
1178            } catch (RemoteException e) {
1179                Slog.w(TAG, "Failed to call onKeyguardExitResult(" + authenticated + ")", e);
1180            }
1181
1182            mExitSecureCallback = null;
1183
1184            if (authenticated) {
1185                // after succesfully exiting securely, no need to reshow
1186                // the keyguard when they've released the lock
1187                mExternallyEnabled = true;
1188                mNeedToReshowWhenReenabled = false;
1189                updateInputRestricted();
1190            }
1191        }
1192
1193        handleHide();
1194    }
1195
1196    private void sendUserPresentBroadcast() {
1197        synchronized (this) {
1198            if (mBootCompleted) {
1199                final UserHandle currentUser = new UserHandle(mLockPatternUtils.getCurrentUser());
1200                final UserManager um = (UserManager) mContext.getSystemService(
1201                        Context.USER_SERVICE);
1202                List <UserInfo> userHandles = um.getProfiles(currentUser.getIdentifier());
1203                for (UserInfo ui : userHandles) {
1204                    mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, ui.getUserHandle());
1205                }
1206            } else {
1207                mBootSendUserPresent = true;
1208            }
1209        }
1210    }
1211
1212    /**
1213     * @see #keyguardDone
1214     * @see #KEYGUARD_DONE_DRAWING
1215     */
1216    private void handleKeyguardDoneDrawing() {
1217        synchronized(this) {
1218            if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing");
1219            if (mWaitingUntilKeyguardVisible) {
1220                if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
1221                mWaitingUntilKeyguardVisible = false;
1222                notifyAll();
1223
1224                // there will usually be two of these sent, one as a timeout, and one
1225                // as a result of the callback, so remove any remaining messages from
1226                // the queue
1227                mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
1228            }
1229        }
1230    }
1231
1232    private void playSounds(boolean locked) {
1233        // User feedback for keyguard.
1234
1235        if (mSuppressNextLockSound) {
1236            mSuppressNextLockSound = false;
1237            return;
1238        }
1239
1240        playSound(locked ? mLockSoundId : mUnlockSoundId);
1241    }
1242
1243    private void playSound(int soundId) {
1244        if (soundId == 0) return;
1245        final ContentResolver cr = mContext.getContentResolver();
1246        if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
1247
1248            mLockSounds.stop(mLockSoundStreamId);
1249            // Init mAudioManager
1250            if (mAudioManager == null) {
1251                mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
1252                if (mAudioManager == null) return;
1253                mUiSoundsStreamType = mAudioManager.getUiSoundsStreamType();
1254            }
1255            // If the stream is muted, don't play the sound
1256            if (mAudioManager.isStreamMute(mUiSoundsStreamType)) return;
1257
1258            mLockSoundStreamId = mLockSounds.play(soundId,
1259                    mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
1260        }
1261    }
1262
1263    private void playTrustedSound() {
1264        if (mSuppressNextLockSound) {
1265            return;
1266        }
1267        playSound(mTrustedSoundId);
1268    }
1269
1270    private void updateActivityLockScreenState() {
1271        try {
1272            ActivityManagerNative.getDefault().setLockScreenShown(mShowing && !mOccluded);
1273        } catch (RemoteException e) {
1274        }
1275    }
1276
1277    /**
1278     * Handle message sent by {@link #showLocked}.
1279     * @see #SHOW
1280     */
1281    private void handleShow(Bundle options) {
1282        synchronized (KeyguardViewMediator.this) {
1283            if (!mSystemReady) {
1284                if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready.");
1285                return;
1286            } else {
1287                if (DEBUG) Log.d(TAG, "handleShow");
1288            }
1289
1290            setShowingLocked(true);
1291            mStatusBarKeyguardViewManager.show(options);
1292            mHiding = false;
1293            resetKeyguardDonePendingLocked();
1294            mHideAnimationRun = false;
1295            updateActivityLockScreenState();
1296            adjustStatusBarLocked();
1297            userActivity();
1298
1299            // Do this at the end to not slow down display of the keyguard.
1300            playSounds(true);
1301
1302            mShowKeyguardWakeLock.release();
1303        }
1304        mKeyguardDisplayManager.show();
1305    }
1306
1307    private final Runnable mKeyguardGoingAwayRunnable = new Runnable() {
1308        @Override
1309        public void run() {
1310            try {
1311                mStatusBarKeyguardViewManager.keyguardGoingAway();
1312
1313                // Don't actually hide the Keyguard at the moment, wait for window
1314                // manager until it tells us it's safe to do so with
1315                // startKeyguardExitAnimation.
1316                mWM.keyguardGoingAway(
1317                        mStatusBarKeyguardViewManager.shouldDisableWindowAnimationsForUnlock(),
1318                        mStatusBarKeyguardViewManager.isGoingToNotificationShade());
1319            } catch (RemoteException e) {
1320                Log.e(TAG, "Error while calling WindowManager", e);
1321            }
1322        }
1323    };
1324
1325    /**
1326     * Handle message sent by {@link #hideLocked()}
1327     * @see #HIDE
1328     */
1329    private void handleHide() {
1330        synchronized (KeyguardViewMediator.this) {
1331            if (DEBUG) Log.d(TAG, "handleHide");
1332
1333            mHiding = true;
1334            if (mShowing && !mOccluded) {
1335                if (!mHideAnimationRun) {
1336                    mStatusBarKeyguardViewManager.startPreHideAnimation(mKeyguardGoingAwayRunnable);
1337                } else {
1338                    mKeyguardGoingAwayRunnable.run();
1339                }
1340            } else {
1341
1342                // Don't try to rely on WindowManager - if Keyguard wasn't showing, window
1343                // manager won't start the exit animation.
1344                handleStartKeyguardExitAnimation(
1345                        SystemClock.uptimeMillis() + mHideAnimation.getStartOffset(),
1346                        mHideAnimation.getDuration());
1347            }
1348        }
1349    }
1350
1351    private void handleOnActivityDrawn() {
1352        if (DEBUG) Log.d(TAG, "handleOnActivityDrawn: mKeyguardDonePending=" + mKeyguardDonePending);
1353        if (mKeyguardDonePending) {
1354            mStatusBarKeyguardViewManager.onActivityDrawn();
1355        }
1356    }
1357
1358    private void handleStartKeyguardExitAnimation(long startTime, long fadeoutDuration) {
1359        synchronized (KeyguardViewMediator.this) {
1360
1361            if (!mHiding) {
1362                return;
1363            }
1364            mHiding = false;
1365
1366            // only play "unlock" noises if not on a call (since the incall UI
1367            // disables the keyguard)
1368            if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
1369                playSounds(false);
1370            }
1371
1372            setShowingLocked(false);
1373            mStatusBarKeyguardViewManager.hide(startTime, fadeoutDuration);
1374            resetKeyguardDonePendingLocked();
1375            mHideAnimationRun = false;
1376            updateActivityLockScreenState();
1377            adjustStatusBarLocked();
1378            sendUserPresentBroadcast();
1379            maybeStopListeningForFingerprint();
1380        }
1381    }
1382
1383    private void maybeStopListeningForFingerprint() {
1384        mUpdateMonitor.stopListeningForFingerprint();
1385    }
1386
1387    private void adjustStatusBarLocked() {
1388        if (mStatusBarManager == null) {
1389            mStatusBarManager = (StatusBarManager)
1390                    mContext.getSystemService(Context.STATUS_BAR_SERVICE);
1391        }
1392        if (mStatusBarManager == null) {
1393            Log.w(TAG, "Could not get status bar manager");
1394        } else {
1395            // Disable aspects of the system/status/navigation bars that must not be re-enabled by
1396            // windows that appear on top, ever
1397            int flags = StatusBarManager.DISABLE_NONE;
1398            if (mShowing) {
1399                // Permanently disable components not available when keyguard is enabled
1400                // (like recents). Temporary enable/disable (e.g. the "back" button) are
1401                // done in KeyguardHostView.
1402                flags |= StatusBarManager.DISABLE_RECENT;
1403                flags |= StatusBarManager.DISABLE_SEARCH;
1404            }
1405            if (isShowingAndNotOccluded()) {
1406                flags |= StatusBarManager.DISABLE_HOME;
1407            }
1408
1409            if (DEBUG) {
1410                Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mOccluded=" + mOccluded
1411                        + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
1412            }
1413
1414            if (!(mContext instanceof Activity)) {
1415                mStatusBarManager.disable(flags);
1416            }
1417        }
1418    }
1419
1420    /**
1421     * Handle message sent by {@link #resetStateLocked}
1422     * @see #RESET
1423     */
1424    private void handleReset() {
1425        synchronized (KeyguardViewMediator.this) {
1426            if (DEBUG) Log.d(TAG, "handleReset");
1427            mStatusBarKeyguardViewManager.reset();
1428        }
1429    }
1430
1431    /**
1432     * Handle message sent by {@link #verifyUnlock}
1433     * @see #VERIFY_UNLOCK
1434     */
1435    private void handleVerifyUnlock() {
1436        synchronized (KeyguardViewMediator.this) {
1437            if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
1438            setShowingLocked(true);
1439            mStatusBarKeyguardViewManager.verifyUnlock();
1440            updateActivityLockScreenState();
1441        }
1442    }
1443
1444    /**
1445     * Handle message sent by {@link #notifyScreenOffLocked()}
1446     * @see #NOTIFY_SCREEN_OFF
1447     */
1448    private void handleNotifyScreenOff() {
1449        synchronized (KeyguardViewMediator.this) {
1450            if (DEBUG) Log.d(TAG, "handleNotifyScreenOff");
1451            mStatusBarKeyguardViewManager.onScreenTurnedOff();
1452        }
1453    }
1454
1455    /**
1456     * Handle message sent by {@link #notifyScreenOnLocked}
1457     * @see #NOTIFY_SCREEN_ON
1458     */
1459    private void handleNotifyScreenOn(IKeyguardShowCallback callback) {
1460        synchronized (KeyguardViewMediator.this) {
1461            if (DEBUG) Log.d(TAG, "handleNotifyScreenOn");
1462            mStatusBarKeyguardViewManager.onScreenTurnedOn(callback);
1463        }
1464    }
1465
1466    private void resetKeyguardDonePendingLocked() {
1467        mKeyguardDonePending = false;
1468        mHandler.removeMessages(KEYGUARD_DONE_PENDING_TIMEOUT);
1469    }
1470
1471    public void onBootCompleted() {
1472        mUpdateMonitor.dispatchBootCompleted();
1473        synchronized (this) {
1474            mBootCompleted = true;
1475            if (mBootSendUserPresent) {
1476                sendUserPresentBroadcast();
1477            }
1478        }
1479    }
1480
1481    public StatusBarKeyguardViewManager registerStatusBar(PhoneStatusBar phoneStatusBar,
1482            ViewGroup container, StatusBarWindowManager statusBarWindowManager,
1483            ScrimController scrimController) {
1484        mStatusBarKeyguardViewManager.registerStatusBar(phoneStatusBar, container,
1485                statusBarWindowManager, scrimController);
1486        return mStatusBarKeyguardViewManager;
1487    }
1488
1489    public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
1490        Message msg = mHandler.obtainMessage(START_KEYGUARD_EXIT_ANIM,
1491                new StartKeyguardExitAnimParams(startTime, fadeoutDuration));
1492        mHandler.sendMessage(msg);
1493    }
1494
1495    public void onActivityDrawn() {
1496        mHandler.sendEmptyMessage(ON_ACTIVITY_DRAWN);
1497    }
1498    public ViewMediatorCallback getViewMediatorCallback() {
1499        return mViewMediatorCallback;
1500    }
1501
1502    private static class StartKeyguardExitAnimParams {
1503
1504        long startTime;
1505        long fadeoutDuration;
1506
1507        private StartKeyguardExitAnimParams(long startTime, long fadeoutDuration) {
1508            this.startTime = startTime;
1509            this.fadeoutDuration = fadeoutDuration;
1510        }
1511    }
1512
1513    private void setShowingLocked(boolean showing) {
1514        if (showing != mShowing) {
1515            mShowing = showing;
1516            try {
1517                int size = mKeyguardStateCallbacks.size();
1518                for (int i = 0; i < size; i++) {
1519                    mKeyguardStateCallbacks.get(i).onShowingStateChanged(showing);
1520                }
1521            } catch (RemoteException e) {
1522                Slog.w(TAG, "Failed to call onShowingStateChanged", e);
1523            }
1524            updateInputRestrictedLocked();
1525            mTrustManager.reportKeyguardShowingChanged();
1526        }
1527    }
1528
1529    public void addStateMonitorCallback(IKeyguardStateCallback callback) {
1530        synchronized (this) {
1531            mKeyguardStateCallbacks.add(callback);
1532            try {
1533                callback.onSimSecureStateChanged(mUpdateMonitor.isSimPinSecure());
1534                callback.onShowingStateChanged(mShowing);
1535            } catch (RemoteException e) {
1536                Slog.w(TAG, "Failed to call onShowingStateChanged or onSimSecureStateChanged", e);
1537            }
1538        }
1539    }
1540}
1541