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