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) {
397 ViewMediatorCallback mViewMediatorCallback = new ViewMediatorCallback() {
399 public void userActivity() {
400 KeyguardViewMediator.this.userActivity();
403 public void userActivity(long holdMs) {
404 KeyguardViewMediator.this.userActivity(holdMs);
407 public void keyguardDone(boolean authenticated) {
408 KeyguardViewMediator.this.keyguardDone(authenticated, true);
411 public void keyguardDoneDrawing() {
412 mHandler.sendEmptyMessage(KEYGUARD_DONE_DRAWING);
416 public void setNeedsInput(boolean needsInput) {
417 mStatusBarKeyguardViewManager.setNeedsInput(needsInput);
421 public void onUserActivityTimeoutChanged() {
422 mStatusBarKeyguardViewManager.updateUserActivityTimeout();
426 public void keyguardDonePending() {
427 mKeyguardDonePending = true;
431 public void keyguardGone() {
432 mKeyguardDisplayManager.hide();
436 private void userActivity() {
437 userActivity(AWAKE_INTERVAL_DEFAULT_MS);
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);
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);
453 mContext.registerReceiver(mBroadcastReceiver, new IntentFilter(DELAYED_KEYGUARD_ACTION));
455 mKeyguardDisplayManager = new KeyguardDisplayManager(mContext);
457 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
459 mUpdateMonitor = KeyguardUpdateMonitor.getInstance(mContext);
461 mLockPatternUtils = new LockPatternUtils(mContext);
462 mLockPatternUtils.setCurrentUser(UserHandle.USER_OWNER);
464 // Assume keyguard is showing (unless it's disabled) until we know for sure...
465 mShowing = (mUpdateMonitor.isDeviceProvisioned() || mLockPatternUtils.isSecure())
466 && !mLockPatternUtils.isLockScreenDisabled();
468 mStatusBarKeyguardViewManager = new StatusBarKeyguardViewManager(mContext,
469 mViewMediatorCallback, mLockPatternUtils);
470 final ContentResolver cr = mContext.getContentResolver();
472 mScreenOn = mPM.isScreenOn();
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);
479 if (soundPath == null || mLockSoundId == 0) {
480 Log.w(TAG, "failed to load lock sound from " + soundPath);
482 soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND);
483 if (soundPath != null) {
484 mUnlockSoundId = mLockSounds.load(soundPath, 1);
486 if (soundPath == null || mUnlockSoundId == 0) {
487 Log.w(TAG, "failed to load unlock sound from " + soundPath);
489 int lockSoundDefaultAttenuation = mContext.getResources().getInteger(
490 com.android.internal.R.integer.config_lockSoundVolumeDb);
491 mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20);
495 public void start() {
497 putComponent(KeyguardViewMediator.class, this);
501 * Let us know that the system is ready after startup.
503 public void onSystemReady() {
504 mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
505 synchronized (this) {
506 if (DEBUG) Log.d(TAG, "onSystemReady");
508 mUpdateMonitor.registerCallback(mUpdateCallback);
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.
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
519 if (mLockPatternUtils.usingBiometricWeak()
520 && mLockPatternUtils.isBiometricWeakInstalled()) {
521 if (DEBUG) Log.d(TAG, "suppressing biometric unlock during boot");
522 mUpdateMonitor.setAlternateUnlockEnabled(false);
524 mUpdateMonitor.setAlternateUnlockEnabled(true);
527 doKeyguardLocked(null);
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();
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}.
539 public void onScreenTurnedOff(int why) {
540 synchronized (this) {
542 if (DEBUG) Log.d(TAG, "onScreenTurnedOff(" + why + ")");
544 mKeyguardDonePending = false;
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();
552 if (mExitSecureCallback != null) {
553 if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
555 mExitSecureCallback.onKeyguardExitResult(false);
556 } catch (RemoteException e) {
557 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
559 mExitSecureCallback = null;
560 if (!mExternallyEnabled) {
563 } else if (mShowing) {
564 notifyScreenOffLocked();
566 } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT
567 || (why == WindowManagerPolicy.OFF_BECAUSE_OF_USER && !lockImmediately)) {
568 doKeyguardLaterLocked();
570 doKeyguardLocked(null);
573 KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurndOff(why);
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();
584 // From DisplaySettings
585 long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
586 KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);
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);
593 // From DevicePolicyAdmin
594 final long policyTimeout = mLockPatternUtils.getDevicePolicyManager()
595 .getMaximumTimeToLock(null, mLockPatternUtils.getCurrentUser());
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);
603 timeout = lockAfterTimeout;
608 mSuppressNextLockSound = true;
609 doKeyguardLocked(null);
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);
623 private void cancelDoKeyguardLaterLocked() {
624 mDelayedShowingSequence++;
628 * Let's us know the screen was turned on.
630 public void onScreenTurnedOn(IKeyguardShowCallback callback) {
631 synchronized (this) {
633 cancelDoKeyguardLaterLocked();
634 if (DEBUG) Log.d(TAG, "onScreenTurnedOn, seq = " + mDelayedShowingSequence);
635 if (callback != null) {
636 notifyScreenOnLocked(callback);
639 KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurnedOn();
640 maybeSendUserPresentBroadcast();
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();
654 * A dream started. We should lock after the usual screen-off lock timeout but only
655 * if there is a secure lock pattern.
657 public void onDreamingStarted() {
658 synchronized (this) {
659 if (mScreenOn && mLockPatternUtils.isSecure()) {
660 doKeyguardLaterLocked();
668 public void onDreamingStopped() {
669 synchronized (this) {
671 cancelDoKeyguardLaterLocked();
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.
681 public void setKeyguardEnabled(boolean enabled) {
682 synchronized (this) {
683 if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
685 mExternallyEnabled = enabled;
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
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;
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;
706 if (mExitSecureCallback != null) {
707 if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
709 mExitSecureCallback.onKeyguardExitResult(false);
710 } catch (RemoteException e) {
711 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
713 mExitSecureCallback = null;
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) {
727 } catch (InterruptedException e) {
728 Thread.currentThread().interrupt();
731 if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
738 * @see android.app.KeyguardManager#exitKeyguardSecurely
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");
747 callback.onKeyguardExitResult(false);
748 } catch (RemoteException e) {
749 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
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");
757 callback.onKeyguardExitResult(false);
758 } catch (RemoteException e) {
759 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
761 } else if (mExitSecureCallback != null) {
762 // already in progress with someone else
764 callback.onKeyguardExitResult(false);
765 } catch (RemoteException e) {
766 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
769 mExitSecureCallback = callback;
770 verifyUnlockLocked();
776 * Is the keyguard currently showing?
778 public boolean isShowing() {
782 public boolean isOccluded() {
787 * Is the keyguard currently showing and not being force hidden?
789 public boolean isShowingAndNotOccluded() {
790 return mShowing && !mOccluded;
794 * Notify us when the keyguard is occluded by another window
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);
804 * Handles SET_OCCLUDED message sent by setOccluded()
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();
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.
821 public void doKeyguardTimeout(Bundle options) {
822 mHandler.removeMessages(KEYGUARD_TIMEOUT);
823 Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
824 mHandler.sendMessage(msg);
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.
832 public boolean isInputRestricted() {
833 return mShowing || mNeedToReshowWhenReenabled || !mUpdateMonitor.isDeviceProvisioned();
837 * Enable the keyguard if the settings are appropriate.
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");
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
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");
862 // if the setup wizard hasn't run yet, don't show
863 final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim",
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)
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");
878 if (!mUserManager.isUserSwitcherEnabled()
879 && mLockPatternUtils.isLockScreenDisabled() && !lockedOrMissing) {
880 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
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
892 if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
897 * Dismiss the keyguard through the security layers.
899 public void handleDismiss() {
900 if (mShowing && !mOccluded) {
901 mStatusBarKeyguardViewManager.dismiss();
905 public void dismiss() {
906 mHandler.sendEmptyMessage(DISMISS);
910 * Send message to keyguard telling it to reset its state.
913 private void resetStateLocked() {
914 if (DEBUG) Log.e(TAG, "resetStateLocked");
915 Message msg = mHandler.obtainMessage(RESET);
916 mHandler.sendMessage(msg);
920 * Send message to keyguard telling it to verify unlock
921 * @see #handleVerifyUnlock()
923 private void verifyUnlockLocked() {
924 if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
925 mHandler.sendEmptyMessage(VERIFY_UNLOCK);
930 * Send a message to keyguard telling it the screen just turned on.
931 * @see #onScreenTurnedOff(int)
932 * @see #handleNotifyScreenOff
934 private void notifyScreenOffLocked() {
935 if (DEBUG) Log.d(TAG, "notifyScreenOffLocked");
936 mHandler.sendEmptyMessage(NOTIFY_SCREEN_OFF);
940 * Send a message to keyguard telling it the screen just turned on.
941 * @see #onScreenTurnedOn
942 * @see #handleNotifyScreenOn
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);
951 * Send message to keyguard telling it to show itself
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);
963 * Send message to keyguard telling it to hide itself
966 private void hideLocked() {
967 if (DEBUG) Log.d(TAG, "hideLocked");
968 Message msg = mHandler.obtainMessage(HIDE);
969 mHandler.sendMessage(msg);
972 public boolean isSecure() {
973 return mLockPatternUtils.isSecure()
974 || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
978 * Update the newUserId. Call while holding WindowManagerService lock.
979 * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.
981 * @param newUserId The id of the incoming user.
983 public void setCurrentUser(int newUserId) {
984 mLockPatternUtils.setCurrentUser(newUserId);
987 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
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);
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;
1011 Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0, wakeup ? 1 : 0);
1012 mHandler.sendMessage(msg);
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.
1022 private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
1024 public void handleMessage(Message msg) {
1027 handleShow((Bundle) msg.obj);
1036 handleVerifyUnlock();
1038 case NOTIFY_SCREEN_OFF:
1039 handleNotifyScreenOff();
1041 case NOTIFY_SCREEN_ON:
1042 handleNotifyScreenOn((IKeyguardShowCallback) msg.obj);
1045 handleKeyguardDone(msg.arg1 != 0, msg.arg2 != 0);
1047 case KEYGUARD_DONE_DRAWING:
1048 handleKeyguardDoneDrawing();
1050 case KEYGUARD_DONE_AUTHENTICATING:
1051 keyguardDone(true, true);
1054 handleSetOccluded(msg.arg1 != 0);
1056 case KEYGUARD_TIMEOUT:
1057 synchronized (KeyguardViewMediator.this) {
1058 doKeyguardLocked((Bundle) msg.obj);
1064 case START_KEYGUARD_EXIT_ANIM:
1065 StartKeyguardExitAnimParams params = (StartKeyguardExitAnimParams) msg.obj;
1066 handleStartKeyguardExitAnimation(params.startTime, params.fadeoutDuration);
1073 * @see #keyguardDone
1074 * @see #KEYGUARD_DONE
1076 private void handleKeyguardDone(boolean authenticated, boolean wakeup) {
1077 if (DEBUG) Log.d(TAG, "handleKeyguardDone");
1079 if (authenticated) {
1080 mUpdateMonitor.clearFailedUnlockAttempts();
1083 if (mExitSecureCallback != null) {
1085 mExitSecureCallback.onKeyguardExitResult(authenticated);
1086 } catch (RemoteException e) {
1087 Slog.w(TAG, "Failed to call onKeyguardExitResult(" + authenticated + ")", e);
1090 mExitSecureCallback = null;
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;
1101 sendUserPresentBroadcast();
1104 private void sendUserPresentBroadcast() {
1105 final UserHandle currentUser = new UserHandle(mLockPatternUtils.getCurrentUser());
1106 mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, currentUser);
1110 * @see #keyguardDone
1111 * @see #KEYGUARD_DONE_DRAWING
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;
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
1124 mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
1129 private void playSounds(boolean locked) {
1130 // User feedback for keyguard.
1132 if (mSuppressNextLockSound) {
1133 mSuppressNextLockSound = false;
1137 final ContentResolver cr = mContext.getContentResolver();
1138 if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
1139 final int whichSound = locked
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();
1149 // If the stream is muted, don't play the sound
1150 if (mAudioManager.isStreamMute(mMasterStreamType)) return;
1152 mLockSoundStreamId = mLockSounds.play(whichSound,
1153 mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
1157 private void updateActivityLockScreenState() {
1159 ActivityManagerNative.getDefault().setLockScreenShown(mShowing && !mOccluded);
1160 } catch (RemoteException e) {
1165 * Handle message sent by {@link #showLocked}.
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.");
1174 if (DEBUG) Log.d(TAG, "handleShow");
1177 mStatusBarKeyguardViewManager.show(options);
1180 mKeyguardDonePending = false;
1181 updateActivityLockScreenState();
1182 adjustStatusBarLocked();
1185 // Do this at the end to not slow down display of the keyguard.
1188 mShowKeyguardWakeLock.release();
1190 mKeyguardDisplayManager.show();
1194 * Handle message sent by {@link #hideLocked()}
1197 private void handleHide() {
1198 synchronized (KeyguardViewMediator.this) {
1199 if (DEBUG) Log.d(TAG, "handleHide");
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();
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);
1213 } catch (RemoteException e) {
1214 Log.e(TAG, "Error while calling WindowManager", e);
1219 private void handleStartKeyguardExitAnimation(long startTime, long fadeoutDuration) {
1220 synchronized (KeyguardViewMediator.this) {
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)) {
1233 mStatusBarKeyguardViewManager.hide(startTime, fadeoutDuration);
1235 mKeyguardDonePending = false;
1236 updateActivityLockScreenState();
1237 adjustStatusBarLocked();
1241 private void adjustStatusBarLocked() {
1242 if (mStatusBarManager == null) {
1243 mStatusBarManager = (StatusBarManager)
1244 mContext.getSystemService(Context.STATUS_BAR_SERVICE);
1246 if (mStatusBarManager == null) {
1247 Log.w(TAG, "Could not get status bar manager");
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;
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;
1261 if (isShowingAndNotOccluded()) {
1262 flags |= StatusBarManager.DISABLE_HOME;
1266 Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mOccluded=" + mOccluded
1267 + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
1270 if (!(mContext instanceof Activity)) {
1271 mStatusBarManager.disable(flags);
1277 * Handle message sent by {@link #resetStateLocked}
1280 private void handleReset() {
1281 synchronized (KeyguardViewMediator.this) {
1282 if (DEBUG) Log.d(TAG, "handleReset");
1283 mStatusBarKeyguardViewManager.reset();
1288 * Handle message sent by {@link #verifyUnlock}
1289 * @see #VERIFY_UNLOCK
1291 private void handleVerifyUnlock() {
1292 synchronized (KeyguardViewMediator.this) {
1293 if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
1294 mStatusBarKeyguardViewManager.verifyUnlock();
1296 updateActivityLockScreenState();
1301 * Handle message sent by {@link #notifyScreenOffLocked()}
1302 * @see #NOTIFY_SCREEN_OFF
1304 private void handleNotifyScreenOff() {
1305 synchronized (KeyguardViewMediator.this) {
1306 if (DEBUG) Log.d(TAG, "handleNotifyScreenOff");
1307 mStatusBarKeyguardViewManager.onScreenTurnedOff();
1312 * Handle message sent by {@link #notifyScreenOnLocked}
1313 * @see #NOTIFY_SCREEN_ON
1315 private void handleNotifyScreenOn(IKeyguardShowCallback callback) {
1316 synchronized (KeyguardViewMediator.this) {
1317 if (DEBUG) Log.d(TAG, "handleNotifyScreenOn");
1318 mStatusBarKeyguardViewManager.onScreenTurnedOn(callback);
1322 public boolean isDismissable() {
1323 return mKeyguardDonePending || !isSecure();
1326 private boolean isAssistantAvailable() {
1327 return mSearchManager != null
1328 && mSearchManager.getAssistIntent(mContext, false, UserHandle.USER_CURRENT) != null;
1331 public void onBootCompleted() {
1332 mUpdateMonitor.dispatchBootCompleted();
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;
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);
1349 public ViewMediatorCallback getViewMediatorCallback() {
1350 return mViewMediatorCallback;
1353 private static class StartKeyguardExitAnimParams {
1356 long fadeoutDuration;
1358 private StartKeyguardExitAnimParams(long startTime, long fadeoutDuration) {
1359 this.startTime = startTime;
1360 this.fadeoutDuration = fadeoutDuration;