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