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