KeyguardViewMediator.java revision 1c2e4948a1f0e803171389427212321973ea66b8
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.policy.impl.keyguard;
18
19import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
20
21import android.app.Activity;
22import android.app.ActivityManagerNative;
23import android.app.AlarmManager;
24import android.app.PendingIntent;
25import android.app.StatusBarManager;
26import android.content.BroadcastReceiver;
27import android.content.ContentResolver;
28import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
31import android.media.AudioManager;
32import android.media.SoundPool;
33import android.os.Bundle;
34import android.os.Handler;
35import android.os.Looper;
36import android.os.Message;
37import android.os.PowerManager;
38import android.os.RemoteException;
39import android.os.SystemClock;
40import android.os.SystemProperties;
41import android.os.UserHandle;
42import android.os.UserManager;
43import android.provider.Settings;
44import android.telephony.TelephonyManager;
45import android.util.EventLog;
46import android.util.Log;
47import android.view.KeyEvent;
48import android.view.WindowManager;
49import android.view.WindowManagerPolicy;
50
51import com.android.internal.telephony.IccCardConstants;
52import com.android.internal.widget.LockPatternUtils;
53
54
55/**
56 * Mediates requests related to the keyguard.  This includes queries about the
57 * state of the keyguard, power management events that effect whether the keyguard
58 * should be shown or reset, callbacks to the phone window manager to notify
59 * it of when the keyguard is showing, and events from the keyguard view itself
60 * stating that the keyguard was succesfully unlocked.
61 *
62 * Note that the keyguard view is shown when the screen is off (as appropriate)
63 * so that once the screen comes on, it will be ready immediately.
64 *
65 * Example queries about the keyguard:
66 * - is {movement, key} one that should wake the keygaurd?
67 * - is the keyguard showing?
68 * - are input events restricted due to the state of the keyguard?
69 *
70 * Callbacks to the phone window manager:
71 * - the keyguard is showing
72 *
73 * Example external events that translate to keyguard view changes:
74 * - screen turned off -> reset the keyguard, and show it so it will be ready
75 *   next time the screen turns on
76 * - keyboard is slid open -> if the keyguard is not secure, hide it
77 *
78 * Events from the keyguard view:
79 * - user succesfully unlocked keyguard -> hide keyguard view, and no longer
80 *   restrict input events.
81 *
82 * Note: in addition to normal power managment events that effect the state of
83 * whether the keyguard should be showing, external apps and services may request
84 * that the keyguard be disabled via {@link #setKeyguardEnabled(boolean)}.  When
85 * false, this will override all other conditions for turning on the keyguard.
86 *
87 * Threading and synchronization:
88 * This class is created by the initialization routine of the {@link WindowManagerPolicy},
89 * and runs on its thread.  The keyguard UI is created from that thread in the
90 * constructor of this class.  The apis may be called from other threads, including the
91 * {@link com.android.server.input.InputManagerService}'s and {@link android.view.WindowManager}'s.
92 * Therefore, methods on this class are synchronized, and any action that is pointed
93 * directly to the keyguard UI is posted to a {@link Handler} to ensure it is taken on the UI
94 * thread of the keyguard.
95 */
96public class KeyguardViewMediator {
97    private static final int KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000;
98    final static boolean DEBUG = false;
99    private final static boolean DBG_WAKE = false;
100
101    private final static String TAG = "KeyguardViewMediator";
102
103    private static final String DELAYED_KEYGUARD_ACTION =
104        "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_KEYGUARD";
105
106    // used for handler messages
107    private static final int SHOW = 2;
108    private static final int HIDE = 3;
109    private static final int RESET = 4;
110    private static final int VERIFY_UNLOCK = 5;
111    private static final int NOTIFY_SCREEN_OFF = 6;
112    private static final int NOTIFY_SCREEN_ON = 7;
113    private static final int WAKE_WHEN_READY = 8;
114    private static final int KEYGUARD_DONE = 9;
115    private static final int KEYGUARD_DONE_DRAWING = 10;
116    private static final int KEYGUARD_DONE_AUTHENTICATING = 11;
117    private static final int SET_HIDDEN = 12;
118    private static final int KEYGUARD_TIMEOUT = 13;
119
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 #wakeWhenReady(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            // Suppress biometric unlock right after boot until things have settled if it is the
524            // selected security method, otherwise unsuppress it.  It must be unsuppressed if it is
525            // not the selected security method for the following reason:  if the user starts
526            // without a screen lock selected, the biometric unlock would be suppressed the first
527            // time they try to use it.
528            //
529            // Note that the biometric unlock will still not show if it is not the selected method.
530            // Calling setAlternateUnlockEnabled(true) simply says don't suppress it if it is the
531            // selected method.
532            if (mLockPatternUtils.usingBiometricWeak()
533                    && mLockPatternUtils.isBiometricWeakInstalled()) {
534                if (DEBUG) Log.d(TAG, "suppressing biometric unlock during boot");
535                mUpdateMonitor.setAlternateUnlockEnabled(false);
536            } else {
537                mUpdateMonitor.setAlternateUnlockEnabled(true);
538            }
539
540            doKeyguardLocked();
541        }
542        // Most services aren't available until the system reaches the ready state, so we
543        // send it here when the device first boots.
544        maybeSendUserPresentBroadcast();
545    }
546
547    /**
548     * Called to let us know the screen was turned off.
549     * @param why either {@link WindowManagerPolicy#OFF_BECAUSE_OF_USER},
550     *   {@link WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT} or
551     *   {@link WindowManagerPolicy#OFF_BECAUSE_OF_PROX_SENSOR}.
552     */
553    public void onScreenTurnedOff(int why) {
554        synchronized (this) {
555            mScreenOn = false;
556            if (DEBUG) Log.d(TAG, "onScreenTurnedOff(" + why + ")");
557
558            // Lock immediately based on setting if secure (user has a pin/pattern/password).
559            // This also "locks" the device when not secure to provide easy access to the
560            // camera while preventing unwanted input.
561            final boolean lockImmediately =
562                mLockPatternUtils.getPowerButtonInstantlyLocks() || !mLockPatternUtils.isSecure();
563
564            if (mExitSecureCallback != null) {
565                if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
566                mExitSecureCallback.onKeyguardExitResult(false);
567                mExitSecureCallback = null;
568                if (!mExternallyEnabled) {
569                    hideLocked();
570                }
571            } else if (mShowing) {
572                notifyScreenOffLocked();
573                resetStateLocked(null);
574            } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT
575                   || (why == WindowManagerPolicy.OFF_BECAUSE_OF_USER && !lockImmediately)) {
576                doKeyguardLaterLocked();
577            } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
578                // Do not enable the keyguard if the prox sensor forced the screen off.
579            } else {
580                doKeyguardLocked();
581            }
582        }
583    }
584
585    private void doKeyguardLaterLocked() {
586        // if the screen turned off because of timeout or the user hit the power button
587        // and we don't need to lock immediately, set an alarm
588        // to enable it a little bit later (i.e, give the user a chance
589        // to turn the screen back on within a certain window without
590        // having to unlock the screen)
591        final ContentResolver cr = mContext.getContentResolver();
592
593        // From DisplaySettings
594        long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
595                KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);
596
597        // From SecuritySettings
598        final long lockAfterTimeout = Settings.Secure.getInt(cr,
599                Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
600                KEYGUARD_LOCK_AFTER_DELAY_DEFAULT);
601
602        // From DevicePolicyAdmin
603        final long policyTimeout = mLockPatternUtils.getDevicePolicyManager()
604                .getMaximumTimeToLock(null, mLockPatternUtils.getCurrentUser());
605
606        long timeout;
607        if (policyTimeout > 0) {
608            // policy in effect. Make sure we don't go beyond policy limit.
609            displayTimeout = Math.max(displayTimeout, 0); // ignore negative values
610            timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);
611        } else {
612            timeout = lockAfterTimeout;
613        }
614
615        if (timeout <= 0) {
616            // Lock now
617            mSuppressNextLockSound = true;
618            doKeyguardLocked();
619        } else {
620            // Lock in the future
621            long when = SystemClock.elapsedRealtime() + timeout;
622            Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
623            intent.putExtra("seq", mDelayedShowingSequence);
624            PendingIntent sender = PendingIntent.getBroadcast(mContext,
625                    0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
626            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender);
627            if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = "
628                             + mDelayedShowingSequence);
629        }
630    }
631
632    private void cancelDoKeyguardLaterLocked() {
633        mDelayedShowingSequence++;
634    }
635
636    /**
637     * Let's us know the screen was turned on.
638     */
639    public void onScreenTurnedOn(KeyguardViewManager.ShowListener showListener) {
640        synchronized (this) {
641            mScreenOn = true;
642            cancelDoKeyguardLaterLocked();
643            if (DEBUG) Log.d(TAG, "onScreenTurnedOn, seq = " + mDelayedShowingSequence);
644            if (showListener != null) {
645                notifyScreenOnLocked(showListener);
646            }
647        }
648        maybeSendUserPresentBroadcast();
649    }
650
651    private void maybeSendUserPresentBroadcast() {
652        if (mSystemReady && mLockPatternUtils.isLockScreenDisabled()
653                && mUserManager.getUsers(true).size() == 1) {
654            // Lock screen is disabled because the user has set the preference to "None".
655            // In this case, send out ACTION_USER_PRESENT here instead of in
656            // handleKeyguardDone()
657            sendUserPresentBroadcast();
658        }
659    }
660
661    /**
662     * A dream started.  We should lock after the usual screen-off lock timeout but only
663     * if there is a secure lock pattern.
664     */
665    public void onDreamingStarted() {
666        synchronized (this) {
667            if (mScreenOn && mLockPatternUtils.isSecure()) {
668                doKeyguardLaterLocked();
669            }
670        }
671    }
672
673    /**
674     * A dream stopped.
675     */
676    public void onDreamingStopped() {
677        synchronized (this) {
678            if (mScreenOn) {
679                cancelDoKeyguardLaterLocked();
680            }
681        }
682    }
683
684    /**
685     * Same semantics as {@link WindowManagerPolicy#enableKeyguard}; provide
686     * a way for external stuff to override normal keyguard behavior.  For instance
687     * the phone app disables the keyguard when it receives incoming calls.
688     */
689    public void setKeyguardEnabled(boolean enabled) {
690        synchronized (this) {
691            if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
692
693            mExternallyEnabled = enabled;
694
695            if (!enabled && mShowing) {
696                if (mExitSecureCallback != null) {
697                    if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
698                    // we're in the process of handling a request to verify the user
699                    // can get past the keyguard. ignore extraneous requests to disable / reenable
700                    return;
701                }
702
703                // hiding keyguard that is showing, remember to reshow later
704                if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
705                        + "disabling status bar expansion");
706                mNeedToReshowWhenReenabled = true;
707                hideLocked();
708            } else if (enabled && mNeedToReshowWhenReenabled) {
709                // reenabled after previously hidden, reshow
710                if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
711                        + "status bar expansion");
712                mNeedToReshowWhenReenabled = false;
713
714                if (mExitSecureCallback != null) {
715                    if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
716                    mExitSecureCallback.onKeyguardExitResult(false);
717                    mExitSecureCallback = null;
718                    resetStateLocked(null);
719                } else {
720                    showLocked(null);
721
722                    // block until we know the keygaurd is done drawing (and post a message
723                    // to unblock us after a timeout so we don't risk blocking too long
724                    // and causing an ANR).
725                    mWaitingUntilKeyguardVisible = true;
726                    mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
727                    if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
728                    while (mWaitingUntilKeyguardVisible) {
729                        try {
730                            wait();
731                        } catch (InterruptedException e) {
732                            Thread.currentThread().interrupt();
733                        }
734                    }
735                    if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
736                }
737            }
738        }
739    }
740
741    /**
742     * @see android.app.KeyguardManager#exitKeyguardSecurely
743     */
744    public void verifyUnlock(WindowManagerPolicy.OnKeyguardExitResult callback) {
745        synchronized (this) {
746            if (DEBUG) Log.d(TAG, "verifyUnlock");
747            if (!mUpdateMonitor.isDeviceProvisioned()) {
748                // don't allow this api when the device isn't provisioned
749                if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
750                callback.onKeyguardExitResult(false);
751            } else if (mExternallyEnabled) {
752                // this only applies when the user has externally disabled the
753                // keyguard.  this is unexpected and means the user is not
754                // using the api properly.
755                Log.w(TAG, "verifyUnlock called when not externally disabled");
756                callback.onKeyguardExitResult(false);
757            } else if (mExitSecureCallback != null) {
758                // already in progress with someone else
759                callback.onKeyguardExitResult(false);
760            } else {
761                mExitSecureCallback = callback;
762                verifyUnlockLocked();
763            }
764        }
765    }
766
767    /**
768     * Is the keyguard currently showing?
769     */
770    public boolean isShowing() {
771        return mShowing;
772    }
773
774    /**
775     * Is the keyguard currently showing and not being force hidden?
776     */
777    public boolean isShowingAndNotHidden() {
778        return mShowing && !mHidden;
779    }
780
781    /**
782     * Notify us when the keyguard is hidden by another window
783     */
784    public void setHidden(boolean isHidden) {
785        if (DEBUG) Log.d(TAG, "setHidden " + isHidden);
786        mUpdateMonitor.sendKeyguardVisibilityChanged(!isHidden);
787        mHandler.removeMessages(SET_HIDDEN);
788        Message msg = mHandler.obtainMessage(SET_HIDDEN, (isHidden ? 1 : 0), 0);
789        mHandler.sendMessage(msg);
790    }
791
792    /**
793     * Handles SET_HIDDEN message sent by setHidden()
794     */
795    private void handleSetHidden(boolean isHidden) {
796        synchronized (KeyguardViewMediator.this) {
797            if (mHidden != isHidden) {
798                mHidden = isHidden;
799                updateActivityLockScreenState();
800                adjustStatusBarLocked();
801            }
802        }
803    }
804
805    /**
806     * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout.
807     * This must be safe to call from any thread and with any window manager locks held.
808     */
809    public void doKeyguardTimeout(Bundle options) {
810        mHandler.removeMessages(KEYGUARD_TIMEOUT);
811        Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
812        mHandler.sendMessage(msg);
813    }
814
815    /**
816     * Given the state of the keyguard, is the input restricted?
817     * Input is restricted when the keyguard is showing, or when the keyguard
818     * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.
819     */
820    public boolean isInputRestricted() {
821        return mShowing || mNeedToReshowWhenReenabled || !mUpdateMonitor.isDeviceProvisioned();
822    }
823
824    private void doKeyguardLocked() {
825        doKeyguardLocked(null);
826    }
827
828    /**
829     * Enable the keyguard if the settings are appropriate.
830     */
831    private void doKeyguardLocked(Bundle options) {
832        // if another app is disabling us, don't show
833        if (!mExternallyEnabled) {
834            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");
835
836            // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes
837            // for an occasional ugly flicker in this situation:
838            // 1) receive a call with the screen on (no keyguard) or make a call
839            // 2) screen times out
840            // 3) user hits key to turn screen back on
841            // instead, we reenable the keyguard when we know the screen is off and the call
842            // ends (see the broadcast receiver below)
843            // TODO: clean this up when we have better support at the window manager level
844            // for apps that wish to be on top of the keyguard
845            return;
846        }
847
848        // if the keyguard is already showing, don't bother
849        if (mKeyguardViewManager.isShowing()) {
850            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
851            return;
852        }
853
854        // if the setup wizard hasn't run yet, don't show
855        final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim",
856                false);
857        final boolean provisioned = mUpdateMonitor.isDeviceProvisioned();
858        final IccCardConstants.State state = mUpdateMonitor.getSimState();
859        final boolean lockedOrMissing = state.isPinLocked()
860                || ((state == IccCardConstants.State.ABSENT
861                || state == IccCardConstants.State.PERM_DISABLED)
862                && requireSim);
863
864        if (!lockedOrMissing && !provisioned) {
865            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
866                    + " and the sim is not locked or missing");
867            return;
868        }
869
870        if (mUserManager.getUsers(true).size() < 2
871                && mLockPatternUtils.isLockScreenDisabled() && !lockedOrMissing) {
872            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
873            return;
874        }
875
876        if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
877        showLocked(options);
878    }
879
880    /**
881     * Dismiss the keyguard through the security layers.
882     */
883    public void dismiss() {
884        mKeyguardViewManager.dismiss();
885    }
886
887    /**
888     * Send message to keyguard telling it to reset its state.
889     * @param options options about how to show the keyguard
890     * @see #handleReset()
891     */
892    private void resetStateLocked(Bundle options) {
893        if (DEBUG) Log.d(TAG, "resetStateLocked");
894        Message msg = mHandler.obtainMessage(RESET, options);
895        mHandler.sendMessage(msg);
896    }
897
898    /**
899     * Send message to keyguard telling it to verify unlock
900     * @see #handleVerifyUnlock()
901     */
902    private void verifyUnlockLocked() {
903        if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
904        mHandler.sendEmptyMessage(VERIFY_UNLOCK);
905    }
906
907
908    /**
909     * Send a message to keyguard telling it the screen just turned on.
910     * @see #onScreenTurnedOff(int)
911     * @see #handleNotifyScreenOff
912     */
913    private void notifyScreenOffLocked() {
914        if (DEBUG) Log.d(TAG, "notifyScreenOffLocked");
915        mHandler.sendEmptyMessage(NOTIFY_SCREEN_OFF);
916    }
917
918    /**
919     * Send a message to keyguard telling it the screen just turned on.
920     * @see #onScreenTurnedOn()
921     * @see #handleNotifyScreenOn
922     */
923    private void notifyScreenOnLocked(KeyguardViewManager.ShowListener showListener) {
924        if (DEBUG) Log.d(TAG, "notifyScreenOnLocked");
925        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_ON, showListener);
926        mHandler.sendMessage(msg);
927    }
928
929    /**
930     * Send message to keyguard telling it about a wake key so it can adjust
931     * its state accordingly and then poke the wake lock when it is ready.
932     * @param keyCode The wake key.
933     * @see #handleWakeWhenReady
934     * @see #onWakeKeyWhenKeyguardShowingTq(int)
935     */
936    private void wakeWhenReady(int keyCode) {
937        if (DBG_WAKE) Log.d(TAG, "wakeWhenReady(" + keyCode + ")");
938
939        /**
940         * acquire the handoff lock that will keep the cpu running.  this will
941         * be released once the keyguard has set itself up and poked the other wakelock
942         * in {@link #handleWakeWhenReady(int)}
943         */
944        mWakeAndHandOff.acquire();
945
946        Message msg = mHandler.obtainMessage(WAKE_WHEN_READY, keyCode, 0);
947        mHandler.sendMessage(msg);
948    }
949
950    /**
951     * Send message to keyguard telling it to show itself
952     * @see #handleShow()
953     */
954    private void showLocked(Bundle options) {
955        if (DEBUG) Log.d(TAG, "showLocked");
956        // ensure we stay awake until we are finished displaying the keyguard
957        mShowKeyguardWakeLock.acquire();
958        Message msg = mHandler.obtainMessage(SHOW, options);
959        mHandler.sendMessage(msg);
960    }
961
962    /**
963     * Send message to keyguard telling it to hide itself
964     * @see #handleHide()
965     */
966    private void hideLocked() {
967        if (DEBUG) Log.d(TAG, "hideLocked");
968        Message msg = mHandler.obtainMessage(HIDE);
969        mHandler.sendMessage(msg);
970    }
971
972    public boolean isSecure() {
973        return mLockPatternUtils.isSecure()
974            || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
975    }
976
977    /**
978     * Update the newUserId. Call while holding WindowManagerService lock.
979     * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.
980     *
981     * @param newUserId The id of the incoming user.
982     */
983    public void setCurrentUser(int newUserId) {
984        mLockPatternUtils.setCurrentUser(newUserId);
985    }
986
987    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
988        @Override
989        public void onReceive(Context context, Intent intent) {
990            if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {
991                final int sequence = intent.getIntExtra("seq", 0);
992                if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
993                        + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
994                synchronized (KeyguardViewMediator.this) {
995                    if (mDelayedShowingSequence == sequence) {
996                        // Don't play lockscreen SFX if the screen went off due to timeout.
997                        mSuppressNextLockSound = true;
998                        doKeyguardLocked();
999                    }
1000                }
1001            }
1002        }
1003    };
1004
1005    /**
1006     * When a key is received when the screen is off and the keyguard is showing,
1007     * we need to decide whether to actually turn on the screen, and if so, tell
1008     * the keyguard to prepare itself and poke the wake lock when it is ready.
1009     *
1010     * The 'Tq' suffix is per the documentation in {@link WindowManagerPolicy}.
1011     * Be sure not to take any action that takes a long time; any significant
1012     * action should be posted to a handler.
1013     *
1014     * @param keyCode The keycode of the key that woke the device
1015     */
1016    public void onWakeKeyWhenKeyguardShowingTq(int keyCode) {
1017        if (DEBUG) Log.d(TAG, "onWakeKeyWhenKeyguardShowing(" + keyCode + ")");
1018
1019        // give the keyguard view manager a chance to adjust the state of the
1020        // keyguard based on the key that woke the device before poking
1021        // the wake lock
1022        wakeWhenReady(keyCode);
1023    }
1024
1025    /**
1026     * When a wake motion such as an external mouse movement is received when the screen
1027     * is off and the keyguard is showing, we need to decide whether to actually turn
1028     * on the screen, and if so, tell the keyguard to prepare itself and poke the wake
1029     * lock when it is ready.
1030     *
1031     * The 'Tq' suffix is per the documentation in {@link WindowManagerPolicy}.
1032     * Be sure not to take any action that takes a long time; any significant
1033     * action should be posted to a handler.
1034     */
1035    public void onWakeMotionWhenKeyguardShowingTq() {
1036        if (DEBUG) Log.d(TAG, "onWakeMotionWhenKeyguardShowing()");
1037
1038        // give the keyguard view manager a chance to adjust the state of the
1039        // keyguard based on the key that woke the device before poking
1040        // the wake lock
1041        wakeWhenReady(KeyEvent.KEYCODE_UNKNOWN);
1042    }
1043
1044    public void keyguardDone(boolean authenticated, boolean wakeup) {
1045        synchronized (this) {
1046            EventLog.writeEvent(70000, 2);
1047            if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated + ")");
1048            Message msg = mHandler.obtainMessage(KEYGUARD_DONE);
1049            msg.arg1 = wakeup ? 1 : 0;
1050            mHandler.sendMessage(msg);
1051
1052            if (authenticated) {
1053                mUpdateMonitor.clearFailedUnlockAttempts();
1054            }
1055
1056            if (mExitSecureCallback != null) {
1057                mExitSecureCallback.onKeyguardExitResult(authenticated);
1058                mExitSecureCallback = null;
1059
1060                if (authenticated) {
1061                    // after succesfully exiting securely, no need to reshow
1062                    // the keyguard when they've released the lock
1063                    mExternallyEnabled = true;
1064                    mNeedToReshowWhenReenabled = false;
1065                }
1066            }
1067        }
1068    }
1069
1070    /**
1071     * This handler will be associated with the policy thread, which will also
1072     * be the UI thread of the keyguard.  Since the apis of the policy, and therefore
1073     * this class, can be called by other threads, any action that directly
1074     * interacts with the keyguard ui should be posted to this handler, rather
1075     * than called directly.
1076     */
1077    private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
1078        @Override
1079        public void handleMessage(Message msg) {
1080            switch (msg.what) {
1081                case SHOW:
1082                    handleShow((Bundle) msg.obj);
1083                    return ;
1084                case HIDE:
1085                    handleHide();
1086                    return ;
1087                case RESET:
1088                    handleReset((Bundle) msg.obj);
1089                    return ;
1090                case VERIFY_UNLOCK:
1091                    handleVerifyUnlock();
1092                    return;
1093                case NOTIFY_SCREEN_OFF:
1094                    handleNotifyScreenOff();
1095                    return;
1096                case NOTIFY_SCREEN_ON:
1097                    handleNotifyScreenOn((KeyguardViewManager.ShowListener)msg.obj);
1098                    return;
1099                case WAKE_WHEN_READY:
1100                    handleWakeWhenReady(msg.arg1);
1101                    return;
1102                case KEYGUARD_DONE:
1103                    handleKeyguardDone(msg.arg1 != 0);
1104                    return;
1105                case KEYGUARD_DONE_DRAWING:
1106                    handleKeyguardDoneDrawing();
1107                    return;
1108                case KEYGUARD_DONE_AUTHENTICATING:
1109                    keyguardDone(true, true);
1110                    return;
1111                case SET_HIDDEN:
1112                    handleSetHidden(msg.arg1 != 0);
1113                    break;
1114                case KEYGUARD_TIMEOUT:
1115                    synchronized (KeyguardViewMediator.this) {
1116                        doKeyguardLocked((Bundle) msg.obj);
1117                    }
1118                    break;
1119            }
1120        }
1121    };
1122
1123    /**
1124     * @see #keyguardDone
1125     * @see #KEYGUARD_DONE
1126     */
1127    private void handleKeyguardDone(boolean wakeup) {
1128        if (DEBUG) Log.d(TAG, "handleKeyguardDone");
1129        handleHide();
1130        if (wakeup) {
1131            wakeUp();
1132        }
1133
1134        sendUserPresentBroadcast();
1135    }
1136
1137    private void sendUserPresentBroadcast() {
1138        if (!(mContext instanceof Activity)) {
1139            final UserHandle currentUser = new UserHandle(mLockPatternUtils.getCurrentUser());
1140            mContext.sendBroadcastAsUser(mUserPresentIntent, currentUser);
1141        }
1142    }
1143
1144    /**
1145     * @see #keyguardDoneDrawing
1146     * @see #KEYGUARD_DONE_DRAWING
1147     */
1148    private void handleKeyguardDoneDrawing() {
1149        synchronized(this) {
1150            if (false) Log.d(TAG, "handleKeyguardDoneDrawing");
1151            if (mWaitingUntilKeyguardVisible) {
1152                if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
1153                mWaitingUntilKeyguardVisible = false;
1154                notifyAll();
1155
1156                // there will usually be two of these sent, one as a timeout, and one
1157                // as a result of the callback, so remove any remaining messages from
1158                // the queue
1159                mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
1160            }
1161        }
1162    }
1163
1164    private void playSounds(boolean locked) {
1165        // User feedback for keyguard.
1166
1167        if (mSuppressNextLockSound) {
1168            mSuppressNextLockSound = false;
1169            return;
1170        }
1171
1172        final ContentResolver cr = mContext.getContentResolver();
1173        if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
1174            final int whichSound = locked
1175                ? mLockSoundId
1176                : mUnlockSoundId;
1177            mLockSounds.stop(mLockSoundStreamId);
1178            // Init mAudioManager
1179            if (mAudioManager == null) {
1180                mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
1181                if (mAudioManager == null) return;
1182                mMasterStreamType = mAudioManager.getMasterStreamType();
1183            }
1184            // If the stream is muted, don't play the sound
1185            if (mAudioManager.isStreamMute(mMasterStreamType)) return;
1186
1187            mLockSoundStreamId = mLockSounds.play(whichSound,
1188                    mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
1189        }
1190    }
1191
1192    private void updateActivityLockScreenState() {
1193        try {
1194            ActivityManagerNative.getDefault().setLockScreenShown(
1195                    mShowing && !mHidden);
1196        } catch (RemoteException e) {
1197        }
1198    }
1199
1200    /**
1201     * Handle message sent by {@link #showLocked}.
1202     * @see #SHOW
1203     */
1204    private void handleShow(Bundle options) {
1205        synchronized (KeyguardViewMediator.this) {
1206            if (DEBUG) Log.d(TAG, "handleShow");
1207            if (!mSystemReady) return;
1208
1209            mKeyguardViewManager.show(options);
1210            mShowing = true;
1211            updateActivityLockScreenState();
1212            adjustStatusBarLocked();
1213            userActivity();
1214            try {
1215                ActivityManagerNative.getDefault().closeSystemDialogs("lock");
1216            } catch (RemoteException e) {
1217            }
1218
1219            // Do this at the end to not slow down display of the keyguard.
1220            playSounds(true);
1221
1222            mShowKeyguardWakeLock.release();
1223        }
1224    }
1225
1226    /**
1227     * Handle message sent by {@link #hideLocked()}
1228     * @see #HIDE
1229     */
1230    private void handleHide() {
1231        synchronized (KeyguardViewMediator.this) {
1232            if (DEBUG) Log.d(TAG, "handleHide");
1233            if (mWakeAndHandOff.isHeld()) {
1234                Log.w(TAG, "attempt to hide the keyguard while waking, ignored");
1235                return;
1236            }
1237
1238            // only play "unlock" noises if not on a call (since the incall UI
1239            // disables the keyguard)
1240            if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
1241                playSounds(false);
1242            }
1243
1244            mKeyguardViewManager.hide();
1245            mShowing = false;
1246            updateActivityLockScreenState();
1247            adjustStatusBarLocked();
1248        }
1249    }
1250
1251    private void adjustStatusBarLocked() {
1252        if (mStatusBarManager == null) {
1253            mStatusBarManager = (StatusBarManager)
1254                    mContext.getSystemService(Context.STATUS_BAR_SERVICE);
1255        }
1256        if (mStatusBarManager == null) {
1257            Log.w(TAG, "Could not get status bar manager");
1258        } else {
1259            if (mShowLockIcon) {
1260                // Give feedback to user when secure keyguard is active and engaged
1261                if (mShowing && isSecure()) {
1262                    if (!mShowingLockIcon) {
1263                        String contentDescription = mContext.getString(
1264                                com.android.internal.R.string.status_bar_device_locked);
1265                        mStatusBarManager.setIcon("secure",
1266                                com.android.internal.R.drawable.stat_sys_secure, 0,
1267                                contentDescription);
1268                        mShowingLockIcon = true;
1269                    }
1270                } else {
1271                    if (mShowingLockIcon) {
1272                        mStatusBarManager.removeIcon("secure");
1273                        mShowingLockIcon = false;
1274                    }
1275                }
1276            }
1277
1278            // Disable aspects of the system/status/navigation bars that must not be re-enabled by
1279            // windows that appear on top, ever
1280            int flags = StatusBarManager.DISABLE_NONE;
1281            if (mShowing) {
1282                // Permanently disable components not available when keyguard is enabled
1283                // (like recents). Temporary enable/disable (e.g. the "back" button) are
1284                // done in KeyguardHostView.
1285                flags |= StatusBarManager.DISABLE_RECENT;
1286                if (isSecure() || !ENABLE_INSECURE_STATUS_BAR_EXPAND) {
1287                    // showing secure lockscreen; disable expanding.
1288                    flags |= StatusBarManager.DISABLE_EXPAND;
1289                }
1290                if (isSecure()) {
1291                    // showing secure lockscreen; disable ticker.
1292                    flags |= StatusBarManager.DISABLE_NOTIFICATION_TICKER;
1293                }
1294            }
1295
1296            if (DEBUG) {
1297                Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mHidden=" + mHidden
1298                        + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
1299            }
1300
1301            if (!(mContext instanceof Activity)) {
1302                mStatusBarManager.disable(flags);
1303            }
1304        }
1305    }
1306
1307    /**
1308     * Handle message sent by {@link #wakeWhenReady(int)}
1309     * @param keyCode The key that woke the device.
1310     * @see #WAKE_WHEN_READY
1311     */
1312    private void handleWakeWhenReady(int keyCode) {
1313        synchronized (KeyguardViewMediator.this) {
1314            if (DBG_WAKE) Log.d(TAG, "handleWakeWhenReady(" + keyCode + ")");
1315
1316            // this should result in a call to 'poke wakelock' which will set a timeout
1317            // on releasing the wakelock
1318            if (!mKeyguardViewManager.wakeWhenReadyTq(keyCode)) {
1319                // poke wakelock ourselves if keyguard is no longer active
1320                Log.w(TAG, "mKeyguardViewManager.wakeWhenReadyTq did not poke wake lock, so poke it ourselves");
1321                userActivity();
1322            }
1323
1324            /**
1325             * Now that the keyguard is ready and has poked the wake lock, we can
1326             * release the handoff wakelock
1327             */
1328            mWakeAndHandOff.release();
1329        }
1330    }
1331
1332    /**
1333     * Handle message sent by {@link #resetStateLocked(Bundle)}
1334     * @see #RESET
1335     */
1336    private void handleReset(Bundle options) {
1337        synchronized (KeyguardViewMediator.this) {
1338            if (DEBUG) Log.d(TAG, "handleReset");
1339            mKeyguardViewManager.reset(options);
1340        }
1341    }
1342
1343    /**
1344     * Handle message sent by {@link #verifyUnlock}
1345     * @see #VERIFY_UNLOCK
1346     */
1347    private void handleVerifyUnlock() {
1348        synchronized (KeyguardViewMediator.this) {
1349            if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
1350            mKeyguardViewManager.verifyUnlock();
1351            mShowing = true;
1352            updateActivityLockScreenState();
1353        }
1354    }
1355
1356    /**
1357     * Handle message sent by {@link #notifyScreenOffLocked()}
1358     * @see #NOTIFY_SCREEN_OFF
1359     */
1360    private void handleNotifyScreenOff() {
1361        synchronized (KeyguardViewMediator.this) {
1362            if (DEBUG) Log.d(TAG, "handleNotifyScreenOff");
1363            mKeyguardViewManager.onScreenTurnedOff();
1364        }
1365    }
1366
1367    /**
1368     * Handle message sent by {@link #notifyScreenOnLocked()}
1369     * @see #NOTIFY_SCREEN_ON
1370     */
1371    private void handleNotifyScreenOn(KeyguardViewManager.ShowListener showListener) {
1372        synchronized (KeyguardViewMediator.this) {
1373            if (DEBUG) Log.d(TAG, "handleNotifyScreenOn");
1374            mKeyguardViewManager.onScreenTurnedOn(showListener);
1375        }
1376    }
1377
1378}
1379