KeyguardViewMediator.java revision 299422baebe1b4c1bc2378f184b014a899dfe6ab
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;
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        // Assume keyguard is showing (unless it's disabled) until we know for sure...
512        mShowing = (mUpdateMonitor.isDeviceProvisioned() || mLockPatternUtils.isSecure())
513                && !mLockPatternUtils.isLockScreenDisabled();
514
515        WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
516
517        mKeyguardViewManager = new KeyguardViewManager(context, wm, mViewMediatorCallback,
518                mLockPatternUtils);
519
520        final ContentResolver cr = mContext.getContentResolver();
521
522        mScreenOn = mPM.isScreenOn();
523
524        mLockSounds = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
525        String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND);
526        if (soundPath != null) {
527            mLockSoundId = mLockSounds.load(soundPath, 1);
528        }
529        if (soundPath == null || mLockSoundId == 0) {
530            Log.w(TAG, "failed to load lock sound from " + soundPath);
531        }
532        soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND);
533        if (soundPath != null) {
534            mUnlockSoundId = mLockSounds.load(soundPath, 1);
535        }
536        if (soundPath == null || mUnlockSoundId == 0) {
537            Log.w(TAG, "failed to load unlock sound from " + soundPath);
538        }
539        int lockSoundDefaultAttenuation = context.getResources().getInteger(
540                com.android.internal.R.integer.config_lockSoundVolumeDb);
541        mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20);
542    }
543
544    /**
545     * Let us know that the system is ready after startup.
546     */
547    public void onSystemReady() {
548        mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
549        synchronized (this) {
550            if (DEBUG) Log.d(TAG, "onSystemReady");
551            mSystemReady = true;
552            mUpdateMonitor.registerCallback(mUpdateCallback);
553
554            // Suppress biometric unlock right after boot until things have settled if it is the
555            // selected security method, otherwise unsuppress it.  It must be unsuppressed if it is
556            // not the selected security method for the following reason:  if the user starts
557            // without a screen lock selected, the biometric unlock would be suppressed the first
558            // time they try to use it.
559            //
560            // Note that the biometric unlock will still not show if it is not the selected method.
561            // Calling setAlternateUnlockEnabled(true) simply says don't suppress it if it is the
562            // selected method.
563            if (mLockPatternUtils.usingBiometricWeak()
564                    && mLockPatternUtils.isBiometricWeakInstalled()) {
565                if (DEBUG) Log.d(TAG, "suppressing biometric unlock during boot");
566                mUpdateMonitor.setAlternateUnlockEnabled(false);
567            } else {
568                mUpdateMonitor.setAlternateUnlockEnabled(true);
569            }
570
571            doKeyguardLocked(null);
572        }
573        // Most services aren't available until the system reaches the ready state, so we
574        // send it here when the device first boots.
575        maybeSendUserPresentBroadcast();
576    }
577
578    /**
579     * Called to let us know the screen was turned off.
580     * @param why either {@link WindowManagerPolicy#OFF_BECAUSE_OF_USER},
581     *   {@link WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT} or
582     *   {@link WindowManagerPolicy#OFF_BECAUSE_OF_PROX_SENSOR}.
583     */
584    public void onScreenTurnedOff(int why) {
585        synchronized (this) {
586            mScreenOn = false;
587            if (DEBUG) Log.d(TAG, "onScreenTurnedOff(" + why + ")");
588
589            mKeyguardDonePending = false;
590
591            // Lock immediately based on setting if secure (user has a pin/pattern/password).
592            // This also "locks" the device when not secure to provide easy access to the
593            // camera while preventing unwanted input.
594            final boolean lockImmediately =
595                mLockPatternUtils.getPowerButtonInstantlyLocks() || !mLockPatternUtils.isSecure();
596
597            if (mExitSecureCallback != null) {
598                if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
599                try {
600                    mExitSecureCallback.onKeyguardExitResult(false);
601                } catch (RemoteException e) {
602                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
603                }
604                mExitSecureCallback = null;
605                if (!mExternallyEnabled) {
606                    hideLocked();
607                }
608            } else if (mShowing) {
609                notifyScreenOffLocked();
610                resetStateLocked(null);
611            } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT
612                   || (why == WindowManagerPolicy.OFF_BECAUSE_OF_USER && !lockImmediately)) {
613                doKeyguardLaterLocked();
614            } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
615                // Do not enable the keyguard if the prox sensor forced the screen off.
616            } else {
617                doKeyguardLocked(null);
618            }
619        }
620        KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurndOff(why);
621
622        // This needs to run on the UI thread
623        mHandler.post(new Runnable() {
624            @Override
625            public void run() {
626                mKeyguardDisplayManager.show();
627            }
628        });
629    }
630
631    private void doKeyguardLaterLocked() {
632        // if the screen turned off because of timeout or the user hit the power button
633        // and we don't need to lock immediately, set an alarm
634        // to enable it a little bit later (i.e, give the user a chance
635        // to turn the screen back on within a certain window without
636        // having to unlock the screen)
637        final ContentResolver cr = mContext.getContentResolver();
638
639        // From DisplaySettings
640        long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
641                KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);
642
643        // From SecuritySettings
644        final long lockAfterTimeout = Settings.Secure.getInt(cr,
645                Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
646                KEYGUARD_LOCK_AFTER_DELAY_DEFAULT);
647
648        // From DevicePolicyAdmin
649        final long policyTimeout = mLockPatternUtils.getDevicePolicyManager()
650                .getMaximumTimeToLock(null, mLockPatternUtils.getCurrentUser());
651
652        long timeout;
653        if (policyTimeout > 0) {
654            // policy in effect. Make sure we don't go beyond policy limit.
655            displayTimeout = Math.max(displayTimeout, 0); // ignore negative values
656            timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);
657        } else {
658            timeout = lockAfterTimeout;
659        }
660
661        if (timeout <= 0) {
662            // Lock now
663            mSuppressNextLockSound = true;
664            doKeyguardLocked(null);
665        } else {
666            // Lock in the future
667            long when = SystemClock.elapsedRealtime() + timeout;
668            Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
669            intent.putExtra("seq", mDelayedShowingSequence);
670            PendingIntent sender = PendingIntent.getBroadcast(mContext,
671                    0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
672            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender);
673            if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = "
674                             + mDelayedShowingSequence);
675        }
676    }
677
678    private void cancelDoKeyguardLaterLocked() {
679        mDelayedShowingSequence++;
680    }
681
682    /**
683     * Let's us know the screen was turned on.
684     */
685    public void onScreenTurnedOn(IKeyguardShowCallback callback) {
686        synchronized (this) {
687            mScreenOn = true;
688            cancelDoKeyguardLaterLocked();
689            if (DEBUG) Log.d(TAG, "onScreenTurnedOn, seq = " + mDelayedShowingSequence);
690            if (callback != null) {
691                notifyScreenOnLocked(callback);
692            }
693        }
694        KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurnedOn();
695        maybeSendUserPresentBroadcast();
696    }
697
698    private void maybeSendUserPresentBroadcast() {
699        if (mSystemReady && mLockPatternUtils.isLockScreenDisabled()
700                && mUserManager.getUsers(true).size() == 1) {
701            // Lock screen is disabled because the user has set the preference to "None".
702            // In this case, send out ACTION_USER_PRESENT here instead of in
703            // handleKeyguardDone()
704            sendUserPresentBroadcast();
705        }
706    }
707
708    /**
709     * A dream started.  We should lock after the usual screen-off lock timeout but only
710     * if there is a secure lock pattern.
711     */
712    public void onDreamingStarted() {
713        synchronized (this) {
714            if (mScreenOn && mLockPatternUtils.isSecure()) {
715                doKeyguardLaterLocked();
716            }
717        }
718    }
719
720    /**
721     * A dream stopped.
722     */
723    public void onDreamingStopped() {
724        synchronized (this) {
725            if (mScreenOn) {
726                cancelDoKeyguardLaterLocked();
727            }
728        }
729    }
730
731    /**
732     * Same semantics as {@link WindowManagerPolicy#enableKeyguard}; provide
733     * a way for external stuff to override normal keyguard behavior.  For instance
734     * the phone app disables the keyguard when it receives incoming calls.
735     */
736    public void setKeyguardEnabled(boolean enabled) {
737        synchronized (this) {
738            if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
739
740            mExternallyEnabled = enabled;
741
742            if (!enabled && mShowing) {
743                if (mExitSecureCallback != null) {
744                    if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
745                    // we're in the process of handling a request to verify the user
746                    // can get past the keyguard. ignore extraneous requests to disable / reenable
747                    return;
748                }
749
750                // hiding keyguard that is showing, remember to reshow later
751                if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
752                        + "disabling status bar expansion");
753                mNeedToReshowWhenReenabled = true;
754                hideLocked();
755            } else if (enabled && mNeedToReshowWhenReenabled) {
756                // reenabled after previously hidden, reshow
757                if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
758                        + "status bar expansion");
759                mNeedToReshowWhenReenabled = false;
760
761                if (mExitSecureCallback != null) {
762                    if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
763                    try {
764                        mExitSecureCallback.onKeyguardExitResult(false);
765                    } catch (RemoteException e) {
766                        Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
767                    }
768                    mExitSecureCallback = null;
769                    resetStateLocked(null);
770                } else {
771                    showLocked(null);
772
773                    // block until we know the keygaurd is done drawing (and post a message
774                    // to unblock us after a timeout so we don't risk blocking too long
775                    // and causing an ANR).
776                    mWaitingUntilKeyguardVisible = true;
777                    mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
778                    if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
779                    while (mWaitingUntilKeyguardVisible) {
780                        try {
781                            wait();
782                        } catch (InterruptedException e) {
783                            Thread.currentThread().interrupt();
784                        }
785                    }
786                    if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
787                }
788            }
789        }
790    }
791
792    /**
793     * @see android.app.KeyguardManager#exitKeyguardSecurely
794     */
795    public void verifyUnlock(IKeyguardExitCallback callback) {
796        synchronized (this) {
797            if (DEBUG) Log.d(TAG, "verifyUnlock");
798            if (!mUpdateMonitor.isDeviceProvisioned()) {
799                // don't allow this api when the device isn't provisioned
800                if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
801                try {
802                    callback.onKeyguardExitResult(false);
803                } catch (RemoteException e) {
804                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
805                }
806            } else if (mExternallyEnabled) {
807                // this only applies when the user has externally disabled the
808                // keyguard.  this is unexpected and means the user is not
809                // using the api properly.
810                Log.w(TAG, "verifyUnlock called when not externally disabled");
811                try {
812                    callback.onKeyguardExitResult(false);
813                } catch (RemoteException e) {
814                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
815                }
816            } else if (mExitSecureCallback != null) {
817                // already in progress with someone else
818                try {
819                    callback.onKeyguardExitResult(false);
820                } catch (RemoteException e) {
821                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
822                }
823            } else {
824                mExitSecureCallback = callback;
825                verifyUnlockLocked();
826            }
827        }
828    }
829
830    /**
831     * Is the keyguard currently showing?
832     */
833    public boolean isShowing() {
834        return mShowing;
835    }
836
837    /**
838     * Is the keyguard currently showing and not being force hidden?
839     */
840    public boolean isShowingAndNotHidden() {
841        return mShowing && !mHidden;
842    }
843
844    /**
845     * Notify us when the keyguard is hidden by another window
846     */
847    public void setHidden(boolean isHidden) {
848        if (DEBUG) Log.d(TAG, "setHidden " + isHidden);
849        mUpdateMonitor.sendKeyguardVisibilityChanged(!isHidden);
850        mHandler.removeMessages(SET_HIDDEN);
851        Message msg = mHandler.obtainMessage(SET_HIDDEN, (isHidden ? 1 : 0), 0);
852        mHandler.sendMessage(msg);
853    }
854
855    /**
856     * Handles SET_HIDDEN message sent by setHidden()
857     */
858    private void handleSetHidden(boolean isHidden) {
859        synchronized (KeyguardViewMediator.this) {
860            if (mHidden != isHidden) {
861                mHidden = isHidden;
862                updateActivityLockScreenState();
863                adjustStatusBarLocked();
864            }
865        }
866    }
867
868    /**
869     * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout.
870     * This must be safe to call from any thread and with any window manager locks held.
871     */
872    public void doKeyguardTimeout(Bundle options) {
873        mHandler.removeMessages(KEYGUARD_TIMEOUT);
874        Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
875        mHandler.sendMessage(msg);
876    }
877
878    /**
879     * Given the state of the keyguard, is the input restricted?
880     * Input is restricted when the keyguard is showing, or when the keyguard
881     * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.
882     */
883    public boolean isInputRestricted() {
884        return mShowing || mNeedToReshowWhenReenabled || !mUpdateMonitor.isDeviceProvisioned();
885    }
886
887    /**
888     * Enable the keyguard if the settings are appropriate.
889     */
890    private void doKeyguardLocked(Bundle options) {
891        // if another app is disabling us, don't show
892        if (!mExternallyEnabled) {
893            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");
894
895            // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes
896            // for an occasional ugly flicker in this situation:
897            // 1) receive a call with the screen on (no keyguard) or make a call
898            // 2) screen times out
899            // 3) user hits key to turn screen back on
900            // instead, we reenable the keyguard when we know the screen is off and the call
901            // ends (see the broadcast receiver below)
902            // TODO: clean this up when we have better support at the window manager level
903            // for apps that wish to be on top of the keyguard
904            return;
905        }
906
907        // if the keyguard is already showing, don't bother
908        if (mKeyguardViewManager.isShowing()) {
909            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
910            return;
911        }
912
913        // if the setup wizard hasn't run yet, don't show
914        final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim",
915                false);
916        final boolean provisioned = mUpdateMonitor.isDeviceProvisioned();
917        final IccCardConstants.State state = mUpdateMonitor.getSimState();
918        final boolean lockedOrMissing = state.isPinLocked()
919                || ((state == IccCardConstants.State.ABSENT
920                || state == IccCardConstants.State.PERM_DISABLED)
921                && requireSim);
922
923        if (!lockedOrMissing && !provisioned) {
924            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
925                    + " and the sim is not locked or missing");
926            return;
927        }
928
929        if (mUserManager.getUsers(true).size() < 2
930                && mLockPatternUtils.isLockScreenDisabled() && !lockedOrMissing) {
931            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
932            return;
933        }
934
935        if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
936        showLocked(options);
937    }
938
939    /**
940     * Dismiss the keyguard through the security layers.
941     */
942    public void handleDismiss() {
943        if (mShowing && !mHidden) {
944            mKeyguardViewManager.dismiss();
945        }
946    }
947
948    public void dismiss() {
949        mHandler.sendEmptyMessage(DISMISS);
950    }
951
952    /**
953     * Send message to keyguard telling it to reset its state.
954     * @param options options about how to show the keyguard
955     * @see #handleReset()
956     */
957    private void resetStateLocked(Bundle options) {
958        if (DEBUG) Log.e(TAG, "resetStateLocked");
959        Message msg = mHandler.obtainMessage(RESET, options);
960        mHandler.sendMessage(msg);
961    }
962
963    /**
964     * Send message to keyguard telling it to verify unlock
965     * @see #handleVerifyUnlock()
966     */
967    private void verifyUnlockLocked() {
968        if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
969        mHandler.sendEmptyMessage(VERIFY_UNLOCK);
970    }
971
972
973    /**
974     * Send a message to keyguard telling it the screen just turned on.
975     * @see #onScreenTurnedOff(int)
976     * @see #handleNotifyScreenOff
977     */
978    private void notifyScreenOffLocked() {
979        if (DEBUG) Log.d(TAG, "notifyScreenOffLocked");
980        mHandler.sendEmptyMessage(NOTIFY_SCREEN_OFF);
981    }
982
983    /**
984     * Send a message to keyguard telling it the screen just turned on.
985     * @see #onScreenTurnedOn()
986     * @see #handleNotifyScreenOn
987     */
988    private void notifyScreenOnLocked(IKeyguardShowCallback result) {
989        if (DEBUG) Log.d(TAG, "notifyScreenOnLocked");
990        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_ON, result);
991        mHandler.sendMessage(msg);
992    }
993
994    /**
995     * Send message to keyguard telling it to show itself
996     * @see #handleShow()
997     */
998    private void showLocked(Bundle options) {
999        if (DEBUG) Log.d(TAG, "showLocked");
1000        // ensure we stay awake until we are finished displaying the keyguard
1001        mShowKeyguardWakeLock.acquire();
1002        Message msg = mHandler.obtainMessage(SHOW, options);
1003        mHandler.sendMessage(msg);
1004    }
1005
1006    /**
1007     * Send message to keyguard telling it to hide itself
1008     * @see #handleHide()
1009     */
1010    private void hideLocked() {
1011        if (DEBUG) Log.d(TAG, "hideLocked");
1012        Message msg = mHandler.obtainMessage(HIDE);
1013        mHandler.sendMessage(msg);
1014    }
1015
1016    public boolean isSecure() {
1017        return mLockPatternUtils.isSecure()
1018            || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
1019    }
1020
1021    /**
1022     * Update the newUserId. Call while holding WindowManagerService lock.
1023     * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.
1024     *
1025     * @param newUserId The id of the incoming user.
1026     */
1027    public void setCurrentUser(int newUserId) {
1028        mLockPatternUtils.setCurrentUser(newUserId);
1029    }
1030
1031    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1032        @Override
1033        public void onReceive(Context context, Intent intent) {
1034            if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {
1035                final int sequence = intent.getIntExtra("seq", 0);
1036                if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
1037                        + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
1038                synchronized (KeyguardViewMediator.this) {
1039                    if (mDelayedShowingSequence == sequence) {
1040                        // Don't play lockscreen SFX if the screen went off due to timeout.
1041                        mSuppressNextLockSound = true;
1042                        doKeyguardLocked(null);
1043                    }
1044                }
1045            }
1046        }
1047    };
1048
1049    public void keyguardDone(boolean authenticated, boolean wakeup) {
1050        if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated + ")");
1051        EventLog.writeEvent(70000, 2);
1052        synchronized (this) {
1053            mKeyguardDonePending = false;
1054        }
1055        Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0, wakeup ? 1 : 0);
1056        mHandler.sendMessage(msg);
1057    }
1058
1059    /**
1060     * This handler will be associated with the policy thread, which will also
1061     * be the UI thread of the keyguard.  Since the apis of the policy, and therefore
1062     * this class, can be called by other threads, any action that directly
1063     * interacts with the keyguard ui should be posted to this handler, rather
1064     * than called directly.
1065     */
1066    private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
1067        @Override
1068        public void handleMessage(Message msg) {
1069            switch (msg.what) {
1070                case SHOW:
1071                    handleShow((Bundle) msg.obj);
1072                    break;
1073                case HIDE:
1074                    handleHide();
1075                    break;
1076                case RESET:
1077                    handleReset((Bundle) msg.obj);
1078                    break;
1079                case VERIFY_UNLOCK:
1080                    handleVerifyUnlock();
1081                    break;
1082                case NOTIFY_SCREEN_OFF:
1083                    handleNotifyScreenOff();
1084                    break;
1085                case NOTIFY_SCREEN_ON:
1086                    handleNotifyScreenOn((IKeyguardShowCallback) msg.obj);
1087                    break;
1088                case KEYGUARD_DONE:
1089                    handleKeyguardDone(msg.arg1 != 0, msg.arg2 != 0);
1090                    break;
1091                case KEYGUARD_DONE_DRAWING:
1092                    handleKeyguardDoneDrawing();
1093                    break;
1094                case KEYGUARD_DONE_AUTHENTICATING:
1095                    keyguardDone(true, true);
1096                    break;
1097                case SET_HIDDEN:
1098                    handleSetHidden(msg.arg1 != 0);
1099                    break;
1100                case KEYGUARD_TIMEOUT:
1101                    synchronized (KeyguardViewMediator.this) {
1102                        doKeyguardLocked((Bundle) msg.obj);
1103                    }
1104                    break;
1105                case SHOW_ASSISTANT:
1106                    handleShowAssistant();
1107                    break;
1108                case DISPATCH_EVENT:
1109                    handleDispatchEvent((MotionEvent) msg.obj);
1110                    break;
1111                case LAUNCH_CAMERA:
1112                    handleLaunchCamera();
1113                    break;
1114                case DISMISS:
1115                    handleDismiss();
1116                    break;
1117            }
1118        }
1119    };
1120
1121    /**
1122     * @see #keyguardDone
1123     * @see #KEYGUARD_DONE
1124     */
1125    private void handleKeyguardDone(boolean authenticated, boolean wakeup) {
1126        if (DEBUG) Log.d(TAG, "handleKeyguardDone");
1127
1128        if (authenticated) {
1129            mUpdateMonitor.clearFailedUnlockAttempts();
1130        }
1131
1132        if (mExitSecureCallback != null) {
1133            try {
1134                mExitSecureCallback.onKeyguardExitResult(authenticated);
1135            } catch (RemoteException e) {
1136                Slog.w(TAG, "Failed to call onKeyguardExitResult(" + authenticated + ")", e);
1137            }
1138
1139            mExitSecureCallback = null;
1140
1141            if (authenticated) {
1142                // after succesfully exiting securely, no need to reshow
1143                // the keyguard when they've released the lock
1144                mExternallyEnabled = true;
1145                mNeedToReshowWhenReenabled = false;
1146            }
1147        }
1148
1149        handleHide();
1150        sendUserPresentBroadcast();
1151    }
1152
1153    protected void handleLaunchCamera() {
1154        mKeyguardViewManager.launchCamera();
1155    }
1156
1157    protected void handleDispatchEvent(MotionEvent event) {
1158        mKeyguardViewManager.dispatch(event);
1159    }
1160
1161    private void sendUserPresentBroadcast() {
1162        final UserHandle currentUser = new UserHandle(mLockPatternUtils.getCurrentUser());
1163        mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, currentUser);
1164    }
1165
1166    /**
1167     * @see #keyguardDoneDrawing
1168     * @see #KEYGUARD_DONE_DRAWING
1169     */
1170    private void handleKeyguardDoneDrawing() {
1171        synchronized(this) {
1172            if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing");
1173            if (mWaitingUntilKeyguardVisible) {
1174                if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
1175                mWaitingUntilKeyguardVisible = false;
1176                notifyAll();
1177
1178                // there will usually be two of these sent, one as a timeout, and one
1179                // as a result of the callback, so remove any remaining messages from
1180                // the queue
1181                mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
1182            }
1183        }
1184    }
1185
1186    private void playSounds(boolean locked) {
1187        // User feedback for keyguard.
1188
1189        if (mSuppressNextLockSound) {
1190            mSuppressNextLockSound = false;
1191            return;
1192        }
1193
1194        final ContentResolver cr = mContext.getContentResolver();
1195        if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
1196            final int whichSound = locked
1197                ? mLockSoundId
1198                : mUnlockSoundId;
1199            mLockSounds.stop(mLockSoundStreamId);
1200            // Init mAudioManager
1201            if (mAudioManager == null) {
1202                mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
1203                if (mAudioManager == null) return;
1204                mMasterStreamType = mAudioManager.getMasterStreamType();
1205            }
1206            // If the stream is muted, don't play the sound
1207            if (mAudioManager.isStreamMute(mMasterStreamType)) return;
1208
1209            mLockSoundStreamId = mLockSounds.play(whichSound,
1210                    mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
1211        }
1212    }
1213
1214    private void updateActivityLockScreenState() {
1215        try {
1216            ActivityManagerNative.getDefault().setLockScreenShown(mShowing && !mHidden);
1217        } catch (RemoteException e) {
1218        }
1219    }
1220
1221    /**
1222     * Handle message sent by {@link #showLocked}.
1223     * @see #SHOW
1224     */
1225    private void handleShow(Bundle options) {
1226        synchronized (KeyguardViewMediator.this) {
1227            if (!mSystemReady) {
1228                if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready.");
1229                return;
1230            } else {
1231                if (DEBUG) Log.d(TAG, "handleShow");
1232            }
1233
1234            mKeyguardViewManager.show(options);
1235            mShowing = true;
1236            mKeyguardDonePending = false;
1237            updateActivityLockScreenState();
1238            adjustStatusBarLocked();
1239            userActivity();
1240            try {
1241                ActivityManagerNative.getDefault().closeSystemDialogs("lock");
1242            } catch (RemoteException e) {
1243            }
1244
1245            // Do this at the end to not slow down display of the keyguard.
1246            playSounds(true);
1247
1248            mShowKeyguardWakeLock.release();
1249        }
1250        mKeyguardDisplayManager.show();
1251    }
1252
1253    /**
1254     * Handle message sent by {@link #hideLocked()}
1255     * @see #HIDE
1256     */
1257    private void handleHide() {
1258        synchronized (KeyguardViewMediator.this) {
1259            if (DEBUG) Log.d(TAG, "handleHide");
1260
1261            // only play "unlock" noises if not on a call (since the incall UI
1262            // disables the keyguard)
1263            if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
1264                playSounds(false);
1265            }
1266
1267            mKeyguardViewManager.hide();
1268            mShowing = false;
1269            mKeyguardDonePending = false;
1270            updateActivityLockScreenState();
1271            adjustStatusBarLocked();
1272        }
1273    }
1274
1275    private void adjustStatusBarLocked() {
1276        if (mStatusBarManager == null) {
1277            mStatusBarManager = (StatusBarManager)
1278                    mContext.getSystemService(Context.STATUS_BAR_SERVICE);
1279        }
1280        if (mStatusBarManager == null) {
1281            Log.w(TAG, "Could not get status bar manager");
1282        } else {
1283            // Disable aspects of the system/status/navigation bars that must not be re-enabled by
1284            // windows that appear on top, ever
1285            int flags = StatusBarManager.DISABLE_NONE;
1286            if (mShowing) {
1287                // Permanently disable components not available when keyguard is enabled
1288                // (like recents). Temporary enable/disable (e.g. the "back" button) are
1289                // done in KeyguardHostView.
1290                flags |= StatusBarManager.DISABLE_RECENT;
1291                if (isSecure() || !ENABLE_INSECURE_STATUS_BAR_EXPAND) {
1292                    // showing secure lockscreen; disable expanding.
1293                    flags |= StatusBarManager.DISABLE_EXPAND;
1294                }
1295                if (isSecure()) {
1296                    // showing secure lockscreen; disable ticker.
1297                    flags |= StatusBarManager.DISABLE_NOTIFICATION_TICKER;
1298                }
1299                if (!isAssistantAvailable()) {
1300                    flags |= StatusBarManager.DISABLE_SEARCH;
1301                }
1302            }
1303
1304            if (DEBUG) {
1305                Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mHidden=" + mHidden
1306                        + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
1307            }
1308
1309            if (!(mContext instanceof Activity)) {
1310                mStatusBarManager.disable(flags);
1311            }
1312        }
1313    }
1314
1315    /**
1316     * Handle message sent by {@link #resetStateLocked(Bundle)}
1317     * @see #RESET
1318     */
1319    private void handleReset(Bundle options) {
1320        if (options == null) {
1321            options = new Bundle();
1322        }
1323        options.putBoolean(KeyguardViewManager.IS_SWITCHING_USER, mSwitchingUser);
1324        synchronized (KeyguardViewMediator.this) {
1325            if (DEBUG) Log.d(TAG, "handleReset");
1326            mKeyguardViewManager.reset(options);
1327        }
1328    }
1329
1330    /**
1331     * Handle message sent by {@link #verifyUnlock}
1332     * @see #VERIFY_UNLOCK
1333     */
1334    private void handleVerifyUnlock() {
1335        synchronized (KeyguardViewMediator.this) {
1336            if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
1337            mKeyguardViewManager.verifyUnlock();
1338            mShowing = true;
1339            updateActivityLockScreenState();
1340        }
1341    }
1342
1343    /**
1344     * Handle message sent by {@link #notifyScreenOffLocked()}
1345     * @see #NOTIFY_SCREEN_OFF
1346     */
1347    private void handleNotifyScreenOff() {
1348        synchronized (KeyguardViewMediator.this) {
1349            if (DEBUG) Log.d(TAG, "handleNotifyScreenOff");
1350            mKeyguardViewManager.onScreenTurnedOff();
1351        }
1352    }
1353
1354    /**
1355     * Handle message sent by {@link #notifyScreenOnLocked()}
1356     * @see #NOTIFY_SCREEN_ON
1357     */
1358    private void handleNotifyScreenOn(IKeyguardShowCallback callback) {
1359        synchronized (KeyguardViewMediator.this) {
1360            if (DEBUG) Log.d(TAG, "handleNotifyScreenOn");
1361            mKeyguardViewManager.onScreenTurnedOn(callback);
1362        }
1363    }
1364
1365    public boolean isDismissable() {
1366        return mKeyguardDonePending || !isSecure();
1367    }
1368
1369    public void showAssistant() {
1370        Message msg = mHandler.obtainMessage(SHOW_ASSISTANT);
1371        mHandler.sendMessage(msg);
1372    }
1373
1374    public void handleShowAssistant() {
1375        mKeyguardViewManager.showAssistant();
1376    }
1377
1378    private boolean isAssistantAvailable() {
1379        return mSearchManager != null
1380                && mSearchManager.getAssistIntent(mContext, false, UserHandle.USER_CURRENT) != null;
1381    }
1382
1383    public static MultiUserAvatarCache getAvatarCache() {
1384        return sMultiUserAvatarCache;
1385    }
1386
1387    public void dispatch(MotionEvent event) {
1388        Message msg = mHandler.obtainMessage(DISPATCH_EVENT, event);
1389        mHandler.sendMessage(msg);
1390    }
1391
1392    public void launchCamera() {
1393        Message msg = mHandler.obtainMessage(LAUNCH_CAMERA);
1394        mHandler.sendMessage(msg);
1395    }
1396
1397    public void onBootCompleted() {
1398        mUpdateMonitor.dispatchBootCompleted();
1399    }
1400}
1401