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