KeyguardViewMediator.java revision 0b9d8accc569d8b51fd76118ce2f069c24b9af90
1/*
2 * Copyright (C) 2007 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.keyguard;
18
19import android.graphics.Bitmap;
20import com.android.internal.policy.IKeyguardExitCallback;
21import com.android.internal.policy.IKeyguardShowCallback;
22import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
23
24import android.app.Activity;
25import android.app.ActivityManagerNative;
26import android.app.AlarmManager;
27import android.app.PendingIntent;
28import android.app.SearchManager;
29import android.app.StatusBarManager;
30import android.content.BroadcastReceiver;
31import android.content.ContentResolver;
32import android.content.Context;
33import android.content.Intent;
34import android.content.IntentFilter;
35import android.media.AudioManager;
36import android.media.SoundPool;
37import android.os.Bundle;
38import android.os.Handler;
39import android.os.Looper;
40import android.os.Message;
41import android.os.PowerManager;
42import android.os.RemoteException;
43import android.os.SystemClock;
44import android.os.SystemProperties;
45import android.os.UserHandle;
46import android.os.UserManager;
47import android.provider.Settings;
48import android.telephony.TelephonyManager;
49import android.util.EventLog;
50import android.util.Log;
51import android.util.Slog;
52import android.view.KeyEvent;
53import android.view.MotionEvent;
54import android.view.WindowManager;
55import android.view.WindowManagerPolicy;
56
57import com.android.internal.telephony.IccCardConstants;
58import com.android.internal.widget.LockPatternUtils;
59
60
61/**
62 * Mediates requests related to the keyguard.  This includes queries about the
63 * state of the keyguard, power management events that effect whether the keyguard
64 * should be shown or reset, callbacks to the phone window manager to notify
65 * it of when the keyguard is showing, and events from the keyguard view itself
66 * stating that the keyguard was succesfully unlocked.
67 *
68 * Note that the keyguard view is shown when the screen is off (as appropriate)
69 * so that once the screen comes on, it will be ready immediately.
70 *
71 * Example queries about the keyguard:
72 * - is {movement, key} one that should wake the keygaurd?
73 * - is the keyguard showing?
74 * - are input events restricted due to the state of the keyguard?
75 *
76 * Callbacks to the phone window manager:
77 * - the keyguard is showing
78 *
79 * Example external events that translate to keyguard view changes:
80 * - screen turned off -> reset the keyguard, and show it so it will be ready
81 *   next time the screen turns on
82 * - keyboard is slid open -> if the keyguard is not secure, hide it
83 *
84 * Events from the keyguard view:
85 * - user succesfully unlocked keyguard -> hide keyguard view, and no longer
86 *   restrict input events.
87 *
88 * Note: in addition to normal power managment events that effect the state of
89 * whether the keyguard should be showing, external apps and services may request
90 * that the keyguard be disabled via {@link #setKeyguardEnabled(boolean)}.  When
91 * false, this will override all other conditions for turning on the keyguard.
92 *
93 * Threading and synchronization:
94 * This class is created by the initialization routine of the {@link WindowManagerPolicy},
95 * and runs on its thread.  The keyguard UI is created from that thread in the
96 * constructor of this class.  The apis may be called from other threads, including the
97 * {@link com.android.server.input.InputManagerService}'s and {@link android.view.WindowManager}'s.
98 * Therefore, methods on this class are synchronized, and any action that is pointed
99 * directly to the keyguard UI is posted to a {@link Handler} to ensure it is taken on the UI
100 * thread of the keyguard.
101 */
102public class KeyguardViewMediator {
103    private static final int KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000;
104    final static boolean DEBUG = false;
105    private final static boolean DBG_WAKE = false;
106
107    private final static String TAG = "KeyguardViewMediator";
108
109    private static final String DELAYED_KEYGUARD_ACTION =
110        "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_KEYGUARD";
111
112    // used for handler messages
113    private static final int SHOW = 2;
114    private static final int HIDE = 3;
115    private static final int RESET = 4;
116    private static final int VERIFY_UNLOCK = 5;
117    private static final int NOTIFY_SCREEN_OFF = 6;
118    private static final int NOTIFY_SCREEN_ON = 7;
119    private static final int KEYGUARD_DONE = 9;
120    private static final int KEYGUARD_DONE_DRAWING = 10;
121    private static final int KEYGUARD_DONE_AUTHENTICATING = 11;
122    private static final int SET_HIDDEN = 12;
123    private static final int KEYGUARD_TIMEOUT = 13;
124    private static final int SHOW_ASSISTANT = 14;
125    private static final int DISPATCH_EVENT = 15;
126    private static final int LAUNCH_CAMERA = 16;
127    private static final int DISMISS = 17;
128
129    /**
130     * The default amount of time we stay awake (used for all key input)
131     */
132    protected static final int AWAKE_INTERVAL_DEFAULT_MS = 10000;
133
134    /**
135     * How long to wait after the screen turns off due to timeout before
136     * turning on the keyguard (i.e, the user has this much time to turn
137     * the screen back on without having to face the keyguard).
138     */
139    private static final int KEYGUARD_LOCK_AFTER_DELAY_DEFAULT = 5000;
140
141    /**
142     * How long we'll wait for the {@link ViewMediatorCallback#keyguardDoneDrawing()}
143     * callback before unblocking a call to {@link #setKeyguardEnabled(boolean)}
144     * that is reenabling the keyguard.
145     */
146    private static final int KEYGUARD_DONE_DRAWING_TIMEOUT_MS = 2000;
147
148    /**
149     * Allow the user to expand the status bar when the keyguard is engaged
150     * (without a pattern or password).
151     */
152    private static final boolean ENABLE_INSECURE_STATUS_BAR_EXPAND = true;
153
154    /** The stream type that the lock sounds are tied to. */
155    private int mMasterStreamType;
156
157    private Context mContext;
158    private AlarmManager mAlarmManager;
159    private AudioManager mAudioManager;
160    private StatusBarManager mStatusBarManager;
161    private boolean mSwitchingUser;
162
163    private boolean mSystemReady;
164
165    // Whether the next call to playSounds() should be skipped.  Defaults to
166    // true because the first lock (on boot) should be silent.
167    private boolean mSuppressNextLockSound = true;
168
169
170    /** High level access to the power manager for WakeLocks */
171    private PowerManager mPM;
172
173    /** UserManager for querying number of users */
174    private UserManager mUserManager;
175
176    /** SearchManager for determining whether or not search assistant is available */
177    private SearchManager mSearchManager;
178
179    /**
180     * Used to keep the device awake while to ensure the keyguard finishes opening before
181     * we sleep.
182     */
183    private PowerManager.WakeLock mShowKeyguardWakeLock;
184
185    private KeyguardViewManager mKeyguardViewManager;
186
187    // these are protected by synchronized (this)
188
189    /**
190     * External apps (like the phone app) can tell us to disable the keygaurd.
191     */
192    private boolean mExternallyEnabled = true;
193
194    /**
195     * Remember if an external call to {@link #setKeyguardEnabled} with value
196     * false caused us to hide the keyguard, so that we need to reshow it once
197     * the keygaurd is reenabled with another call with value true.
198     */
199    private boolean mNeedToReshowWhenReenabled = false;
200
201    // cached value of whether we are showing (need to know this to quickly
202    // answer whether the input should be restricted)
203    private boolean mShowing = false;
204
205    // true if the keyguard is hidden by another window
206    private boolean mHidden = false;
207
208    /**
209     * Helps remember whether the screen has turned on since the last time
210     * it turned off due to timeout. see {@link #onScreenTurnedOff(int)}
211     */
212    private int mDelayedShowingSequence;
213
214    /**
215     * If the user has disabled the keyguard, then requests to exit, this is
216     * how we'll ultimately let them know whether it was successful.  We use this
217     * var being non-null as an indicator that there is an in progress request.
218     */
219    private IKeyguardExitCallback mExitSecureCallback;
220
221    // the properties of the keyguard
222
223    private KeyguardUpdateMonitor mUpdateMonitor;
224
225    private boolean mScreenOn;
226
227    // last known state of the cellular connection
228    private String mPhoneState = TelephonyManager.EXTRA_STATE_IDLE;
229
230    /**
231     * we send this intent when the keyguard is dismissed.
232     */
233    private static final Intent USER_PRESENT_INTENT = new Intent(Intent.ACTION_USER_PRESENT)
234            .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
235                    | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
236
237    /**
238     * {@link #setKeyguardEnabled} waits on this condition when it reenables
239     * the keyguard.
240     */
241    private boolean mWaitingUntilKeyguardVisible = false;
242    private LockPatternUtils mLockPatternUtils;
243    private boolean mKeyguardDonePending = false;
244
245    private SoundPool mLockSounds;
246    private int mLockSoundId;
247    private int mUnlockSoundId;
248    private int mLockSoundStreamId;
249
250    /**
251     * The volume applied to the lock/unlock sounds.
252     */
253    private final float mLockSoundVolume;
254
255    /**
256     * For managing external displays
257     */
258    private KeyguardDisplayManager mKeyguardDisplayManager;
259
260    /**
261     * Cache of avatar drawables, for use by KeyguardMultiUserAvatar.
262     */
263    private static MultiUserAvatarCache sMultiUserAvatarCache = new MultiUserAvatarCache();
264
265    /**
266     * The callback used by the keyguard view to tell the {@link KeyguardViewMediator}
267     * various things.
268     */
269    public interface ViewMediatorCallback {
270        /**
271         * Reports user activity and requests that the screen stay on.
272         */
273        void userActivity();
274
275        /**
276         * Reports user activity and requests that the screen stay on for at least
277         * the specified amount of time.
278         * @param millis The amount of time in millis.  This value is currently ignored.
279         */
280        void userActivity(long millis);
281
282        /**
283         * Report that the keyguard is done.
284         * @param authenticated Whether the user securely got past the keyguard.
285         *   the only reason for this to be false is if the keyguard was instructed
286         *   to appear temporarily to verify the user is supposed to get past the
287         *   keyguard, and the user fails to do so.
288         */
289        void keyguardDone(boolean authenticated);
290
291        /**
292         * Report that the keyguard is done drawing.
293         */
294        void keyguardDoneDrawing();
295
296        /**
297         * Tell ViewMediator that the current view needs IME input
298         * @param needsInput
299         */
300        void setNeedsInput(boolean needsInput);
301
302        /**
303         * Tell view mediator that the keyguard view's desired user activity timeout
304         * has changed and needs to be reapplied to the window.
305         */
306        void onUserActivityTimeoutChanged();
307
308        /**
309         * Report that the keyguard is dismissable, pending the next keyguardDone call.
310         */
311        void keyguardDonePending();
312
313        /**
314         * Report when keyguard is actually gone
315         */
316        void keyguardGone();
317    }
318
319    KeyguardUpdateMonitorCallback mUpdateCallback = new KeyguardUpdateMonitorCallback() {
320
321        @Override
322        public void onUserSwitching(int userId) {
323            // Note that the mLockPatternUtils user has already been updated from setCurrentUser.
324            // We need to force a reset of the views, since lockNow (called by
325            // ActivityManagerService) will not reconstruct the keyguard if it is already showing.
326            synchronized (KeyguardViewMediator.this) {
327                mSwitchingUser = true;
328                resetStateLocked(null);
329                adjustStatusBarLocked();
330                // When we switch users we want to bring the new user to the biometric unlock even
331                // if the current user has gone to the backup.
332                KeyguardUpdateMonitor.getInstance(mContext).setAlternateUnlockEnabled(true);
333            }
334        }
335
336        @Override
337        public void onUserSwitchComplete(int userId) {
338            mSwitchingUser = false;
339        }
340
341        @Override
342        public void onUserRemoved(int userId) {
343            mLockPatternUtils.removeUser(userId);
344            sMultiUserAvatarCache.clear(userId);
345        }
346
347        @Override
348        public void onUserInfoChanged(int userId) {
349            sMultiUserAvatarCache.clear(userId);
350        }
351
352        @Override
353        void onPhoneStateChanged(int phoneState) {
354            synchronized (KeyguardViewMediator.this) {
355                if (TelephonyManager.CALL_STATE_IDLE == phoneState  // call ending
356                        && !mScreenOn                           // screen off
357                        && mExternallyEnabled) {                // not disabled by any app
358
359                    // note: this is a way to gracefully reenable the keyguard when the call
360                    // ends and the screen is off without always reenabling the keyguard
361                    // each time the screen turns off while in call (and having an occasional ugly
362                    // flicker while turning back on the screen and disabling the keyguard again).
363                    if (DEBUG) Log.d(TAG, "screen is off and call ended, let's make sure the "
364                            + "keyguard is showing");
365                    doKeyguardLocked(null);
366                }
367            }
368        };
369
370        @Override
371        public void onClockVisibilityChanged() {
372            adjustStatusBarLocked();
373        }
374
375        @Override
376        public void onDeviceProvisioned() {
377            sendUserPresentBroadcast();
378        }
379
380        @Override
381        public void onSimStateChanged(IccCardConstants.State simState) {
382            if (DEBUG) Log.d(TAG, "onSimStateChanged: " + simState);
383
384            switch (simState) {
385                case NOT_READY:
386                case ABSENT:
387                    // only force lock screen in case of missing sim if user hasn't
388                    // gone through setup wizard
389                    synchronized (this) {
390                        if (!mUpdateMonitor.isDeviceProvisioned()) {
391                            if (!isShowing()) {
392                                if (DEBUG) Log.d(TAG, "ICC_ABSENT isn't showing,"
393                                        + " we need to show the keyguard since the "
394                                        + "device isn't provisioned yet.");
395                                doKeyguardLocked(null);
396                            } else {
397                                resetStateLocked(null);
398                            }
399                        }
400                    }
401                    break;
402                case PIN_REQUIRED:
403                case PUK_REQUIRED:
404                    synchronized (this) {
405                        if (!isShowing()) {
406                            if (DEBUG) Log.d(TAG, "INTENT_VALUE_ICC_LOCKED and keygaurd isn't "
407                                    + "showing; need to show keyguard so user can enter sim pin");
408                            doKeyguardLocked(null);
409                        } else {
410                            resetStateLocked(null);
411                        }
412                    }
413                    break;
414                case PERM_DISABLED:
415                    synchronized (this) {
416                        if (!isShowing()) {
417                            if (DEBUG) Log.d(TAG, "PERM_DISABLED and "
418                                  + "keygaurd isn't showing.");
419                            doKeyguardLocked(null);
420                        } else {
421                            if (DEBUG) Log.d(TAG, "PERM_DISABLED, resetStateLocked to"
422                                  + "show permanently disabled message in lockscreen.");
423                            resetStateLocked(null);
424                        }
425                    }
426                    break;
427                case READY:
428                    synchronized (this) {
429                        if (isShowing()) {
430                            resetStateLocked(null);
431                        }
432                    }
433                    break;
434            }
435        }
436
437    };
438
439    ViewMediatorCallback mViewMediatorCallback = new ViewMediatorCallback() {
440        public void userActivity() {
441            KeyguardViewMediator.this.userActivity();
442        }
443
444        public void userActivity(long holdMs) {
445            KeyguardViewMediator.this.userActivity(holdMs);
446        }
447
448        public void keyguardDone(boolean authenticated) {
449            KeyguardViewMediator.this.keyguardDone(authenticated, true);
450        }
451
452        public void keyguardDoneDrawing() {
453            mHandler.sendEmptyMessage(KEYGUARD_DONE_DRAWING);
454        }
455
456        @Override
457        public void setNeedsInput(boolean needsInput) {
458            mKeyguardViewManager.setNeedsInput(needsInput);
459        }
460
461        @Override
462        public void onUserActivityTimeoutChanged() {
463            mKeyguardViewManager.updateUserActivityTimeout();
464        }
465
466        @Override
467        public void keyguardDonePending() {
468            mKeyguardDonePending = true;
469        }
470
471        @Override
472        public void keyguardGone() {
473            mKeyguardDisplayManager.hide();
474        }
475    };
476
477    private void userActivity() {
478        userActivity(AWAKE_INTERVAL_DEFAULT_MS);
479    }
480
481    public void userActivity(long holdMs) {
482        // We ignore the hold time.  Eventually we should remove it.
483        // Instead, the keyguard window has an explicit user activity timeout set on it.
484        mPM.userActivity(SystemClock.uptimeMillis(), false);
485    }
486
487    /**
488     * Construct a KeyguardViewMediator
489     * @param context
490     * @param lockPatternUtils optional mock interface for LockPatternUtils
491     */
492    public KeyguardViewMediator(Context context, LockPatternUtils lockPatternUtils) {
493        mContext = context;
494        mPM = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
495        mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
496        mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "show keyguard");
497        mShowKeyguardWakeLock.setReferenceCounted(false);
498
499        mContext.registerReceiver(mBroadcastReceiver, new IntentFilter(DELAYED_KEYGUARD_ACTION));
500
501        mKeyguardDisplayManager = new KeyguardDisplayManager(context);
502
503        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
504
505        mUpdateMonitor = KeyguardUpdateMonitor.getInstance(context);
506
507        mLockPatternUtils = lockPatternUtils != null
508                ? lockPatternUtils : new LockPatternUtils(mContext);
509        mLockPatternUtils.setCurrentUser(UserHandle.USER_OWNER);
510
511        WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
512
513        mKeyguardViewManager = new KeyguardViewManager(context, wm, mViewMediatorCallback,
514                mLockPatternUtils);
515
516        final ContentResolver cr = mContext.getContentResolver();
517
518        mScreenOn = mPM.isScreenOn();
519
520        mLockSounds = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
521        String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND);
522        if (soundPath != null) {
523            mLockSoundId = mLockSounds.load(soundPath, 1);
524        }
525        if (soundPath == null || mLockSoundId == 0) {
526            Log.w(TAG, "failed to load lock sound from " + soundPath);
527        }
528        soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND);
529        if (soundPath != null) {
530            mUnlockSoundId = mLockSounds.load(soundPath, 1);
531        }
532        if (soundPath == null || mUnlockSoundId == 0) {
533            Log.w(TAG, "failed to load unlock sound from " + soundPath);
534        }
535        int lockSoundDefaultAttenuation = context.getResources().getInteger(
536                com.android.internal.R.integer.config_lockSoundVolumeDb);
537        mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20);
538    }
539
540    /**
541     * Let us know that the system is ready after startup.
542     */
543    public void onSystemReady() {
544        mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
545        synchronized (this) {
546            if (DEBUG) Log.d(TAG, "onSystemReady");
547            mSystemReady = true;
548            mUpdateMonitor.registerCallback(mUpdateCallback);
549
550            // Suppress biometric unlock right after boot until things have settled if it is the
551            // selected security method, otherwise unsuppress it.  It must be unsuppressed if it is
552            // not the selected security method for the following reason:  if the user starts
553            // without a screen lock selected, the biometric unlock would be suppressed the first
554            // time they try to use it.
555            //
556            // Note that the biometric unlock will still not show if it is not the selected method.
557            // Calling setAlternateUnlockEnabled(true) simply says don't suppress it if it is the
558            // selected method.
559            if (mLockPatternUtils.usingBiometricWeak()
560                    && mLockPatternUtils.isBiometricWeakInstalled()) {
561                if (DEBUG) Log.d(TAG, "suppressing biometric unlock during boot");
562                mUpdateMonitor.setAlternateUnlockEnabled(false);
563            } else {
564                mUpdateMonitor.setAlternateUnlockEnabled(true);
565            }
566
567            doKeyguardLocked(null);
568        }
569        // Most services aren't available until the system reaches the ready state, so we
570        // send it here when the device first boots.
571        maybeSendUserPresentBroadcast();
572    }
573
574    /**
575     * Called to let us know the screen was turned off.
576     * @param why either {@link WindowManagerPolicy#OFF_BECAUSE_OF_USER},
577     *   {@link WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT} or
578     *   {@link WindowManagerPolicy#OFF_BECAUSE_OF_PROX_SENSOR}.
579     */
580    public void onScreenTurnedOff(int why) {
581        synchronized (this) {
582            mScreenOn = false;
583            if (DEBUG) Log.d(TAG, "onScreenTurnedOff(" + why + ")");
584
585            mKeyguardDonePending = false;
586
587            // Lock immediately based on setting if secure (user has a pin/pattern/password).
588            // This also "locks" the device when not secure to provide easy access to the
589            // camera while preventing unwanted input.
590            final boolean lockImmediately =
591                mLockPatternUtils.getPowerButtonInstantlyLocks() || !mLockPatternUtils.isSecure();
592
593            if (mExitSecureCallback != null) {
594                if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
595                try {
596                    mExitSecureCallback.onKeyguardExitResult(false);
597                } catch (RemoteException e) {
598                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
599                }
600                mExitSecureCallback = null;
601                if (!mExternallyEnabled) {
602                    hideLocked();
603                }
604            } else if (mShowing) {
605                notifyScreenOffLocked();
606                resetStateLocked(null);
607            } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT
608                   || (why == WindowManagerPolicy.OFF_BECAUSE_OF_USER && !lockImmediately)) {
609                doKeyguardLaterLocked();
610            } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
611                // Do not enable the keyguard if the prox sensor forced the screen off.
612            } else {
613                doKeyguardLocked(null);
614            }
615        }
616        KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurndOff(why);
617        mKeyguardDisplayManager.show();
618    }
619
620    private void doKeyguardLaterLocked() {
621        // if the screen turned off because of timeout or the user hit the power button
622        // and we don't need to lock immediately, set an alarm
623        // to enable it a little bit later (i.e, give the user a chance
624        // to turn the screen back on within a certain window without
625        // having to unlock the screen)
626        final ContentResolver cr = mContext.getContentResolver();
627
628        // From DisplaySettings
629        long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
630                KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);
631
632        // From SecuritySettings
633        final long lockAfterTimeout = Settings.Secure.getInt(cr,
634                Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
635                KEYGUARD_LOCK_AFTER_DELAY_DEFAULT);
636
637        // From DevicePolicyAdmin
638        final long policyTimeout = mLockPatternUtils.getDevicePolicyManager()
639                .getMaximumTimeToLock(null, mLockPatternUtils.getCurrentUser());
640
641        long timeout;
642        if (policyTimeout > 0) {
643            // policy in effect. Make sure we don't go beyond policy limit.
644            displayTimeout = Math.max(displayTimeout, 0); // ignore negative values
645            timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);
646        } else {
647            timeout = lockAfterTimeout;
648        }
649
650        if (timeout <= 0) {
651            // Lock now
652            mSuppressNextLockSound = true;
653            doKeyguardLocked(null);
654        } else {
655            // Lock in the future
656            long when = SystemClock.elapsedRealtime() + timeout;
657            Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
658            intent.putExtra("seq", mDelayedShowingSequence);
659            PendingIntent sender = PendingIntent.getBroadcast(mContext,
660                    0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
661            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender);
662            if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = "
663                             + mDelayedShowingSequence);
664        }
665    }
666
667    private void cancelDoKeyguardLaterLocked() {
668        mDelayedShowingSequence++;
669    }
670
671    /**
672     * Let's us know the screen was turned on.
673     */
674    public void onScreenTurnedOn(IKeyguardShowCallback callback) {
675        synchronized (this) {
676            mScreenOn = true;
677            cancelDoKeyguardLaterLocked();
678            if (DEBUG) Log.d(TAG, "onScreenTurnedOn, seq = " + mDelayedShowingSequence);
679            if (callback != null) {
680                notifyScreenOnLocked(callback);
681            }
682        }
683        KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurnedOn();
684        maybeSendUserPresentBroadcast();
685    }
686
687    private void maybeSendUserPresentBroadcast() {
688        if (mSystemReady && mLockPatternUtils.isLockScreenDisabled()
689                && mUserManager.getUsers(true).size() == 1) {
690            // Lock screen is disabled because the user has set the preference to "None".
691            // In this case, send out ACTION_USER_PRESENT here instead of in
692            // handleKeyguardDone()
693            sendUserPresentBroadcast();
694        }
695    }
696
697    /**
698     * A dream started.  We should lock after the usual screen-off lock timeout but only
699     * if there is a secure lock pattern.
700     */
701    public void onDreamingStarted() {
702        synchronized (this) {
703            if (mScreenOn && mLockPatternUtils.isSecure()) {
704                doKeyguardLaterLocked();
705            }
706        }
707    }
708
709    /**
710     * A dream stopped.
711     */
712    public void onDreamingStopped() {
713        synchronized (this) {
714            if (mScreenOn) {
715                cancelDoKeyguardLaterLocked();
716            }
717        }
718    }
719
720    /**
721     * Same semantics as {@link WindowManagerPolicy#enableKeyguard}; provide
722     * a way for external stuff to override normal keyguard behavior.  For instance
723     * the phone app disables the keyguard when it receives incoming calls.
724     */
725    public void setKeyguardEnabled(boolean enabled) {
726        synchronized (this) {
727            if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
728
729            mExternallyEnabled = enabled;
730
731            if (!enabled && mShowing) {
732                if (mExitSecureCallback != null) {
733                    if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
734                    // we're in the process of handling a request to verify the user
735                    // can get past the keyguard. ignore extraneous requests to disable / reenable
736                    return;
737                }
738
739                // hiding keyguard that is showing, remember to reshow later
740                if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
741                        + "disabling status bar expansion");
742                mNeedToReshowWhenReenabled = true;
743                hideLocked();
744            } else if (enabled && mNeedToReshowWhenReenabled) {
745                // reenabled after previously hidden, reshow
746                if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
747                        + "status bar expansion");
748                mNeedToReshowWhenReenabled = false;
749
750                if (mExitSecureCallback != null) {
751                    if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
752                    try {
753                        mExitSecureCallback.onKeyguardExitResult(false);
754                    } catch (RemoteException e) {
755                        Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
756                    }
757                    mExitSecureCallback = null;
758                    resetStateLocked(null);
759                } else {
760                    showLocked(null);
761
762                    // block until we know the keygaurd is done drawing (and post a message
763                    // to unblock us after a timeout so we don't risk blocking too long
764                    // and causing an ANR).
765                    mWaitingUntilKeyguardVisible = true;
766                    mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
767                    if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
768                    while (mWaitingUntilKeyguardVisible) {
769                        try {
770                            wait();
771                        } catch (InterruptedException e) {
772                            Thread.currentThread().interrupt();
773                        }
774                    }
775                    if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
776                }
777            }
778        }
779    }
780
781    /**
782     * @see android.app.KeyguardManager#exitKeyguardSecurely
783     */
784    public void verifyUnlock(IKeyguardExitCallback callback) {
785        synchronized (this) {
786            if (DEBUG) Log.d(TAG, "verifyUnlock");
787            if (!mUpdateMonitor.isDeviceProvisioned()) {
788                // don't allow this api when the device isn't provisioned
789                if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
790                try {
791                    callback.onKeyguardExitResult(false);
792                } catch (RemoteException e) {
793                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
794                }
795            } else if (mExternallyEnabled) {
796                // this only applies when the user has externally disabled the
797                // keyguard.  this is unexpected and means the user is not
798                // using the api properly.
799                Log.w(TAG, "verifyUnlock called when not externally disabled");
800                try {
801                    callback.onKeyguardExitResult(false);
802                } catch (RemoteException e) {
803                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
804                }
805            } else if (mExitSecureCallback != null) {
806                // already in progress with someone else
807                try {
808                    callback.onKeyguardExitResult(false);
809                } catch (RemoteException e) {
810                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
811                }
812            } else {
813                mExitSecureCallback = callback;
814                verifyUnlockLocked();
815            }
816        }
817    }
818
819    /**
820     * Is the keyguard currently showing?
821     */
822    public boolean isShowing() {
823        return mShowing;
824    }
825
826    /**
827     * Is the keyguard currently showing and not being force hidden?
828     */
829    public boolean isShowingAndNotHidden() {
830        return mShowing && !mHidden;
831    }
832
833    /**
834     * Notify us when the keyguard is hidden by another window
835     */
836    public void setHidden(boolean isHidden) {
837        if (DEBUG) Log.d(TAG, "setHidden " + isHidden);
838        mUpdateMonitor.sendKeyguardVisibilityChanged(!isHidden);
839        mHandler.removeMessages(SET_HIDDEN);
840        Message msg = mHandler.obtainMessage(SET_HIDDEN, (isHidden ? 1 : 0), 0);
841        mHandler.sendMessage(msg);
842    }
843
844    /**
845     * Handles SET_HIDDEN message sent by setHidden()
846     */
847    private void handleSetHidden(boolean isHidden) {
848        synchronized (KeyguardViewMediator.this) {
849            if (mHidden != isHidden) {
850                mHidden = isHidden;
851                updateActivityLockScreenState();
852                adjustStatusBarLocked();
853            }
854        }
855    }
856
857    /**
858     * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout.
859     * This must be safe to call from any thread and with any window manager locks held.
860     */
861    public void doKeyguardTimeout(Bundle options) {
862        mHandler.removeMessages(KEYGUARD_TIMEOUT);
863        Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
864        mHandler.sendMessage(msg);
865    }
866
867    /**
868     * Given the state of the keyguard, is the input restricted?
869     * Input is restricted when the keyguard is showing, or when the keyguard
870     * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.
871     */
872    public boolean isInputRestricted() {
873        return mShowing || mNeedToReshowWhenReenabled || !mUpdateMonitor.isDeviceProvisioned();
874    }
875
876    /**
877     * Enable the keyguard if the settings are appropriate.
878     */
879    private void doKeyguardLocked(Bundle options) {
880        // if another app is disabling us, don't show
881        if (!mExternallyEnabled) {
882            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");
883
884            // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes
885            // for an occasional ugly flicker in this situation:
886            // 1) receive a call with the screen on (no keyguard) or make a call
887            // 2) screen times out
888            // 3) user hits key to turn screen back on
889            // instead, we reenable the keyguard when we know the screen is off and the call
890            // ends (see the broadcast receiver below)
891            // TODO: clean this up when we have better support at the window manager level
892            // for apps that wish to be on top of the keyguard
893            return;
894        }
895
896        // if the keyguard is already showing, don't bother
897        if (mKeyguardViewManager.isShowing()) {
898            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
899            return;
900        }
901
902        // if the setup wizard hasn't run yet, don't show
903        final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim",
904                false);
905        final boolean provisioned = mUpdateMonitor.isDeviceProvisioned();
906        final IccCardConstants.State state = mUpdateMonitor.getSimState();
907        final boolean lockedOrMissing = state.isPinLocked()
908                || ((state == IccCardConstants.State.ABSENT
909                || state == IccCardConstants.State.PERM_DISABLED)
910                && requireSim);
911
912        if (!lockedOrMissing && !provisioned) {
913            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
914                    + " and the sim is not locked or missing");
915            return;
916        }
917
918        if (mUserManager.getUsers(true).size() < 2
919                && mLockPatternUtils.isLockScreenDisabled() && !lockedOrMissing) {
920            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
921            return;
922        }
923
924        if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
925        showLocked(options);
926    }
927
928    /**
929     * Dismiss the keyguard through the security layers.
930     */
931    public void handleDismiss() {
932        if (mShowing && !mHidden) {
933            mKeyguardViewManager.dismiss();
934        }
935    }
936
937    public void dismiss() {
938        mHandler.sendEmptyMessage(DISMISS);
939    }
940
941    /**
942     * Send message to keyguard telling it to reset its state.
943     * @param options options about how to show the keyguard
944     * @see #handleReset()
945     */
946    private void resetStateLocked(Bundle options) {
947        if (DEBUG) Log.e(TAG, "resetStateLocked");
948        Message msg = mHandler.obtainMessage(RESET, options);
949        mHandler.sendMessage(msg);
950    }
951
952    /**
953     * Send message to keyguard telling it to verify unlock
954     * @see #handleVerifyUnlock()
955     */
956    private void verifyUnlockLocked() {
957        if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
958        mHandler.sendEmptyMessage(VERIFY_UNLOCK);
959    }
960
961
962    /**
963     * Send a message to keyguard telling it the screen just turned on.
964     * @see #onScreenTurnedOff(int)
965     * @see #handleNotifyScreenOff
966     */
967    private void notifyScreenOffLocked() {
968        if (DEBUG) Log.d(TAG, "notifyScreenOffLocked");
969        mHandler.sendEmptyMessage(NOTIFY_SCREEN_OFF);
970    }
971
972    /**
973     * Send a message to keyguard telling it the screen just turned on.
974     * @see #onScreenTurnedOn()
975     * @see #handleNotifyScreenOn
976     */
977    private void notifyScreenOnLocked(IKeyguardShowCallback result) {
978        if (DEBUG) Log.d(TAG, "notifyScreenOnLocked");
979        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_ON, result);
980        mHandler.sendMessage(msg);
981    }
982
983    /**
984     * Send message to keyguard telling it to show itself
985     * @see #handleShow()
986     */
987    private void showLocked(Bundle options) {
988        if (DEBUG) Log.d(TAG, "showLocked");
989        // ensure we stay awake until we are finished displaying the keyguard
990        mShowKeyguardWakeLock.acquire();
991        Message msg = mHandler.obtainMessage(SHOW, options);
992        mHandler.sendMessage(msg);
993    }
994
995    /**
996     * Send message to keyguard telling it to hide itself
997     * @see #handleHide()
998     */
999    private void hideLocked() {
1000        if (DEBUG) Log.d(TAG, "hideLocked");
1001        Message msg = mHandler.obtainMessage(HIDE);
1002        mHandler.sendMessage(msg);
1003    }
1004
1005    public boolean isSecure() {
1006        return mLockPatternUtils.isSecure()
1007            || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
1008    }
1009
1010    /**
1011     * Update the newUserId. Call while holding WindowManagerService lock.
1012     * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.
1013     *
1014     * @param newUserId The id of the incoming user.
1015     */
1016    public void setCurrentUser(int newUserId) {
1017        mLockPatternUtils.setCurrentUser(newUserId);
1018    }
1019
1020    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1021        @Override
1022        public void onReceive(Context context, Intent intent) {
1023            if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {
1024                final int sequence = intent.getIntExtra("seq", 0);
1025                if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
1026                        + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
1027                synchronized (KeyguardViewMediator.this) {
1028                    if (mDelayedShowingSequence == sequence) {
1029                        // Don't play lockscreen SFX if the screen went off due to timeout.
1030                        mSuppressNextLockSound = true;
1031                        doKeyguardLocked(null);
1032                    }
1033                }
1034            }
1035        }
1036    };
1037
1038    public void keyguardDone(boolean authenticated, boolean wakeup) {
1039        if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated + ")");
1040        EventLog.writeEvent(70000, 2);
1041        synchronized (this) {
1042            mKeyguardDonePending = false;
1043        }
1044        Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0, wakeup ? 1 : 0);
1045        mHandler.sendMessage(msg);
1046    }
1047
1048    /**
1049     * This handler will be associated with the policy thread, which will also
1050     * be the UI thread of the keyguard.  Since the apis of the policy, and therefore
1051     * this class, can be called by other threads, any action that directly
1052     * interacts with the keyguard ui should be posted to this handler, rather
1053     * than called directly.
1054     */
1055    private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
1056        @Override
1057        public void handleMessage(Message msg) {
1058            switch (msg.what) {
1059                case SHOW:
1060                    handleShow((Bundle) msg.obj);
1061                    break;
1062                case HIDE:
1063                    handleHide();
1064                    break;
1065                case RESET:
1066                    handleReset((Bundle) msg.obj);
1067                    break;
1068                case VERIFY_UNLOCK:
1069                    handleVerifyUnlock();
1070                    break;
1071                case NOTIFY_SCREEN_OFF:
1072                    handleNotifyScreenOff();
1073                    break;
1074                case NOTIFY_SCREEN_ON:
1075                    handleNotifyScreenOn((IKeyguardShowCallback) msg.obj);
1076                    break;
1077                case KEYGUARD_DONE:
1078                    handleKeyguardDone(msg.arg1 != 0, msg.arg2 != 0);
1079                    break;
1080                case KEYGUARD_DONE_DRAWING:
1081                    handleKeyguardDoneDrawing();
1082                    break;
1083                case KEYGUARD_DONE_AUTHENTICATING:
1084                    keyguardDone(true, true);
1085                    break;
1086                case SET_HIDDEN:
1087                    handleSetHidden(msg.arg1 != 0);
1088                    break;
1089                case KEYGUARD_TIMEOUT:
1090                    synchronized (KeyguardViewMediator.this) {
1091                        doKeyguardLocked((Bundle) msg.obj);
1092                    }
1093                    break;
1094                case SHOW_ASSISTANT:
1095                    handleShowAssistant();
1096                    break;
1097                case DISPATCH_EVENT:
1098                    handleDispatchEvent((MotionEvent) msg.obj);
1099                    break;
1100                case LAUNCH_CAMERA:
1101                    handleLaunchCamera();
1102                    break;
1103                case DISMISS:
1104                    handleDismiss();
1105                    break;
1106            }
1107        }
1108    };
1109
1110    /**
1111     * @see #keyguardDone
1112     * @see #KEYGUARD_DONE
1113     */
1114    private void handleKeyguardDone(boolean authenticated, boolean wakeup) {
1115        if (DEBUG) Log.d(TAG, "handleKeyguardDone");
1116
1117        if (authenticated) {
1118            mUpdateMonitor.clearFailedUnlockAttempts();
1119        }
1120
1121        if (mExitSecureCallback != null) {
1122            try {
1123                mExitSecureCallback.onKeyguardExitResult(authenticated);
1124            } catch (RemoteException e) {
1125                Slog.w(TAG, "Failed to call onKeyguardExitResult(" + authenticated + ")", e);
1126            }
1127
1128            mExitSecureCallback = null;
1129
1130            if (authenticated) {
1131                // after succesfully exiting securely, no need to reshow
1132                // the keyguard when they've released the lock
1133                mExternallyEnabled = true;
1134                mNeedToReshowWhenReenabled = false;
1135            }
1136        }
1137
1138        handleHide();
1139        sendUserPresentBroadcast();
1140    }
1141
1142    protected void handleLaunchCamera() {
1143        mKeyguardViewManager.launchCamera();
1144    }
1145
1146    protected void handleDispatchEvent(MotionEvent event) {
1147        mKeyguardViewManager.dispatch(event);
1148    }
1149
1150    private void sendUserPresentBroadcast() {
1151        final UserHandle currentUser = new UserHandle(mLockPatternUtils.getCurrentUser());
1152        mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, currentUser);
1153    }
1154
1155    /**
1156     * @see #keyguardDoneDrawing
1157     * @see #KEYGUARD_DONE_DRAWING
1158     */
1159    private void handleKeyguardDoneDrawing() {
1160        synchronized(this) {
1161            if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing");
1162            if (mWaitingUntilKeyguardVisible) {
1163                if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
1164                mWaitingUntilKeyguardVisible = false;
1165                notifyAll();
1166
1167                // there will usually be two of these sent, one as a timeout, and one
1168                // as a result of the callback, so remove any remaining messages from
1169                // the queue
1170                mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
1171            }
1172        }
1173    }
1174
1175    private void playSounds(boolean locked) {
1176        // User feedback for keyguard.
1177
1178        if (mSuppressNextLockSound) {
1179            mSuppressNextLockSound = false;
1180            return;
1181        }
1182
1183        final ContentResolver cr = mContext.getContentResolver();
1184        if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
1185            final int whichSound = locked
1186                ? mLockSoundId
1187                : mUnlockSoundId;
1188            mLockSounds.stop(mLockSoundStreamId);
1189            // Init mAudioManager
1190            if (mAudioManager == null) {
1191                mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
1192                if (mAudioManager == null) return;
1193                mMasterStreamType = mAudioManager.getMasterStreamType();
1194            }
1195            // If the stream is muted, don't play the sound
1196            if (mAudioManager.isStreamMute(mMasterStreamType)) return;
1197
1198            mLockSoundStreamId = mLockSounds.play(whichSound,
1199                    mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
1200        }
1201    }
1202
1203    private void updateActivityLockScreenState() {
1204        try {
1205            ActivityManagerNative.getDefault().setLockScreenShown(mShowing && !mHidden);
1206        } catch (RemoteException e) {
1207        }
1208    }
1209
1210    /**
1211     * Handle message sent by {@link #showLocked}.
1212     * @see #SHOW
1213     */
1214    private void handleShow(Bundle options) {
1215        synchronized (KeyguardViewMediator.this) {
1216            if (!mSystemReady) {
1217                if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready.");
1218                return;
1219            } else {
1220                if (DEBUG) Log.d(TAG, "handleShow");
1221            }
1222
1223            mKeyguardViewManager.show(options);
1224            mShowing = true;
1225            mKeyguardDonePending = false;
1226            updateActivityLockScreenState();
1227            adjustStatusBarLocked();
1228            userActivity();
1229            try {
1230                ActivityManagerNative.getDefault().closeSystemDialogs("lock");
1231            } catch (RemoteException e) {
1232            }
1233
1234            // Do this at the end to not slow down display of the keyguard.
1235            playSounds(true);
1236
1237            mShowKeyguardWakeLock.release();
1238        }
1239        mKeyguardDisplayManager.show();
1240    }
1241
1242    /**
1243     * Handle message sent by {@link #hideLocked()}
1244     * @see #HIDE
1245     */
1246    private void handleHide() {
1247        synchronized (KeyguardViewMediator.this) {
1248            if (DEBUG) Log.d(TAG, "handleHide");
1249
1250            // only play "unlock" noises if not on a call (since the incall UI
1251            // disables the keyguard)
1252            if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
1253                playSounds(false);
1254            }
1255
1256            mKeyguardViewManager.hide();
1257            mShowing = false;
1258            mKeyguardDonePending = false;
1259            updateActivityLockScreenState();
1260            adjustStatusBarLocked();
1261        }
1262    }
1263
1264    private void adjustStatusBarLocked() {
1265        if (mStatusBarManager == null) {
1266            mStatusBarManager = (StatusBarManager)
1267                    mContext.getSystemService(Context.STATUS_BAR_SERVICE);
1268        }
1269        if (mStatusBarManager == null) {
1270            Log.w(TAG, "Could not get status bar manager");
1271        } else {
1272            // Disable aspects of the system/status/navigation bars that must not be re-enabled by
1273            // windows that appear on top, ever
1274            int flags = StatusBarManager.DISABLE_NONE;
1275            if (mShowing) {
1276                // Permanently disable components not available when keyguard is enabled
1277                // (like recents). Temporary enable/disable (e.g. the "back" button) are
1278                // done in KeyguardHostView.
1279                flags |= StatusBarManager.DISABLE_RECENT;
1280                if (isSecure() || !ENABLE_INSECURE_STATUS_BAR_EXPAND) {
1281                    // showing secure lockscreen; disable expanding.
1282                    flags |= StatusBarManager.DISABLE_EXPAND;
1283                }
1284                if (isSecure()) {
1285                    // showing secure lockscreen; disable ticker.
1286                    flags |= StatusBarManager.DISABLE_NOTIFICATION_TICKER;
1287                }
1288                if (!isAssistantAvailable()) {
1289                    flags |= StatusBarManager.DISABLE_SEARCH;
1290                }
1291            }
1292
1293            if (DEBUG) {
1294                Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mHidden=" + mHidden
1295                        + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
1296            }
1297
1298            if (!(mContext instanceof Activity)) {
1299                mStatusBarManager.disable(flags);
1300            }
1301        }
1302    }
1303
1304    /**
1305     * Handle message sent by {@link #resetStateLocked(Bundle)}
1306     * @see #RESET
1307     */
1308    private void handleReset(Bundle options) {
1309        if (options == null) {
1310            options = new Bundle();
1311        }
1312        options.putBoolean(KeyguardViewManager.IS_SWITCHING_USER, mSwitchingUser);
1313        synchronized (KeyguardViewMediator.this) {
1314            if (DEBUG) Log.d(TAG, "handleReset");
1315            mKeyguardViewManager.reset(options);
1316        }
1317    }
1318
1319    /**
1320     * Handle message sent by {@link #verifyUnlock}
1321     * @see #VERIFY_UNLOCK
1322     */
1323    private void handleVerifyUnlock() {
1324        synchronized (KeyguardViewMediator.this) {
1325            if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
1326            mKeyguardViewManager.verifyUnlock();
1327            mShowing = true;
1328            updateActivityLockScreenState();
1329        }
1330    }
1331
1332    /**
1333     * Handle message sent by {@link #notifyScreenOffLocked()}
1334     * @see #NOTIFY_SCREEN_OFF
1335     */
1336    private void handleNotifyScreenOff() {
1337        synchronized (KeyguardViewMediator.this) {
1338            if (DEBUG) Log.d(TAG, "handleNotifyScreenOff");
1339            mKeyguardViewManager.onScreenTurnedOff();
1340        }
1341    }
1342
1343    /**
1344     * Handle message sent by {@link #notifyScreenOnLocked()}
1345     * @see #NOTIFY_SCREEN_ON
1346     */
1347    private void handleNotifyScreenOn(IKeyguardShowCallback callback) {
1348        synchronized (KeyguardViewMediator.this) {
1349            if (DEBUG) Log.d(TAG, "handleNotifyScreenOn");
1350            mKeyguardViewManager.onScreenTurnedOn(callback);
1351        }
1352    }
1353
1354    public boolean isDismissable() {
1355        return mKeyguardDonePending || !isSecure();
1356    }
1357
1358    public void showAssistant() {
1359        Message msg = mHandler.obtainMessage(SHOW_ASSISTANT);
1360        mHandler.sendMessage(msg);
1361    }
1362
1363    public void handleShowAssistant() {
1364        mKeyguardViewManager.showAssistant();
1365    }
1366
1367    private boolean isAssistantAvailable() {
1368        return mSearchManager != null
1369                && mSearchManager.getAssistIntent(mContext, false, UserHandle.USER_CURRENT) != null;
1370    }
1371
1372    public static MultiUserAvatarCache getAvatarCache() {
1373        return sMultiUserAvatarCache;
1374    }
1375
1376    public void dispatch(MotionEvent event) {
1377        Message msg = mHandler.obtainMessage(DISPATCH_EVENT, event);
1378        mHandler.sendMessage(msg);
1379    }
1380
1381    public void launchCamera() {
1382        Message msg = mHandler.obtainMessage(LAUNCH_CAMERA);
1383        mHandler.sendMessage(msg);
1384    }
1385
1386    public void onBootCompleted() {
1387        mUpdateMonitor.dispatchBootCompleted();
1388    }
1389}
1390