KeyguardViewMediator.java revision 3dc524bc31a1578693ca958ef442dfa092b7aa7f
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();
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();
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();
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();
381                        }
382                    }
383                    break;
384                case READY:
385                    synchronized (this) {
386                        if (isShowing()) {
387                            resetStateLocked();
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.System.getString(cr, Settings.System.LOCK_SOUND);
474        if (soundPath != null) {
475            mLockSoundId = mLockSounds.load(soundPath, 1);
476        }
477        if (soundPath == null || mLockSoundId == 0) {
478            if (DEBUG) Log.d(TAG, "failed to load sound from " + soundPath);
479        }
480        soundPath = Settings.System.getString(cr, Settings.System.UNLOCK_SOUND);
481        if (soundPath != null) {
482            mUnlockSoundId = mLockSounds.load(soundPath, 1);
483        }
484        if (soundPath == null || mUnlockSoundId == 0) {
485            if (DEBUG) Log.d(TAG, "failed to load 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();
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();
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     * @see #handleReset()
809     */
810    private void resetStateLocked() {
811        if (DEBUG) Log.d(TAG, "resetStateLocked");
812        Message msg = mHandler.obtainMessage(RESET);
813        mHandler.sendMessage(msg);
814    }
815
816    /**
817     * Send message to keyguard telling it to verify unlock
818     * @see #handleVerifyUnlock()
819     */
820    private void verifyUnlockLocked() {
821        if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
822        mHandler.sendEmptyMessage(VERIFY_UNLOCK);
823    }
824
825
826    /**
827     * Send a message to keyguard telling it the screen just turned on.
828     * @see #onScreenTurnedOff(int)
829     * @see #handleNotifyScreenOff
830     */
831    private void notifyScreenOffLocked() {
832        if (DEBUG) Log.d(TAG, "notifyScreenOffLocked");
833        mHandler.sendEmptyMessage(NOTIFY_SCREEN_OFF);
834    }
835
836    /**
837     * Send a message to keyguard telling it the screen just turned on.
838     * @see #onScreenTurnedOn()
839     * @see #handleNotifyScreenOn
840     */
841    private void notifyScreenOnLocked(KeyguardViewManager.ShowListener showListener) {
842        if (DEBUG) Log.d(TAG, "notifyScreenOnLocked");
843        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_ON, showListener);
844        mHandler.sendMessage(msg);
845    }
846
847    /**
848     * Send message to keyguard telling it about a wake key so it can adjust
849     * its state accordingly and then poke the wake lock when it is ready.
850     * @param keyCode The wake key.
851     * @see #handleWakeWhenReady
852     * @see #onWakeKeyWhenKeyguardShowingTq(int)
853     */
854    private void wakeWhenReadyLocked(int keyCode) {
855        if (DBG_WAKE) Log.d(TAG, "wakeWhenReadyLocked(" + keyCode + ")");
856
857        /**
858         * acquire the handoff lock that will keep the cpu running.  this will
859         * be released once the keyguard has set itself up and poked the other wakelock
860         * in {@link #handleWakeWhenReady(int)}
861         */
862        mWakeAndHandOff.acquire();
863
864        Message msg = mHandler.obtainMessage(WAKE_WHEN_READY, keyCode, 0);
865        mHandler.sendMessage(msg);
866    }
867
868    /**
869     * Send message to keyguard telling it to show itself
870     * @see #handleShow()
871     */
872    private void showLocked() {
873        if (DEBUG) Log.d(TAG, "showLocked");
874        // ensure we stay awake until we are finished displaying the keyguard
875        mShowKeyguardWakeLock.acquire();
876        Message msg = mHandler.obtainMessage(SHOW);
877        mHandler.sendMessage(msg);
878    }
879
880    /**
881     * Send message to keyguard telling it to hide itself
882     * @see #handleHide()
883     */
884    private void hideLocked() {
885        if (DEBUG) Log.d(TAG, "hideLocked");
886        Message msg = mHandler.obtainMessage(HIDE);
887        mHandler.sendMessage(msg);
888    }
889
890    public boolean isSecure() {
891        return mLockPatternUtils.isSecure()
892            || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
893    }
894
895    /**
896     * Update the newUserId. Call while holding WindowManagerService lock.
897     * @param newUserId The id of the incoming user.
898     */
899    public void setCurrentUser(int newUserId) {
900        mLockPatternUtils.setCurrentUser(newUserId);
901    }
902
903    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
904        @Override
905        public void onReceive(Context context, Intent intent) {
906            if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {
907                final int sequence = intent.getIntExtra("seq", 0);
908                if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
909                        + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
910                synchronized (KeyguardViewMediator.this) {
911                    if (mDelayedShowingSequence == sequence) {
912                        // Don't play lockscreen SFX if the screen went off due to timeout.
913                        mSuppressNextLockSound = true;
914                        doKeyguardLocked();
915                    }
916                }
917            }
918        }
919    };
920
921    /**
922     * When a key is received when the screen is off and the keyguard is showing,
923     * we need to decide whether to actually turn on the screen, and if so, tell
924     * the keyguard to prepare itself and poke the wake lock when it is ready.
925     *
926     * The 'Tq' suffix is per the documentation in {@link WindowManagerPolicy}.
927     * Be sure not to take any action that takes a long time; any significant
928     * action should be posted to a handler.
929     *
930     * @param keyCode The keycode of the key that woke the device
931     * @param isDocked True if the device is in the dock
932     * @return Whether we poked the wake lock (and turned the screen on)
933     */
934    public boolean onWakeKeyWhenKeyguardShowingTq(int keyCode, boolean isDocked) {
935        if (DEBUG) Log.d(TAG, "onWakeKeyWhenKeyguardShowing(" + keyCode + ")");
936
937        if (isWakeKeyWhenKeyguardShowing(keyCode, isDocked)) {
938            // give the keyguard view manager a chance to adjust the state of the
939            // keyguard based on the key that woke the device before poking
940            // the wake lock
941            wakeWhenReadyLocked(keyCode);
942            return true;
943        } else {
944            return false;
945        }
946    }
947
948    /**
949     * When the keyguard is showing we ignore some keys that might otherwise typically
950     * be considered wake keys.  We filter them out here.
951     *
952     * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it
953     * is always considered a wake key.
954     */
955    private boolean isWakeKeyWhenKeyguardShowing(int keyCode, boolean isDocked) {
956        switch (keyCode) {
957            // ignore volume keys unless docked
958            case KeyEvent.KEYCODE_VOLUME_UP:
959            case KeyEvent.KEYCODE_VOLUME_DOWN:
960            case KeyEvent.KEYCODE_VOLUME_MUTE:
961                return isDocked;
962
963            // ignore media and camera keys
964            case KeyEvent.KEYCODE_MUTE:
965            case KeyEvent.KEYCODE_HEADSETHOOK:
966            case KeyEvent.KEYCODE_MEDIA_PLAY:
967            case KeyEvent.KEYCODE_MEDIA_PAUSE:
968            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
969            case KeyEvent.KEYCODE_MEDIA_STOP:
970            case KeyEvent.KEYCODE_MEDIA_NEXT:
971            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
972            case KeyEvent.KEYCODE_MEDIA_REWIND:
973            case KeyEvent.KEYCODE_MEDIA_RECORD:
974            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
975            case KeyEvent.KEYCODE_CAMERA:
976                return false;
977        }
978        return true;
979    }
980
981    /**
982     * When a wake motion such as an external mouse movement is received when the screen
983     * is off and the keyguard is showing, we need to decide whether to actually turn
984     * on the screen, and if so, tell the keyguard to prepare itself and poke the wake
985     * lock when it is ready.
986     *
987     * The 'Tq' suffix is per the documentation in {@link WindowManagerPolicy}.
988     * Be sure not to take any action that takes a long time; any significant
989     * action should be posted to a handler.
990     *
991     * @return Whether we poked the wake lock (and turned the screen on)
992     */
993    public boolean onWakeMotionWhenKeyguardShowingTq() {
994        if (DEBUG) Log.d(TAG, "onWakeMotionWhenKeyguardShowing()");
995
996        // give the keyguard view manager a chance to adjust the state of the
997        // keyguard based on the key that woke the device before poking
998        // the wake lock
999        wakeWhenReadyLocked(KeyEvent.KEYCODE_UNKNOWN);
1000        return true;
1001    }
1002
1003    public void keyguardDone(boolean authenticated, boolean wakeup) {
1004        synchronized (this) {
1005            EventLog.writeEvent(70000, 2);
1006            if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated + ")");
1007            Message msg = mHandler.obtainMessage(KEYGUARD_DONE);
1008            msg.arg1 = wakeup ? 1 : 0;
1009            mHandler.sendMessage(msg);
1010
1011            if (authenticated) {
1012                mUpdateMonitor.clearFailedUnlockAttempts();
1013            }
1014
1015            if (mExitSecureCallback != null) {
1016                mExitSecureCallback.onKeyguardExitResult(authenticated);
1017                mExitSecureCallback = null;
1018
1019                if (authenticated) {
1020                    // after succesfully exiting securely, no need to reshow
1021                    // the keyguard when they've released the lock
1022                    mExternallyEnabled = true;
1023                    mNeedToReshowWhenReenabled = false;
1024                }
1025            }
1026        }
1027    }
1028
1029    /**
1030     * This handler will be associated with the policy thread, which will also
1031     * be the UI thread of the keyguard.  Since the apis of the policy, and therefore
1032     * this class, can be called by other threads, any action that directly
1033     * interacts with the keyguard ui should be posted to this handler, rather
1034     * than called directly.
1035     */
1036    private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
1037        @Override
1038        public void handleMessage(Message msg) {
1039            switch (msg.what) {
1040                case SHOW:
1041                    handleShow();
1042                    return ;
1043                case HIDE:
1044                    handleHide();
1045                    return ;
1046                case RESET:
1047                    handleReset();
1048                    return ;
1049                case VERIFY_UNLOCK:
1050                    handleVerifyUnlock();
1051                    return;
1052                case NOTIFY_SCREEN_OFF:
1053                    handleNotifyScreenOff();
1054                    return;
1055                case NOTIFY_SCREEN_ON:
1056                    handleNotifyScreenOn((KeyguardViewManager.ShowListener)msg.obj);
1057                    return;
1058                case WAKE_WHEN_READY:
1059                    handleWakeWhenReady(msg.arg1);
1060                    return;
1061                case KEYGUARD_DONE:
1062                    handleKeyguardDone(msg.arg1 != 0);
1063                    return;
1064                case KEYGUARD_DONE_DRAWING:
1065                    handleKeyguardDoneDrawing();
1066                    return;
1067                case KEYGUARD_DONE_AUTHENTICATING:
1068                    keyguardDone(true, true);
1069                    return;
1070                case SET_HIDDEN:
1071                    handleSetHidden(msg.arg1 != 0);
1072                    break;
1073                case KEYGUARD_TIMEOUT:
1074                    synchronized (KeyguardViewMediator.this) {
1075                        doKeyguardLocked();
1076                    }
1077                    break;
1078            }
1079        }
1080    };
1081
1082    /**
1083     * @see #keyguardDone
1084     * @see #KEYGUARD_DONE
1085     */
1086    private void handleKeyguardDone(boolean wakeup) {
1087        if (DEBUG) Log.d(TAG, "handleKeyguardDone");
1088        handleHide();
1089        if (wakeup) {
1090            wakeUp();
1091        }
1092
1093        sendUserPresentBroadcast();
1094    }
1095
1096    private void sendUserPresentBroadcast() {
1097        if (!(mContext instanceof Activity)) {
1098            final UserHandle currentUser = new UserHandle(mLockPatternUtils.getCurrentUser());
1099            mContext.sendBroadcastAsUser(mUserPresentIntent, currentUser);
1100        }
1101    }
1102
1103    /**
1104     * @see #keyguardDoneDrawing
1105     * @see #KEYGUARD_DONE_DRAWING
1106     */
1107    private void handleKeyguardDoneDrawing() {
1108        synchronized(this) {
1109            if (false) Log.d(TAG, "handleKeyguardDoneDrawing");
1110            if (mWaitingUntilKeyguardVisible) {
1111                if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
1112                mWaitingUntilKeyguardVisible = false;
1113                notifyAll();
1114
1115                // there will usually be two of these sent, one as a timeout, and one
1116                // as a result of the callback, so remove any remaining messages from
1117                // the queue
1118                mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
1119            }
1120        }
1121    }
1122
1123    private void playSounds(boolean locked) {
1124        // User feedback for keyguard.
1125
1126        if (mSuppressNextLockSound) {
1127            mSuppressNextLockSound = false;
1128            return;
1129        }
1130
1131        final ContentResolver cr = mContext.getContentResolver();
1132        if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
1133            final int whichSound = locked
1134                ? mLockSoundId
1135                : mUnlockSoundId;
1136            mLockSounds.stop(mLockSoundStreamId);
1137            // Init mAudioManager
1138            if (mAudioManager == null) {
1139                mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
1140                if (mAudioManager == null) return;
1141                mMasterStreamType = mAudioManager.getMasterStreamType();
1142            }
1143            // If the stream is muted, don't play the sound
1144            if (mAudioManager.isStreamMute(mMasterStreamType)) return;
1145
1146            mLockSoundStreamId = mLockSounds.play(whichSound,
1147                    mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
1148        }
1149    }
1150
1151    private void updateActivityLockScreenState() {
1152        try {
1153            ActivityManagerNative.getDefault().setLockScreenShown(
1154                    mShowing && !mHidden);
1155        } catch (RemoteException e) {
1156        }
1157    }
1158
1159    /**
1160     * Handle message sent by {@link #showLocked}.
1161     * @see #SHOW
1162     */
1163    private void handleShow() {
1164        synchronized (KeyguardViewMediator.this) {
1165            if (DEBUG) Log.d(TAG, "handleShow");
1166            if (!mSystemReady) return;
1167
1168            mKeyguardViewManager.show();
1169            mShowing = true;
1170            updateActivityLockScreenState();
1171            adjustStatusBarLocked();
1172            userActivity();
1173            try {
1174                ActivityManagerNative.getDefault().closeSystemDialogs("lock");
1175            } catch (RemoteException e) {
1176            }
1177
1178            // Do this at the end to not slow down display of the keyguard.
1179            playSounds(true);
1180
1181            mShowKeyguardWakeLock.release();
1182        }
1183    }
1184
1185    /**
1186     * Handle message sent by {@link #hideLocked()}
1187     * @see #HIDE
1188     */
1189    private void handleHide() {
1190        synchronized (KeyguardViewMediator.this) {
1191            if (DEBUG) Log.d(TAG, "handleHide");
1192            if (mWakeAndHandOff.isHeld()) {
1193                Log.w(TAG, "attempt to hide the keyguard while waking, ignored");
1194                return;
1195            }
1196
1197            // only play "unlock" noises if not on a call (since the incall UI
1198            // disables the keyguard)
1199            if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
1200                playSounds(false);
1201            }
1202
1203            mKeyguardViewManager.hide();
1204            mShowing = false;
1205            updateActivityLockScreenState();
1206            adjustStatusBarLocked();
1207        }
1208    }
1209
1210    private void adjustStatusBarLocked() {
1211        if (mStatusBarManager == null) {
1212            mStatusBarManager = (StatusBarManager)
1213                    mContext.getSystemService(Context.STATUS_BAR_SERVICE);
1214        }
1215        if (mStatusBarManager == null) {
1216            Log.w(TAG, "Could not get status bar manager");
1217        } else {
1218            if (mShowLockIcon) {
1219                // Give feedback to user when secure keyguard is active and engaged
1220                if (mShowing && isSecure()) {
1221                    if (!mShowingLockIcon) {
1222                        String contentDescription = mContext.getString(
1223                                com.android.internal.R.string.status_bar_device_locked);
1224                        mStatusBarManager.setIcon("secure",
1225                                com.android.internal.R.drawable.stat_sys_secure, 0,
1226                                contentDescription);
1227                        mShowingLockIcon = true;
1228                    }
1229                } else {
1230                    if (mShowingLockIcon) {
1231                        mStatusBarManager.removeIcon("secure");
1232                        mShowingLockIcon = false;
1233                    }
1234                }
1235            }
1236
1237            // Disable aspects of the system/status/navigation bars that must not be re-enabled by
1238            // windows that appear on top, ever
1239            int flags = StatusBarManager.DISABLE_NONE;
1240            if (mShowing) {
1241                // Permanently disable components not available when keyguard is enabled
1242                // (like recents). Temporary enable/disable (e.g. the "back" button) are
1243                // done in KeyguardHostView.
1244                flags |= StatusBarManager.DISABLE_RECENT;
1245                if (isSecure() || !ENABLE_INSECURE_STATUS_BAR_EXPAND) {
1246                    // showing secure lockscreen; disable expanding.
1247                    flags |= StatusBarManager.DISABLE_EXPAND;
1248                }
1249                if (isSecure()) {
1250                    // showing secure lockscreen; disable ticker.
1251                    flags |= StatusBarManager.DISABLE_NOTIFICATION_TICKER;
1252                }
1253            }
1254
1255            if (DEBUG) {
1256                Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mHidden=" + mHidden
1257                        + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
1258            }
1259
1260            mStatusBarManager.disable(flags);
1261        }
1262    }
1263
1264    /**
1265     * Handle message sent by {@link #wakeWhenReadyLocked(int)}
1266     * @param keyCode The key that woke the device.
1267     * @see #WAKE_WHEN_READY
1268     */
1269    private void handleWakeWhenReady(int keyCode) {
1270        synchronized (KeyguardViewMediator.this) {
1271            if (DBG_WAKE) Log.d(TAG, "handleWakeWhenReady(" + keyCode + ")");
1272
1273            // this should result in a call to 'poke wakelock' which will set a timeout
1274            // on releasing the wakelock
1275            if (!mKeyguardViewManager.wakeWhenReadyTq(keyCode)) {
1276                // poke wakelock ourselves if keyguard is no longer active
1277                Log.w(TAG, "mKeyguardViewManager.wakeWhenReadyTq did not poke wake lock, so poke it ourselves");
1278                userActivity();
1279            }
1280
1281            /**
1282             * Now that the keyguard is ready and has poked the wake lock, we can
1283             * release the handoff wakelock
1284             */
1285            mWakeAndHandOff.release();
1286        }
1287    }
1288
1289    /**
1290     * Handle message sent by {@link #resetStateLocked()}
1291     * @see #RESET
1292     */
1293    private void handleReset() {
1294        synchronized (KeyguardViewMediator.this) {
1295            if (DEBUG) Log.d(TAG, "handleReset");
1296            mKeyguardViewManager.reset();
1297        }
1298    }
1299
1300    /**
1301     * Handle message sent by {@link #verifyUnlock}
1302     * @see #RESET
1303     */
1304    private void handleVerifyUnlock() {
1305        synchronized (KeyguardViewMediator.this) {
1306            if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
1307            mKeyguardViewManager.verifyUnlock();
1308            mShowing = true;
1309            updateActivityLockScreenState();
1310        }
1311    }
1312
1313    /**
1314     * Handle message sent by {@link #notifyScreenOffLocked()}
1315     * @see #NOTIFY_SCREEN_OFF
1316     */
1317    private void handleNotifyScreenOff() {
1318        synchronized (KeyguardViewMediator.this) {
1319            if (DEBUG) Log.d(TAG, "handleNotifyScreenOff");
1320            mKeyguardViewManager.onScreenTurnedOff();
1321        }
1322    }
1323
1324    /**
1325     * Handle message sent by {@link #notifyScreenOnLocked()}
1326     * @see #NOTIFY_SCREEN_ON
1327     */
1328    private void handleNotifyScreenOn(KeyguardViewManager.ShowListener showListener) {
1329        synchronized (KeyguardViewMediator.this) {
1330            if (DEBUG) Log.d(TAG, "handleNotifyScreenOn");
1331            mKeyguardViewManager.onScreenTurnedOn(showListener);
1332        }
1333    }
1334
1335}
1336