2 * Copyright (C) 2014 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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
17 package com.android.systemui.keyguard;
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;
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;
70 import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
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.
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.
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?
88 * Callbacks to the phone window manager:
89 * - the keyguard is showing
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
96 * Events from the keyguard view:
97 * - user succesfully unlocked keyguard -> hide keyguard view, and no longer
98 * restrict input events.
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.
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.
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;
119 private final static String TAG = "KeyguardViewMediator";
121 private static final String DELAYED_KEYGUARD_ACTION =
122 "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_KEYGUARD";
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;
140 * The default amount of time we stay awake (used for all key input)
142 public static final int AWAKE_INTERVAL_DEFAULT_MS = 10000;
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).
149 private static final int KEYGUARD_LOCK_AFTER_DELAY_DEFAULT = 5000;
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.
156 private static final int KEYGUARD_DONE_DRAWING_TIMEOUT_MS = 2000;
159 * Secure setting whether analytics are collected on the keyguard.
161 private static final String KEYGUARD_ANALYTICS_SETTING = "keyguard_analytics";
163 /** The stream type that the lock sounds are tied to. */
164 private int mMasterStreamType;
166 private AlarmManager mAlarmManager;
167 private AudioManager mAudioManager;
168 private StatusBarManager mStatusBarManager;
169 private boolean mSwitchingUser;
171 private boolean mSystemReady;
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;
178 /** High level access to the power manager for WakeLocks */
179 private PowerManager mPM;
181 /** High level access to the window manager for dismissing keyguard animation */
182 private IWindowManager mWM;
184 /** UserManager for querying number of users */
185 private UserManager mUserManager;
187 /** SearchManager for determining whether or not search assistant is available */
188 private SearchManager mSearchManager;
191 * Used to keep the device awake while to ensure the keyguard finishes opening before
194 private PowerManager.WakeLock mShowKeyguardWakeLock;
196 private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
198 // these are protected by synchronized (this)
201 * External apps (like the phone app) can tell us to disable the keygaurd.
203 private boolean mExternallyEnabled = true;
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.
210 private boolean mNeedToReshowWhenReenabled = false;
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;
216 // true if the keyguard is hidden by another window
217 private boolean mOccluded = false;
220 * Helps remember whether the screen has turned on since the last time
221 * it turned off due to timeout. see {@link #onScreenTurnedOff(int)}
223 private int mDelayedShowingSequence;
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.
230 private IKeyguardExitCallback mExitSecureCallback;
232 // the properties of the keyguard
234 private KeyguardUpdateMonitor mUpdateMonitor;
236 private boolean mScreenOn;
238 // last known state of the cellular connection
239 private String mPhoneState = TelephonyManager.EXTRA_STATE_IDLE;
242 * Whether a hide is pending an we are just waiting for #startKeyguardExitAnimation to be
245 private boolean mHiding;
248 * we send this intent when the keyguard is dismissed.
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);
255 * {@link #setKeyguardEnabled} waits on this condition when it reenables
258 private boolean mWaitingUntilKeyguardVisible = false;
259 private LockPatternUtils mLockPatternUtils;
260 private boolean mKeyguardDonePending = false;
262 private SoundPool mLockSounds;
263 private int mLockSoundId;
264 private int mUnlockSoundId;
265 private int mLockSoundStreamId;
268 * The volume applied to the lock/unlock sounds.
270 private float mLockSoundVolume;
273 * For managing external displays
275 private KeyguardDisplayManager mKeyguardDisplayManager;
277 KeyguardUpdateMonitorCallback mUpdateCallback = new KeyguardUpdateMonitorCallback() {
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;
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);
295 public void onUserSwitchComplete(int userId) {
296 mSwitchingUser = false;
300 public void onUserRemoved(int userId) {
301 mLockPatternUtils.removeUser(userId);
302 MultiUserAvatarCache.getInstance().clear(userId);
306 public void onUserInfoChanged(int userId) {
307 MultiUserAvatarCache.getInstance().clear(userId);
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
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);
329 public void onClockVisibilityChanged() {
330 adjustStatusBarLocked();
334 public void onDeviceProvisioned() {
335 sendUserPresentBroadcast();
339 public void onSimStateChanged(IccCardConstants.State simState) {
340 if (DEBUG) Log.d(TAG, "onSimStateChanged: " + simState);
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()) {
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);
362 synchronized (this) {
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);
373 synchronized (this) {
375 if (DEBUG) Log.d(TAG, "PERM_DISABLED and "
376 + "keygaurd isn't showing.");
377 doKeyguardLocked(null);
379 if (DEBUG) Log.d(TAG, "PERM_DISABLED, resetStateLocked to"
380 + "show permanently disabled message in lockscreen.");
386 synchronized (this) {
395 public void onFingerprintRecognized(int userId) {
396 if (mStatusBarKeyguardViewManager.isBouncerShowing()) {
397 mViewMediatorCallback.keyguardDone(true);
403 ViewMediatorCallback mViewMediatorCallback = new ViewMediatorCallback() {
405 public void userActivity() {
406 KeyguardViewMediator.this.userActivity();
409 public void userActivity(long holdMs) {
410 KeyguardViewMediator.this.userActivity(holdMs);
413 public void keyguardDone(boolean authenticated) {
414 KeyguardViewMediator.this.keyguardDone(authenticated, true);
417 public void keyguardDoneDrawing() {
418 mHandler.sendEmptyMessage(KEYGUARD_DONE_DRAWING);
422 public void setNeedsInput(boolean needsInput) {
423 mStatusBarKeyguardViewManager.setNeedsInput(needsInput);
427 public void onUserActivityTimeoutChanged() {
428 mStatusBarKeyguardViewManager.updateUserActivityTimeout();
432 public void keyguardDonePending() {
433 mKeyguardDonePending = true;
437 public void keyguardGone() {
438 mKeyguardDisplayManager.hide();
442 private void userActivity() {
443 userActivity(AWAKE_INTERVAL_DEFAULT_MS);
446 public void userActivity(long holdMs) {
447 // We ignore the hold time. Eventually we should remove it.
448 // Instead, the keyguard window has an explicit user activity timeout set on it.
449 mPM.userActivity(SystemClock.uptimeMillis(), false);
452 private void setup() {
453 mPM = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
454 mWM = WindowManagerGlobal.getWindowManagerService();
455 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
456 mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "show keyguard");
457 mShowKeyguardWakeLock.setReferenceCounted(false);
459 mContext.registerReceiver(mBroadcastReceiver, new IntentFilter(DELAYED_KEYGUARD_ACTION));
461 mKeyguardDisplayManager = new KeyguardDisplayManager(mContext);
463 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
465 mUpdateMonitor = KeyguardUpdateMonitor.getInstance(mContext);
467 mLockPatternUtils = new LockPatternUtils(mContext);
468 mLockPatternUtils.setCurrentUser(UserHandle.USER_OWNER);
470 // Assume keyguard is showing (unless it's disabled) until we know for sure...
471 mShowing = (mUpdateMonitor.isDeviceProvisioned() || mLockPatternUtils.isSecure())
472 && !mLockPatternUtils.isLockScreenDisabled();
474 mStatusBarKeyguardViewManager = new StatusBarKeyguardViewManager(mContext,
475 mViewMediatorCallback, mLockPatternUtils);
476 final ContentResolver cr = mContext.getContentResolver();
478 mScreenOn = mPM.isScreenOn();
480 mLockSounds = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
481 String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND);
482 if (soundPath != null) {
483 mLockSoundId = mLockSounds.load(soundPath, 1);
485 if (soundPath == null || mLockSoundId == 0) {
486 Log.w(TAG, "failed to load lock sound from " + soundPath);
488 soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND);
489 if (soundPath != null) {
490 mUnlockSoundId = mLockSounds.load(soundPath, 1);
492 if (soundPath == null || mUnlockSoundId == 0) {
493 Log.w(TAG, "failed to load unlock sound from " + soundPath);
495 int lockSoundDefaultAttenuation = mContext.getResources().getInteger(
496 com.android.internal.R.integer.config_lockSoundVolumeDb);
497 mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20);
501 public void start() {
503 putComponent(KeyguardViewMediator.class, this);
507 * Let us know that the system is ready after startup.
509 public void onSystemReady() {
510 mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
511 synchronized (this) {
512 if (DEBUG) Log.d(TAG, "onSystemReady");
514 mUpdateMonitor.registerCallback(mUpdateCallback);
516 // Suppress biometric unlock right after boot until things have settled if it is the
517 // selected security method, otherwise unsuppress it. It must be unsuppressed if it is
518 // not the selected security method for the following reason: if the user starts
519 // without a screen lock selected, the biometric unlock would be suppressed the first
520 // time they try to use it.
522 // Note that the biometric unlock will still not show if it is not the selected method.
523 // Calling setAlternateUnlockEnabled(true) simply says don't suppress it if it is the
525 if (mLockPatternUtils.usingBiometricWeak()
526 && mLockPatternUtils.isBiometricWeakInstalled()) {
527 if (DEBUG) Log.d(TAG, "suppressing biometric unlock during boot");
528 mUpdateMonitor.setAlternateUnlockEnabled(false);
530 mUpdateMonitor.setAlternateUnlockEnabled(true);
533 doKeyguardLocked(null);
535 // Most services aren't available until the system reaches the ready state, so we
536 // send it here when the device first boots.
537 maybeSendUserPresentBroadcast();
541 * Called to let us know the screen was turned off.
542 * @param why either {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_USER} or
543 * {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT}.
545 public void onScreenTurnedOff(int why) {
546 synchronized (this) {
548 if (DEBUG) Log.d(TAG, "onScreenTurnedOff(" + why + ")");
550 mKeyguardDonePending = false;
552 // Lock immediately based on setting if secure (user has a pin/pattern/password).
553 // This also "locks" the device when not secure to provide easy access to the
554 // camera while preventing unwanted input.
555 final boolean lockImmediately =
556 mLockPatternUtils.getPowerButtonInstantlyLocks() || !mLockPatternUtils.isSecure();
558 if (mExitSecureCallback != null) {
559 if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
561 mExitSecureCallback.onKeyguardExitResult(false);
562 } catch (RemoteException e) {
563 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
565 mExitSecureCallback = null;
566 if (!mExternallyEnabled) {
569 } else if (mShowing) {
570 notifyScreenOffLocked();
572 } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT
573 || (why == WindowManagerPolicy.OFF_BECAUSE_OF_USER && !lockImmediately)) {
574 doKeyguardLaterLocked();
576 doKeyguardLocked(null);
579 KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurndOff(why);
582 private void doKeyguardLaterLocked() {
583 // if the screen turned off because of timeout or the user hit the power button
584 // and we don't need to lock immediately, set an alarm
585 // to enable it a little bit later (i.e, give the user a chance
586 // to turn the screen back on within a certain window without
587 // having to unlock the screen)
588 final ContentResolver cr = mContext.getContentResolver();
590 // From DisplaySettings
591 long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
592 KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);
594 // From SecuritySettings
595 final long lockAfterTimeout = Settings.Secure.getInt(cr,
596 Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
597 KEYGUARD_LOCK_AFTER_DELAY_DEFAULT);
599 // From DevicePolicyAdmin
600 final long policyTimeout = mLockPatternUtils.getDevicePolicyManager()
601 .getMaximumTimeToLock(null, mLockPatternUtils.getCurrentUser());
604 if (policyTimeout > 0) {
605 // policy in effect. Make sure we don't go beyond policy limit.
606 displayTimeout = Math.max(displayTimeout, 0); // ignore negative values
607 timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);
609 timeout = lockAfterTimeout;
614 mSuppressNextLockSound = true;
615 doKeyguardLocked(null);
617 // Lock in the future
618 long when = SystemClock.elapsedRealtime() + timeout;
619 Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
620 intent.putExtra("seq", mDelayedShowingSequence);
621 PendingIntent sender = PendingIntent.getBroadcast(mContext,
622 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
623 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender);
624 if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = "
625 + mDelayedShowingSequence);
629 private void cancelDoKeyguardLaterLocked() {
630 mDelayedShowingSequence++;
634 * Let's us know the screen was turned on.
636 public void onScreenTurnedOn(IKeyguardShowCallback callback) {
637 synchronized (this) {
639 cancelDoKeyguardLaterLocked();
640 if (DEBUG) Log.d(TAG, "onScreenTurnedOn, seq = " + mDelayedShowingSequence);
641 if (callback != null) {
642 notifyScreenOnLocked(callback);
645 KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurnedOn();
646 maybeSendUserPresentBroadcast();
649 private void maybeSendUserPresentBroadcast() {
650 if (mSystemReady && mLockPatternUtils.isLockScreenDisabled()
651 && !mUserManager.isUserSwitcherEnabled()) {
652 // Lock screen is disabled because the user has set the preference to "None".
653 // In this case, send out ACTION_USER_PRESENT here instead of in
654 // handleKeyguardDone()
655 sendUserPresentBroadcast();
660 * A dream started. We should lock after the usual screen-off lock timeout but only
661 * if there is a secure lock pattern.
663 public void onDreamingStarted() {
664 synchronized (this) {
665 if (mScreenOn && mLockPatternUtils.isSecure()) {
666 doKeyguardLaterLocked();
674 public void onDreamingStopped() {
675 synchronized (this) {
677 cancelDoKeyguardLaterLocked();
683 * Same semantics as {@link android.view.WindowManagerPolicy#enableKeyguard}; provide
684 * a way for external stuff to override normal keyguard behavior. For instance
685 * the phone app disables the keyguard when it receives incoming calls.
687 public void setKeyguardEnabled(boolean enabled) {
688 synchronized (this) {
689 if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
691 mExternallyEnabled = enabled;
693 if (!enabled && mShowing) {
694 if (mExitSecureCallback != null) {
695 if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
696 // we're in the process of handling a request to verify the user
697 // can get past the keyguard. ignore extraneous requests to disable / reenable
701 // hiding keyguard that is showing, remember to reshow later
702 if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
703 + "disabling status bar expansion");
704 mNeedToReshowWhenReenabled = true;
706 } else if (enabled && mNeedToReshowWhenReenabled) {
707 // reenabled after previously hidden, reshow
708 if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
709 + "status bar expansion");
710 mNeedToReshowWhenReenabled = false;
712 if (mExitSecureCallback != null) {
713 if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
715 mExitSecureCallback.onKeyguardExitResult(false);
716 } catch (RemoteException e) {
717 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
719 mExitSecureCallback = null;
724 // block until we know the keygaurd is done drawing (and post a message
725 // to unblock us after a timeout so we don't risk blocking too long
726 // and causing an ANR).
727 mWaitingUntilKeyguardVisible = true;
728 mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
729 if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
730 while (mWaitingUntilKeyguardVisible) {
733 } catch (InterruptedException e) {
734 Thread.currentThread().interrupt();
737 if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
744 * @see android.app.KeyguardManager#exitKeyguardSecurely
746 public void verifyUnlock(IKeyguardExitCallback callback) {
747 synchronized (this) {
748 if (DEBUG) Log.d(TAG, "verifyUnlock");
749 if (!mUpdateMonitor.isDeviceProvisioned()) {
750 // don't allow this api when the device isn't provisioned
751 if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
753 callback.onKeyguardExitResult(false);
754 } catch (RemoteException e) {
755 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
757 } else if (mExternallyEnabled) {
758 // this only applies when the user has externally disabled the
759 // keyguard. this is unexpected and means the user is not
760 // using the api properly.
761 Log.w(TAG, "verifyUnlock called when not externally disabled");
763 callback.onKeyguardExitResult(false);
764 } catch (RemoteException e) {
765 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
767 } else if (mExitSecureCallback != null) {
768 // already in progress with someone else
770 callback.onKeyguardExitResult(false);
771 } catch (RemoteException e) {
772 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
775 mExitSecureCallback = callback;
776 verifyUnlockLocked();
782 * Is the keyguard currently showing?
784 public boolean isShowing() {
788 public boolean isOccluded() {
793 * Is the keyguard currently showing and not being force hidden?
795 public boolean isShowingAndNotOccluded() {
796 return mShowing && !mOccluded;
800 * Notify us when the keyguard is occluded by another window
802 public void setOccluded(boolean isOccluded) {
803 if (DEBUG) Log.d(TAG, "setOccluded " + isOccluded);
804 mHandler.removeMessages(SET_OCCLUDED);
805 Message msg = mHandler.obtainMessage(SET_OCCLUDED, (isOccluded ? 1 : 0), 0);
806 mHandler.sendMessage(msg);
810 * Handles SET_OCCLUDED message sent by setOccluded()
812 private void handleSetOccluded(boolean isOccluded) {
813 synchronized (KeyguardViewMediator.this) {
814 if (mOccluded != isOccluded) {
815 mOccluded = isOccluded;
816 mStatusBarKeyguardViewManager.setOccluded(isOccluded);
817 updateActivityLockScreenState();
818 adjustStatusBarLocked();
824 * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout.
825 * This must be safe to call from any thread and with any window manager locks held.
827 public void doKeyguardTimeout(Bundle options) {
828 mHandler.removeMessages(KEYGUARD_TIMEOUT);
829 Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
830 mHandler.sendMessage(msg);
834 * Given the state of the keyguard, is the input restricted?
835 * Input is restricted when the keyguard is showing, or when the keyguard
836 * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.
838 public boolean isInputRestricted() {
839 return mShowing || mNeedToReshowWhenReenabled || !mUpdateMonitor.isDeviceProvisioned();
843 * Enable the keyguard if the settings are appropriate.
845 private void doKeyguardLocked(Bundle options) {
846 // if another app is disabling us, don't show
847 if (!mExternallyEnabled) {
848 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");
850 // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes
851 // for an occasional ugly flicker in this situation:
852 // 1) receive a call with the screen on (no keyguard) or make a call
853 // 2) screen times out
854 // 3) user hits key to turn screen back on
855 // instead, we reenable the keyguard when we know the screen is off and the call
856 // ends (see the broadcast receiver below)
857 // TODO: clean this up when we have better support at the window manager level
858 // for apps that wish to be on top of the keyguard
862 // if the keyguard is already showing, don't bother
863 if (mStatusBarKeyguardViewManager.isShowing()) {
864 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
868 // if the setup wizard hasn't run yet, don't show
869 final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim",
871 final boolean provisioned = mUpdateMonitor.isDeviceProvisioned();
872 final IccCardConstants.State state = mUpdateMonitor.getSimState();
873 final boolean lockedOrMissing = state.isPinLocked()
874 || ((state == IccCardConstants.State.ABSENT
875 || state == IccCardConstants.State.PERM_DISABLED)
878 if (!lockedOrMissing && !provisioned) {
879 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
880 + " and the sim is not locked or missing");
884 if (!mUserManager.isUserSwitcherEnabled()
885 && mLockPatternUtils.isLockScreenDisabled() && !lockedOrMissing) {
886 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
890 if (mLockPatternUtils.checkVoldPassword()) {
891 if (DEBUG) Log.d(TAG, "Not showing lock screen since just decrypted");
892 // Without this, settings is not enabled until the lock screen first appears
898 if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
903 * Dismiss the keyguard through the security layers.
905 public void handleDismiss() {
906 if (mShowing && !mOccluded) {
907 mStatusBarKeyguardViewManager.dismiss();
911 public void dismiss() {
912 mHandler.sendEmptyMessage(DISMISS);
916 * Send message to keyguard telling it to reset its state.
919 private void resetStateLocked() {
920 if (DEBUG) Log.e(TAG, "resetStateLocked");
921 Message msg = mHandler.obtainMessage(RESET);
922 mHandler.sendMessage(msg);
926 * Send message to keyguard telling it to verify unlock
927 * @see #handleVerifyUnlock()
929 private void verifyUnlockLocked() {
930 if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
931 mHandler.sendEmptyMessage(VERIFY_UNLOCK);
936 * Send a message to keyguard telling it the screen just turned on.
937 * @see #onScreenTurnedOff(int)
938 * @see #handleNotifyScreenOff
940 private void notifyScreenOffLocked() {
941 if (DEBUG) Log.d(TAG, "notifyScreenOffLocked");
942 mHandler.sendEmptyMessage(NOTIFY_SCREEN_OFF);
946 * Send a message to keyguard telling it the screen just turned on.
947 * @see #onScreenTurnedOn
948 * @see #handleNotifyScreenOn
950 private void notifyScreenOnLocked(IKeyguardShowCallback result) {
951 if (DEBUG) Log.d(TAG, "notifyScreenOnLocked");
952 Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_ON, result);
953 mHandler.sendMessage(msg);
957 * Send message to keyguard telling it to show itself
960 private void showLocked(Bundle options) {
961 if (DEBUG) Log.d(TAG, "showLocked");
962 // ensure we stay awake until we are finished displaying the keyguard
963 mShowKeyguardWakeLock.acquire();
964 Message msg = mHandler.obtainMessage(SHOW, options);
965 mHandler.sendMessage(msg);
969 * Send message to keyguard telling it to hide itself
972 private void hideLocked() {
973 if (DEBUG) Log.d(TAG, "hideLocked");
974 Message msg = mHandler.obtainMessage(HIDE);
975 mHandler.sendMessage(msg);
978 public boolean isSecure() {
979 return mLockPatternUtils.isSecure()
980 || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
984 * Update the newUserId. Call while holding WindowManagerService lock.
985 * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.
987 * @param newUserId The id of the incoming user.
989 public void setCurrentUser(int newUserId) {
990 mLockPatternUtils.setCurrentUser(newUserId);
993 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
995 public void onReceive(Context context, Intent intent) {
996 if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {
997 final int sequence = intent.getIntExtra("seq", 0);
998 if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
999 + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
1000 synchronized (KeyguardViewMediator.this) {
1001 if (mDelayedShowingSequence == sequence) {
1002 // Don't play lockscreen SFX if the screen went off due to timeout.
1003 mSuppressNextLockSound = true;
1004 doKeyguardLocked(null);
1011 public void keyguardDone(boolean authenticated, boolean wakeup) {
1012 if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated + ")");
1013 EventLog.writeEvent(70000, 2);
1014 synchronized (this) {
1015 mKeyguardDonePending = false;
1017 Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0, wakeup ? 1 : 0);
1018 mHandler.sendMessage(msg);
1022 * This handler will be associated with the policy thread, which will also
1023 * be the UI thread of the keyguard. Since the apis of the policy, and therefore
1024 * this class, can be called by other threads, any action that directly
1025 * interacts with the keyguard ui should be posted to this handler, rather
1026 * than called directly.
1028 private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
1030 public void handleMessage(Message msg) {
1033 handleShow((Bundle) msg.obj);
1042 handleVerifyUnlock();
1044 case NOTIFY_SCREEN_OFF:
1045 handleNotifyScreenOff();
1047 case NOTIFY_SCREEN_ON:
1048 handleNotifyScreenOn((IKeyguardShowCallback) msg.obj);
1051 handleKeyguardDone(msg.arg1 != 0, msg.arg2 != 0);
1053 case KEYGUARD_DONE_DRAWING:
1054 handleKeyguardDoneDrawing();
1056 case KEYGUARD_DONE_AUTHENTICATING:
1057 keyguardDone(true, true);
1060 handleSetOccluded(msg.arg1 != 0);
1062 case KEYGUARD_TIMEOUT:
1063 synchronized (KeyguardViewMediator.this) {
1064 doKeyguardLocked((Bundle) msg.obj);
1070 case START_KEYGUARD_EXIT_ANIM:
1071 StartKeyguardExitAnimParams params = (StartKeyguardExitAnimParams) msg.obj;
1072 handleStartKeyguardExitAnimation(params.startTime, params.fadeoutDuration);
1079 * @see #keyguardDone
1080 * @see #KEYGUARD_DONE
1082 private void handleKeyguardDone(boolean authenticated, boolean wakeup) {
1083 if (DEBUG) Log.d(TAG, "handleKeyguardDone");
1085 if (authenticated) {
1086 mUpdateMonitor.clearFailedUnlockAttempts();
1088 mUpdateMonitor.clearFingerprintRecognized();
1090 if (mExitSecureCallback != null) {
1092 mExitSecureCallback.onKeyguardExitResult(authenticated);
1093 } catch (RemoteException e) {
1094 Slog.w(TAG, "Failed to call onKeyguardExitResult(" + authenticated + ")", e);
1097 mExitSecureCallback = null;
1099 if (authenticated) {
1100 // after succesfully exiting securely, no need to reshow
1101 // the keyguard when they've released the lock
1102 mExternallyEnabled = true;
1103 mNeedToReshowWhenReenabled = false;
1108 sendUserPresentBroadcast();
1111 private void sendUserPresentBroadcast() {
1112 final UserHandle currentUser = new UserHandle(mLockPatternUtils.getCurrentUser());
1113 mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, currentUser);
1117 * @see #keyguardDone
1118 * @see #KEYGUARD_DONE_DRAWING
1120 private void handleKeyguardDoneDrawing() {
1121 synchronized(this) {
1122 if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing");
1123 if (mWaitingUntilKeyguardVisible) {
1124 if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
1125 mWaitingUntilKeyguardVisible = false;
1128 // there will usually be two of these sent, one as a timeout, and one
1129 // as a result of the callback, so remove any remaining messages from
1131 mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
1136 private void playSounds(boolean locked) {
1137 // User feedback for keyguard.
1139 if (mSuppressNextLockSound) {
1140 mSuppressNextLockSound = false;
1144 final ContentResolver cr = mContext.getContentResolver();
1145 if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
1146 final int whichSound = locked
1149 mLockSounds.stop(mLockSoundStreamId);
1150 // Init mAudioManager
1151 if (mAudioManager == null) {
1152 mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
1153 if (mAudioManager == null) return;
1154 mMasterStreamType = mAudioManager.getMasterStreamType();
1156 // If the stream is muted, don't play the sound
1157 if (mAudioManager.isStreamMute(mMasterStreamType)) return;
1159 mLockSoundStreamId = mLockSounds.play(whichSound,
1160 mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
1164 private void updateActivityLockScreenState() {
1166 ActivityManagerNative.getDefault().setLockScreenShown(mShowing && !mOccluded);
1167 } catch (RemoteException e) {
1172 * Handle message sent by {@link #showLocked}.
1175 private void handleShow(Bundle options) {
1176 synchronized (KeyguardViewMediator.this) {
1177 if (!mSystemReady) {
1178 if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready.");
1181 if (DEBUG) Log.d(TAG, "handleShow");
1184 mStatusBarKeyguardViewManager.show(options);
1187 mKeyguardDonePending = false;
1188 updateActivityLockScreenState();
1189 adjustStatusBarLocked();
1192 // Do this at the end to not slow down display of the keyguard.
1195 mShowKeyguardWakeLock.release();
1197 mKeyguardDisplayManager.show();
1201 * Handle message sent by {@link #hideLocked()}
1204 private void handleHide() {
1205 synchronized (KeyguardViewMediator.this) {
1206 if (DEBUG) Log.d(TAG, "handleHide");
1211 // Don't actually hide the Keyguard at the moment, wait for window manager until
1212 // it tells us it's safe to do so with startKeyguardExitAnimation.
1213 mWM.keyguardGoingAway();
1216 // Don't try to rely on WindowManager - if Keyguard wasn't showing, window
1217 // manager won't start the exit animation.
1218 handleStartKeyguardExitAnimation(0, 0);
1220 } catch (RemoteException e) {
1221 Log.e(TAG, "Error while calling WindowManager", e);
1226 private void handleStartKeyguardExitAnimation(long startTime, long fadeoutDuration) {
1227 synchronized (KeyguardViewMediator.this) {
1234 // only play "unlock" noises if not on a call (since the incall UI
1235 // disables the keyguard)
1236 if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
1240 mStatusBarKeyguardViewManager.hide(startTime, fadeoutDuration);
1242 mKeyguardDonePending = false;
1243 updateActivityLockScreenState();
1244 adjustStatusBarLocked();
1248 private void adjustStatusBarLocked() {
1249 if (mStatusBarManager == null) {
1250 mStatusBarManager = (StatusBarManager)
1251 mContext.getSystemService(Context.STATUS_BAR_SERVICE);
1253 if (mStatusBarManager == null) {
1254 Log.w(TAG, "Could not get status bar manager");
1256 // Disable aspects of the system/status/navigation bars that must not be re-enabled by
1257 // windows that appear on top, ever
1258 int flags = StatusBarManager.DISABLE_NONE;
1260 // Permanently disable components not available when keyguard is enabled
1261 // (like recents). Temporary enable/disable (e.g. the "back" button) are
1262 // done in KeyguardHostView.
1263 flags |= StatusBarManager.DISABLE_RECENT;
1264 if (!isAssistantAvailable()) {
1265 flags |= StatusBarManager.DISABLE_SEARCH;
1268 if (isShowingAndNotOccluded()) {
1269 flags |= StatusBarManager.DISABLE_HOME;
1273 Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mOccluded=" + mOccluded
1274 + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
1277 if (!(mContext instanceof Activity)) {
1278 mStatusBarManager.disable(flags);
1284 * Handle message sent by {@link #resetStateLocked}
1287 private void handleReset() {
1288 synchronized (KeyguardViewMediator.this) {
1289 if (DEBUG) Log.d(TAG, "handleReset");
1290 mStatusBarKeyguardViewManager.reset();
1295 * Handle message sent by {@link #verifyUnlock}
1296 * @see #VERIFY_UNLOCK
1298 private void handleVerifyUnlock() {
1299 synchronized (KeyguardViewMediator.this) {
1300 if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
1301 mStatusBarKeyguardViewManager.verifyUnlock();
1303 updateActivityLockScreenState();
1308 * Handle message sent by {@link #notifyScreenOffLocked()}
1309 * @see #NOTIFY_SCREEN_OFF
1311 private void handleNotifyScreenOff() {
1312 synchronized (KeyguardViewMediator.this) {
1313 if (DEBUG) Log.d(TAG, "handleNotifyScreenOff");
1314 mStatusBarKeyguardViewManager.onScreenTurnedOff();
1319 * Handle message sent by {@link #notifyScreenOnLocked}
1320 * @see #NOTIFY_SCREEN_ON
1322 private void handleNotifyScreenOn(IKeyguardShowCallback callback) {
1323 synchronized (KeyguardViewMediator.this) {
1324 if (DEBUG) Log.d(TAG, "handleNotifyScreenOn");
1325 mStatusBarKeyguardViewManager.onScreenTurnedOn(callback);
1329 public boolean isDismissable() {
1330 return mKeyguardDonePending || !isSecure();
1333 private boolean isAssistantAvailable() {
1334 return mSearchManager != null
1335 && mSearchManager.getAssistIntent(mContext, false, UserHandle.USER_CURRENT) != null;
1338 public void onBootCompleted() {
1339 mUpdateMonitor.dispatchBootCompleted();
1342 public StatusBarKeyguardViewManager registerStatusBar(PhoneStatusBar phoneStatusBar,
1343 ViewGroup container, StatusBarWindowManager statusBarWindowManager,
1344 ScrimController scrimController) {
1345 mStatusBarKeyguardViewManager.registerStatusBar(phoneStatusBar, container,
1346 statusBarWindowManager, scrimController);
1347 return mStatusBarKeyguardViewManager;
1350 public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
1351 Message msg = mHandler.obtainMessage(START_KEYGUARD_EXIT_ANIM,
1352 new StartKeyguardExitAnimParams(startTime, fadeoutDuration));
1353 mHandler.sendMessage(msg);
1356 public ViewMediatorCallback getViewMediatorCallback() {
1357 return mViewMediatorCallback;
1360 private static class StartKeyguardExitAnimParams {
1363 long fadeoutDuration;
1365 private StartKeyguardExitAnimParams(long startTime, long fadeoutDuration) {
1366 this.startTime = startTime;
1367 this.fadeoutDuration = fadeoutDuration;