OSDN Git Service

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