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