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