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