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