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.ActivityManager;
21 import android.app.ActivityManagerNative;
22 import android.app.AlarmManager;
23 import android.app.PendingIntent;
24 import android.app.SearchManager;
25 import android.app.StatusBarManager;
26 import android.app.trust.TrustManager;
27 import android.content.BroadcastReceiver;
28 import android.content.ContentResolver;
29 import android.content.Context;
30 import android.content.Intent;
31 import android.content.IntentFilter;
32 import android.content.pm.UserInfo;
33 import android.media.AudioManager;
34 import android.media.SoundPool;
35 import android.os.Bundle;
36 import android.os.DeadObjectException;
37 import android.os.Handler;
38 import android.os.Looper;
39 import android.os.Message;
40 import android.os.PowerManager;
41 import android.os.RemoteException;
42 import android.os.SystemClock;
43 import android.os.SystemProperties;
44 import android.os.UserHandle;
45 import android.os.UserManager;
46 import android.provider.Settings;
47 import android.telephony.SubscriptionManager;
48 import android.telephony.TelephonyManager;
49 import android.util.EventLog;
50 import android.util.Log;
51 import android.util.Slog;
52 import android.view.IWindowManager;
53 import android.view.ViewGroup;
54 import android.view.WindowManagerGlobal;
55 import android.view.WindowManagerPolicy;
56 import android.view.animation.Animation;
57 import android.view.animation.AnimationUtils;
59 import com.android.internal.policy.IKeyguardDrawnCallback;
60 import com.android.internal.policy.IKeyguardExitCallback;
61 import com.android.internal.policy.IKeyguardStateCallback;
62 import com.android.internal.telephony.IccCardConstants;
63 import com.android.internal.widget.LockPatternUtils;
64 import com.android.keyguard.KeyguardConstants;
65 import com.android.keyguard.KeyguardDisplayManager;
66 import com.android.keyguard.KeyguardSecurityView;
67 import com.android.keyguard.KeyguardUpdateMonitor;
68 import com.android.keyguard.KeyguardUpdateMonitorCallback;
69 import com.android.keyguard.ViewMediatorCallback;
70 import com.android.systemui.SystemUI;
71 import com.android.systemui.statusbar.phone.FingerprintUnlockController;
72 import com.android.systemui.statusbar.phone.PhoneStatusBar;
73 import com.android.systemui.statusbar.phone.ScrimController;
74 import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
75 import com.android.systemui.statusbar.phone.StatusBarWindowManager;
77 import java.io.FileDescriptor;
78 import java.io.PrintWriter;
79 import java.util.ArrayList;
80 import java.util.List;
82 import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
85 * Mediates requests related to the keyguard. This includes queries about the
86 * state of the keyguard, power management events that effect whether the keyguard
87 * should be shown or reset, callbacks to the phone window manager to notify
88 * it of when the keyguard is showing, and events from the keyguard view itself
89 * stating that the keyguard was succesfully unlocked.
91 * Note that the keyguard view is shown when the screen is off (as appropriate)
92 * so that once the screen comes on, it will be ready immediately.
94 * Example queries about the keyguard:
95 * - is {movement, key} one that should wake the keygaurd?
96 * - is the keyguard showing?
97 * - are input events restricted due to the state of the keyguard?
99 * Callbacks to the phone window manager:
100 * - the keyguard is showing
102 * Example external events that translate to keyguard view changes:
103 * - screen turned off -> reset the keyguard, and show it so it will be ready
104 * next time the screen turns on
105 * - keyboard is slid open -> if the keyguard is not secure, hide it
107 * Events from the keyguard view:
108 * - user succesfully unlocked keyguard -> hide keyguard view, and no longer
109 * restrict input events.
111 * Note: in addition to normal power managment events that effect the state of
112 * whether the keyguard should be showing, external apps and services may request
113 * that the keyguard be disabled via {@link #setKeyguardEnabled(boolean)}. When
114 * false, this will override all other conditions for turning on the keyguard.
116 * Threading and synchronization:
117 * This class is created by the initialization routine of the {@link android.view.WindowManagerPolicy},
118 * and runs on its thread. The keyguard UI is created from that thread in the
119 * constructor of this class. The apis may be called from other threads, including the
120 * {@link com.android.server.input.InputManagerService}'s and {@link android.view.WindowManager}'s.
121 * Therefore, methods on this class are synchronized, and any action that is pointed
122 * directly to the keyguard UI is posted to a {@link android.os.Handler} to ensure it is taken on the UI
123 * thread of the keyguard.
125 public class KeyguardViewMediator extends SystemUI {
126 private static final int KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000;
127 private static final long KEYGUARD_DONE_PENDING_TIMEOUT_MS = 3000;
129 private static final boolean DEBUG = KeyguardConstants.DEBUG;
130 private static final boolean DEBUG_SIM_STATES = KeyguardConstants.DEBUG_SIM_STATES;
131 private final static boolean DBG_WAKE = false;
133 private final static String TAG = "KeyguardViewMediator";
135 private static final String DELAYED_KEYGUARD_ACTION =
136 "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_KEYGUARD";
138 // used for handler messages
139 private static final int SHOW = 2;
140 private static final int HIDE = 3;
141 private static final int RESET = 4;
142 private static final int VERIFY_UNLOCK = 5;
143 private static final int NOTIFY_FINISHED_GOING_TO_SLEEP = 6;
144 private static final int NOTIFY_SCREEN_TURNING_ON = 7;
145 private static final int KEYGUARD_DONE = 9;
146 private static final int KEYGUARD_DONE_DRAWING = 10;
147 private static final int KEYGUARD_DONE_AUTHENTICATING = 11;
148 private static final int SET_OCCLUDED = 12;
149 private static final int KEYGUARD_TIMEOUT = 13;
150 private static final int DISMISS = 17;
151 private static final int START_KEYGUARD_EXIT_ANIM = 18;
152 private static final int ON_ACTIVITY_DRAWN = 19;
153 private static final int KEYGUARD_DONE_PENDING_TIMEOUT = 20;
154 private static final int NOTIFY_STARTED_WAKING_UP = 21;
155 private static final int NOTIFY_SCREEN_TURNED_ON = 22;
156 private static final int NOTIFY_SCREEN_TURNED_OFF = 23;
157 private static final int NOTIFY_STARTED_GOING_TO_SLEEP = 24;
160 * The default amount of time we stay awake (used for all key input)
162 public static final int AWAKE_INTERVAL_DEFAULT_MS = 10000;
165 * How long to wait after the screen turns off due to timeout before
166 * turning on the keyguard (i.e, the user has this much time to turn
167 * the screen back on without having to face the keyguard).
169 private static final int KEYGUARD_LOCK_AFTER_DELAY_DEFAULT = 5000;
172 * How long we'll wait for the {@link ViewMediatorCallback#keyguardDoneDrawing()}
173 * callback before unblocking a call to {@link #setKeyguardEnabled(boolean)}
174 * that is reenabling the keyguard.
176 private static final int KEYGUARD_DONE_DRAWING_TIMEOUT_MS = 2000;
179 * Secure setting whether analytics are collected on the keyguard.
181 private static final String KEYGUARD_ANALYTICS_SETTING = "keyguard_analytics";
183 /** The stream type that the lock sounds are tied to. */
184 private int mUiSoundsStreamType;
186 private AlarmManager mAlarmManager;
187 private AudioManager mAudioManager;
188 private StatusBarManager mStatusBarManager;
189 private boolean mSwitchingUser;
191 private boolean mSystemReady;
192 private boolean mBootCompleted;
193 private boolean mBootSendUserPresent;
195 /** High level access to the power manager for WakeLocks */
196 private PowerManager mPM;
198 /** High level access to the window manager for dismissing keyguard animation */
199 private IWindowManager mWM;
202 /** TrustManager for letting it know when we change visibility */
203 private TrustManager mTrustManager;
205 /** SearchManager for determining whether or not search assistant is available */
206 private SearchManager mSearchManager;
209 * Used to keep the device awake while to ensure the keyguard finishes opening before
212 private PowerManager.WakeLock mShowKeyguardWakeLock;
214 private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
216 // these are protected by synchronized (this)
219 * External apps (like the phone app) can tell us to disable the keygaurd.
221 private boolean mExternallyEnabled = true;
224 * Remember if an external call to {@link #setKeyguardEnabled} with value
225 * false caused us to hide the keyguard, so that we need to reshow it once
226 * the keygaurd is reenabled with another call with value true.
228 private boolean mNeedToReshowWhenReenabled = false;
230 // cached value of whether we are showing (need to know this to quickly
231 // answer whether the input should be restricted)
232 private boolean mShowing;
234 /** Cached value of #isInputRestricted */
235 private boolean mInputRestricted;
237 // true if the keyguard is hidden by another window
238 private boolean mOccluded = false;
241 * Helps remember whether the screen has turned on since the last time
242 * it turned off due to timeout. see {@link #onScreenTurnedOff(int)}
244 private int mDelayedShowingSequence;
247 * If the user has disabled the keyguard, then requests to exit, this is
248 * how we'll ultimately let them know whether it was successful. We use this
249 * var being non-null as an indicator that there is an in progress request.
251 private IKeyguardExitCallback mExitSecureCallback;
253 // the properties of the keyguard
255 private KeyguardUpdateMonitor mUpdateMonitor;
257 private boolean mDeviceInteractive;
258 private boolean mGoingToSleep;
260 // last known state of the cellular connection
261 private String mPhoneState = TelephonyManager.EXTRA_STATE_IDLE;
264 * Whether a hide is pending an we are just waiting for #startKeyguardExitAnimation to be
267 private boolean mHiding;
270 * we send this intent when the keyguard is dismissed.
272 private static final Intent USER_PRESENT_INTENT = new Intent(Intent.ACTION_USER_PRESENT)
273 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
274 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
277 * {@link #setKeyguardEnabled} waits on this condition when it reenables
280 private boolean mWaitingUntilKeyguardVisible = false;
281 private LockPatternUtils mLockPatternUtils;
282 private boolean mKeyguardDonePending = false;
283 private boolean mHideAnimationRun = false;
285 private SoundPool mLockSounds;
286 private int mLockSoundId;
287 private int mUnlockSoundId;
288 private int mTrustedSoundId;
289 private int mLockSoundStreamId;
292 * The animation used for hiding keyguard. This is used to fetch the animation timings if
293 * WindowManager is not providing us with them.
295 private Animation mHideAnimation;
298 * The volume applied to the lock/unlock sounds.
300 private float mLockSoundVolume;
303 * For managing external displays
305 private KeyguardDisplayManager mKeyguardDisplayManager;
307 private final ArrayList<IKeyguardStateCallback> mKeyguardStateCallbacks = new ArrayList<>();
310 * When starting going to sleep, we figured out that we need to reset Keyguard state and this
311 * should be committed when finished going to sleep.
313 private boolean mPendingReset;
316 * When starting going to sleep, we figured out that we need to lock Keyguard and this should be
317 * committed when finished going to sleep.
319 private boolean mPendingLock;
321 private boolean mWakeAndUnlocking;
322 private IKeyguardDrawnCallback mDrawnCallback;
324 KeyguardUpdateMonitorCallback mUpdateCallback = new KeyguardUpdateMonitorCallback() {
327 public void onUserSwitching(int userId) {
328 // Note that the mLockPatternUtils user has already been updated from setCurrentUser.
329 // We need to force a reset of the views, since lockNow (called by
330 // ActivityManagerService) will not reconstruct the keyguard if it is already showing.
331 synchronized (KeyguardViewMediator.this) {
332 mSwitchingUser = true;
333 resetKeyguardDonePendingLocked();
335 adjustStatusBarLocked();
340 public void onUserSwitchComplete(int userId) {
341 mSwitchingUser = false;
342 if (userId != UserHandle.USER_OWNER) {
343 UserInfo info = UserManager.get(mContext).getUserInfo(userId);
344 if (info != null && info.isGuest()) {
345 // If we just switched to a guest, try to dismiss keyguard.
352 public void onUserInfoChanged(int userId) {
356 public void onPhoneStateChanged(int phoneState) {
357 synchronized (KeyguardViewMediator.this) {
358 if (TelephonyManager.CALL_STATE_IDLE == phoneState // call ending
359 && !mDeviceInteractive // screen off
360 && mExternallyEnabled) { // not disabled by any app
362 // note: this is a way to gracefully reenable the keyguard when the call
363 // ends and the screen is off without always reenabling the keyguard
364 // each time the screen turns off while in call (and having an occasional ugly
365 // flicker while turning back on the screen and disabling the keyguard again).
366 if (DEBUG) Log.d(TAG, "screen is off and call ended, let's make sure the "
367 + "keyguard is showing");
368 doKeyguardLocked(null);
374 public void onClockVisibilityChanged() {
375 adjustStatusBarLocked();
379 public void onDeviceProvisioned() {
380 sendUserPresentBroadcast();
384 public void onSimStateChanged(int subId, int slotId, IccCardConstants.State simState) {
386 if (DEBUG_SIM_STATES) {
387 Log.d(TAG, "onSimStateChanged(subId=" + subId + ", slotId=" + slotId
388 + ",state=" + simState + ")");
391 int size = mKeyguardStateCallbacks.size();
392 boolean simPinSecure = mUpdateMonitor.isSimPinSecure();
393 for (int i = size - 1; i >= 0; i--) {
395 mKeyguardStateCallbacks.get(i).onSimSecureStateChanged(simPinSecure);
396 } catch (RemoteException e) {
397 Slog.w(TAG, "Failed to call onSimSecureStateChanged", e);
398 if (e instanceof DeadObjectException) {
399 mKeyguardStateCallbacks.remove(i);
407 // only force lock screen in case of missing sim if user hasn't
408 // gone through setup wizard
409 synchronized (this) {
410 if (shouldWaitForProvisioning()) {
412 if (DEBUG_SIM_STATES) Log.d(TAG, "ICC_ABSENT isn't showing,"
413 + " we need to show the keyguard since the "
414 + "device isn't provisioned yet.");
415 doKeyguardLocked(null);
424 synchronized (this) {
426 if (DEBUG_SIM_STATES) Log.d(TAG,
427 "INTENT_VALUE_ICC_LOCKED and keygaurd isn't "
428 + "showing; need to show keyguard so user can enter sim pin");
429 doKeyguardLocked(null);
436 synchronized (this) {
438 if (DEBUG_SIM_STATES) Log.d(TAG, "PERM_DISABLED and "
439 + "keygaurd isn't showing.");
440 doKeyguardLocked(null);
442 if (DEBUG_SIM_STATES) Log.d(TAG, "PERM_DISABLED, resetStateLocked to"
443 + "show permanently disabled message in lockscreen.");
449 synchronized (this) {
456 if (DEBUG_SIM_STATES) Log.v(TAG, "Ignoring state: " + simState);
462 ViewMediatorCallback mViewMediatorCallback = new ViewMediatorCallback() {
464 public void userActivity() {
465 KeyguardViewMediator.this.userActivity();
468 public void keyguardDone(boolean strongAuth) {
469 if (!mKeyguardDonePending) {
470 KeyguardViewMediator.this.keyguardDone(true /* authenticated */);
473 mUpdateMonitor.reportSuccessfulStrongAuthUnlockAttempt();
477 public void keyguardDoneDrawing() {
478 mHandler.sendEmptyMessage(KEYGUARD_DONE_DRAWING);
482 public void setNeedsInput(boolean needsInput) {
483 mStatusBarKeyguardViewManager.setNeedsInput(needsInput);
487 public void keyguardDonePending(boolean strongAuth) {
488 mKeyguardDonePending = true;
489 mHideAnimationRun = true;
490 mStatusBarKeyguardViewManager.startPreHideAnimation(null /* finishRunnable */);
491 mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_PENDING_TIMEOUT,
492 KEYGUARD_DONE_PENDING_TIMEOUT_MS);
494 mUpdateMonitor.reportSuccessfulStrongAuthUnlockAttempt();
499 public void keyguardGone() {
500 mKeyguardDisplayManager.hide();
504 public void readyForKeyguardDone() {
505 if (mKeyguardDonePending) {
506 // Somebody has called keyguardDonePending before, which means that we are
508 KeyguardViewMediator.this.keyguardDone(true /* authenticated */);
513 public void resetKeyguard() {
518 public void playTrustedSound() {
519 KeyguardViewMediator.this.playTrustedSound();
523 public boolean isInputRestricted() {
524 return KeyguardViewMediator.this.isInputRestricted();
528 public boolean isScreenOn() {
529 return mDeviceInteractive;
533 public int getBouncerPromptReason() {
534 int currentUser = ActivityManager.getCurrentUser();
535 if ((mUpdateMonitor.getUserTrustIsManaged(currentUser)
536 || mUpdateMonitor.isUnlockWithFingerprintPossible(currentUser))
537 && !mUpdateMonitor.getStrongAuthTracker().hasUserAuthenticatedSinceBoot()) {
538 return KeyguardSecurityView.PROMPT_REASON_RESTART;
539 } else if (mUpdateMonitor.isUnlockWithFingerprintPossible(currentUser)
540 && mUpdateMonitor.hasFingerprintUnlockTimedOut(currentUser)) {
541 return KeyguardSecurityView.PROMPT_REASON_TIMEOUT;
543 return KeyguardSecurityView.PROMPT_REASON_NONE;
547 public void userActivity() {
548 mPM.userActivity(SystemClock.uptimeMillis(), false);
551 private void setupLocked() {
552 mPM = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
553 mWM = WindowManagerGlobal.getWindowManagerService();
554 mTrustManager = (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
556 mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "show keyguard");
557 mShowKeyguardWakeLock.setReferenceCounted(false);
559 mContext.registerReceiver(mBroadcastReceiver, new IntentFilter(DELAYED_KEYGUARD_ACTION));
561 mKeyguardDisplayManager = new KeyguardDisplayManager(mContext);
563 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
565 mUpdateMonitor = KeyguardUpdateMonitor.getInstance(mContext);
567 mLockPatternUtils = new LockPatternUtils(mContext);
568 KeyguardUpdateMonitor.setCurrentUser(ActivityManager.getCurrentUser());
570 // Assume keyguard is showing (unless it's disabled) until we know for sure...
571 setShowingLocked(!shouldWaitForProvisioning() && !mLockPatternUtils.isLockScreenDisabled(
572 KeyguardUpdateMonitor.getCurrentUser()));
573 updateInputRestrictedLocked();
574 mTrustManager.reportKeyguardShowingChanged();
576 mStatusBarKeyguardViewManager = new StatusBarKeyguardViewManager(mContext,
577 mViewMediatorCallback, mLockPatternUtils);
578 final ContentResolver cr = mContext.getContentResolver();
580 mDeviceInteractive = mPM.isInteractive();
582 mLockSounds = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
583 String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND);
584 if (soundPath != null) {
585 mLockSoundId = mLockSounds.load(soundPath, 1);
587 if (soundPath == null || mLockSoundId == 0) {
588 Log.w(TAG, "failed to load lock sound from " + soundPath);
590 soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND);
591 if (soundPath != null) {
592 mUnlockSoundId = mLockSounds.load(soundPath, 1);
594 if (soundPath == null || mUnlockSoundId == 0) {
595 Log.w(TAG, "failed to load unlock sound from " + soundPath);
597 soundPath = Settings.Global.getString(cr, Settings.Global.TRUSTED_SOUND);
598 if (soundPath != null) {
599 mTrustedSoundId = mLockSounds.load(soundPath, 1);
601 if (soundPath == null || mTrustedSoundId == 0) {
602 Log.w(TAG, "failed to load trusted sound from " + soundPath);
605 int lockSoundDefaultAttenuation = mContext.getResources().getInteger(
606 com.android.internal.R.integer.config_lockSoundVolumeDb);
607 mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20);
609 mHideAnimation = AnimationUtils.loadAnimation(mContext,
610 com.android.internal.R.anim.lock_screen_behind_enter);
614 public void start() {
615 synchronized (this) {
618 putComponent(KeyguardViewMediator.class, this);
622 * Let us know that the system is ready after startup.
624 public void onSystemReady() {
625 mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
626 synchronized (this) {
627 if (DEBUG) Log.d(TAG, "onSystemReady");
629 doKeyguardLocked(null);
630 mUpdateMonitor.registerCallback(mUpdateCallback);
632 // Most services aren't available until the system reaches the ready state, so we
633 // send it here when the device first boots.
634 maybeSendUserPresentBroadcast();
638 * Called to let us know the screen was turned off.
639 * @param why either {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_USER} or
640 * {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT}.
642 public void onStartedGoingToSleep(int why) {
643 if (DEBUG) Log.d(TAG, "onStartedGoingToSleep(" + why + ")");
644 synchronized (this) {
645 mDeviceInteractive = false;
646 mGoingToSleep = true;
648 // Lock immediately based on setting if secure (user has a pin/pattern/password).
649 // This also "locks" the device when not secure to provide easy access to the
650 // camera while preventing unwanted input.
651 int currentUser = KeyguardUpdateMonitor.getCurrentUser();
652 final boolean lockImmediately =
653 mLockPatternUtils.getPowerButtonInstantlyLocks(currentUser)
654 || !mLockPatternUtils.isSecure(currentUser);
656 if (mExitSecureCallback != null) {
657 if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
659 mExitSecureCallback.onKeyguardExitResult(false);
660 } catch (RemoteException e) {
661 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
663 mExitSecureCallback = null;
664 if (!mExternallyEnabled) {
667 } else if (mShowing) {
668 mPendingReset = true;
669 } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT
670 || (why == WindowManagerPolicy.OFF_BECAUSE_OF_USER && !lockImmediately)) {
671 doKeyguardLaterLocked();
672 } else if (!mLockPatternUtils.isLockScreenDisabled(currentUser)) {
680 KeyguardUpdateMonitor.getInstance(mContext).dispatchStartedGoingToSleep(why);
681 notifyStartedGoingToSleep();
684 public void onFinishedGoingToSleep(int why) {
685 if (DEBUG) Log.d(TAG, "onFinishedGoingToSleep(" + why + ")");
686 synchronized (this) {
687 mDeviceInteractive = false;
688 mGoingToSleep = false;
690 resetKeyguardDonePendingLocked();
691 mHideAnimationRun = false;
693 notifyFinishedGoingToSleep();
697 mPendingReset = false;
700 doKeyguardLocked(null);
701 mPendingLock = false;
704 KeyguardUpdateMonitor.getInstance(mContext).dispatchFinishedGoingToSleep(why);
707 private void doKeyguardLaterLocked() {
708 // if the screen turned off because of timeout or the user hit the power button
709 // and we don't need to lock immediately, set an alarm
710 // to enable it a little bit later (i.e, give the user a chance
711 // to turn the screen back on within a certain window without
712 // having to unlock the screen)
713 final ContentResolver cr = mContext.getContentResolver();
715 // From DisplaySettings
716 long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
717 KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);
719 // From SecuritySettings
720 final long lockAfterTimeout = Settings.Secure.getInt(cr,
721 Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
722 KEYGUARD_LOCK_AFTER_DELAY_DEFAULT);
724 // From DevicePolicyAdmin
725 final long policyTimeout = mLockPatternUtils.getDevicePolicyManager()
726 .getMaximumTimeToLock(null, KeyguardUpdateMonitor.getCurrentUser());
729 if (policyTimeout > 0) {
730 // policy in effect. Make sure we don't go beyond policy limit.
731 displayTimeout = Math.max(displayTimeout, 0); // ignore negative values
732 timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);
734 timeout = lockAfterTimeout;
739 doKeyguardLocked(null);
741 // Lock in the future
742 long when = SystemClock.elapsedRealtime() + timeout;
743 Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
744 intent.putExtra("seq", mDelayedShowingSequence);
745 PendingIntent sender = PendingIntent.getBroadcast(mContext,
746 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
747 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender);
748 if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = "
749 + mDelayedShowingSequence);
753 private void cancelDoKeyguardLaterLocked() {
754 mDelayedShowingSequence++;
758 * Let's us know when the device is waking up.
760 public void onStartedWakingUp() {
762 // TODO: Rename all screen off/on references to interactive/sleeping
763 synchronized (this) {
764 mDeviceInteractive = true;
765 cancelDoKeyguardLaterLocked();
766 if (DEBUG) Log.d(TAG, "onStartedWakingUp, seq = " + mDelayedShowingSequence);
767 notifyStartedWakingUp();
769 KeyguardUpdateMonitor.getInstance(mContext).dispatchStartedWakingUp();
770 maybeSendUserPresentBroadcast();
773 public void onScreenTurningOn(IKeyguardDrawnCallback callback) {
774 notifyScreenOn(callback);
777 public void onScreenTurnedOn() {
778 notifyScreenTurnedOn();
779 mUpdateMonitor.dispatchScreenTurnedOn();
782 public void onScreenTurnedOff() {
783 notifyScreenTurnedOff();
784 mUpdateMonitor.dispatchScreenTurnedOff();
787 private void maybeSendUserPresentBroadcast() {
788 if (mSystemReady && mLockPatternUtils.isLockScreenDisabled(
789 KeyguardUpdateMonitor.getCurrentUser())) {
790 // Lock screen is disabled because the user has set the preference to "None".
791 // In this case, send out ACTION_USER_PRESENT here instead of in
792 // handleKeyguardDone()
793 sendUserPresentBroadcast();
798 * A dream started. We should lock after the usual screen-off lock timeout but only
799 * if there is a secure lock pattern.
801 public void onDreamingStarted() {
802 synchronized (this) {
803 if (mDeviceInteractive
804 && mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())) {
805 doKeyguardLaterLocked();
813 public void onDreamingStopped() {
814 synchronized (this) {
815 if (mDeviceInteractive) {
816 cancelDoKeyguardLaterLocked();
822 * Same semantics as {@link android.view.WindowManagerPolicy#enableKeyguard}; provide
823 * a way for external stuff to override normal keyguard behavior. For instance
824 * the phone app disables the keyguard when it receives incoming calls.
826 public void setKeyguardEnabled(boolean enabled) {
827 synchronized (this) {
828 if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
830 mExternallyEnabled = enabled;
832 if (!enabled && mShowing) {
833 if (mExitSecureCallback != null) {
834 if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
835 // we're in the process of handling a request to verify the user
836 // can get past the keyguard. ignore extraneous requests to disable / reenable
840 // hiding keyguard that is showing, remember to reshow later
841 if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
842 + "disabling status bar expansion");
843 mNeedToReshowWhenReenabled = true;
844 updateInputRestrictedLocked();
846 } else if (enabled && mNeedToReshowWhenReenabled) {
847 // reenabled after previously hidden, reshow
848 if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
849 + "status bar expansion");
850 mNeedToReshowWhenReenabled = false;
851 updateInputRestrictedLocked();
853 if (mExitSecureCallback != null) {
854 if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
856 mExitSecureCallback.onKeyguardExitResult(false);
857 } catch (RemoteException e) {
858 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
860 mExitSecureCallback = null;
865 // block until we know the keygaurd is done drawing (and post a message
866 // to unblock us after a timeout so we don't risk blocking too long
867 // and causing an ANR).
868 mWaitingUntilKeyguardVisible = true;
869 mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
870 if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
871 while (mWaitingUntilKeyguardVisible) {
874 } catch (InterruptedException e) {
875 Thread.currentThread().interrupt();
878 if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
885 * @see android.app.KeyguardManager#exitKeyguardSecurely
887 public void verifyUnlock(IKeyguardExitCallback callback) {
888 synchronized (this) {
889 if (DEBUG) Log.d(TAG, "verifyUnlock");
890 if (shouldWaitForProvisioning()) {
891 // don't allow this api when the device isn't provisioned
892 if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
894 callback.onKeyguardExitResult(false);
895 } catch (RemoteException e) {
896 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
898 } else if (mExternallyEnabled) {
899 // this only applies when the user has externally disabled the
900 // keyguard. this is unexpected and means the user is not
901 // using the api properly.
902 Log.w(TAG, "verifyUnlock called when not externally disabled");
904 callback.onKeyguardExitResult(false);
905 } catch (RemoteException e) {
906 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
908 } else if (mExitSecureCallback != null) {
909 // already in progress with someone else
911 callback.onKeyguardExitResult(false);
912 } catch (RemoteException e) {
913 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
916 mExitSecureCallback = callback;
917 verifyUnlockLocked();
923 * Is the keyguard currently showing and not being force hidden?
925 public boolean isShowingAndNotOccluded() {
926 return mShowing && !mOccluded;
930 * Notify us when the keyguard is occluded by another window
932 public void setOccluded(boolean isOccluded) {
933 if (DEBUG) Log.d(TAG, "setOccluded " + isOccluded);
934 mHandler.removeMessages(SET_OCCLUDED);
935 Message msg = mHandler.obtainMessage(SET_OCCLUDED, (isOccluded ? 1 : 0), 0);
936 mHandler.sendMessage(msg);
940 * Handles SET_OCCLUDED message sent by setOccluded()
942 private void handleSetOccluded(boolean isOccluded) {
943 synchronized (KeyguardViewMediator.this) {
944 if (mHiding && isOccluded) {
945 // We're in the process of going away but WindowManager wants to show a
946 // SHOW_WHEN_LOCKED activity instead.
947 startKeyguardExitAnimation(0, 0);
950 if (mOccluded != isOccluded) {
951 mOccluded = isOccluded;
952 mStatusBarKeyguardViewManager.setOccluded(isOccluded);
953 updateActivityLockScreenState();
954 adjustStatusBarLocked();
960 * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout.
961 * This must be safe to call from any thread and with any window manager locks held.
963 public void doKeyguardTimeout(Bundle options) {
964 mHandler.removeMessages(KEYGUARD_TIMEOUT);
965 Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
966 mHandler.sendMessage(msg);
970 * Given the state of the keyguard, is the input restricted?
971 * Input is restricted when the keyguard is showing, or when the keyguard
972 * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.
974 public boolean isInputRestricted() {
975 return mShowing || mNeedToReshowWhenReenabled;
978 private void updateInputRestricted() {
979 synchronized (this) {
980 updateInputRestrictedLocked();
983 private void updateInputRestrictedLocked() {
984 boolean inputRestricted = isInputRestricted();
985 if (mInputRestricted != inputRestricted) {
986 mInputRestricted = inputRestricted;
987 int size = mKeyguardStateCallbacks.size();
988 for (int i = size - 1; i >= 0; i--) {
990 mKeyguardStateCallbacks.get(i).onInputRestrictedStateChanged(inputRestricted);
991 } catch (RemoteException e) {
992 Slog.w(TAG, "Failed to call onDeviceProvisioned", e);
993 if (e instanceof DeadObjectException) {
994 mKeyguardStateCallbacks.remove(i);
1002 * Enable the keyguard if the settings are appropriate.
1004 private void doKeyguardLocked(Bundle options) {
1005 // if another app is disabling us, don't show
1006 if (!mExternallyEnabled) {
1007 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");
1009 // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes
1010 // for an occasional ugly flicker in this situation:
1011 // 1) receive a call with the screen on (no keyguard) or make a call
1012 // 2) screen times out
1013 // 3) user hits key to turn screen back on
1014 // instead, we reenable the keyguard when we know the screen is off and the call
1015 // ends (see the broadcast receiver below)
1016 // TODO: clean this up when we have better support at the window manager level
1017 // for apps that wish to be on top of the keyguard
1021 // if the keyguard is already showing, don't bother
1022 if (mStatusBarKeyguardViewManager.isShowing()) {
1023 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
1028 // if the setup wizard hasn't run yet, don't show
1029 final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim", false);
1030 final boolean absent = SubscriptionManager.isValidSubscriptionId(
1031 mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.ABSENT));
1032 final boolean disabled = SubscriptionManager.isValidSubscriptionId(
1033 mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.PERM_DISABLED));
1034 final boolean lockedOrMissing = mUpdateMonitor.isSimPinSecure()
1035 || ((absent || disabled) && requireSim);
1037 if (!lockedOrMissing && shouldWaitForProvisioning()) {
1038 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
1039 + " and the sim is not locked or missing");
1043 if (mLockPatternUtils.isLockScreenDisabled(KeyguardUpdateMonitor.getCurrentUser())
1044 && !lockedOrMissing) {
1045 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
1049 if (mLockPatternUtils.checkVoldPassword(KeyguardUpdateMonitor.getCurrentUser())) {
1050 if (DEBUG) Log.d(TAG, "Not showing lock screen since just decrypted");
1051 // Without this, settings is not enabled until the lock screen first appears
1052 setShowingLocked(false);
1054 mUpdateMonitor.reportSuccessfulStrongAuthUnlockAttempt();
1058 if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
1059 showLocked(options);
1062 private boolean shouldWaitForProvisioning() {
1063 return !mUpdateMonitor.isDeviceProvisioned() && !isSecure();
1067 * Dismiss the keyguard through the security layers.
1069 public void handleDismiss() {
1070 if (mShowing && !mOccluded) {
1071 mStatusBarKeyguardViewManager.dismiss();
1075 public void dismiss() {
1076 mHandler.sendEmptyMessage(DISMISS);
1080 * Send message to keyguard telling it to reset its state.
1083 private void resetStateLocked() {
1084 if (DEBUG) Log.e(TAG, "resetStateLocked");
1085 Message msg = mHandler.obtainMessage(RESET);
1086 mHandler.sendMessage(msg);
1090 * Send message to keyguard telling it to verify unlock
1091 * @see #handleVerifyUnlock()
1093 private void verifyUnlockLocked() {
1094 if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
1095 mHandler.sendEmptyMessage(VERIFY_UNLOCK);
1098 private void notifyStartedGoingToSleep() {
1099 if (DEBUG) Log.d(TAG, "notifyStartedGoingToSleep");
1100 mHandler.sendEmptyMessage(NOTIFY_STARTED_GOING_TO_SLEEP);
1103 private void notifyFinishedGoingToSleep() {
1104 if (DEBUG) Log.d(TAG, "notifyFinishedGoingToSleep");
1105 mHandler.sendEmptyMessage(NOTIFY_FINISHED_GOING_TO_SLEEP);
1108 private void notifyStartedWakingUp() {
1109 if (DEBUG) Log.d(TAG, "notifyStartedWakingUp");
1110 mHandler.sendEmptyMessage(NOTIFY_STARTED_WAKING_UP);
1113 private void notifyScreenOn(IKeyguardDrawnCallback callback) {
1114 if (DEBUG) Log.d(TAG, "notifyScreenOn");
1115 Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNING_ON, callback);
1116 mHandler.sendMessage(msg);
1119 private void notifyScreenTurnedOn() {
1120 if (DEBUG) Log.d(TAG, "notifyScreenTurnedOn");
1121 Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNED_ON);
1122 mHandler.sendMessage(msg);
1125 private void notifyScreenTurnedOff() {
1126 if (DEBUG) Log.d(TAG, "notifyScreenTurnedOff");
1127 Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNED_OFF);
1128 mHandler.sendMessage(msg);
1132 * Send message to keyguard telling it to show itself
1135 private void showLocked(Bundle options) {
1136 if (DEBUG) Log.d(TAG, "showLocked");
1137 // ensure we stay awake until we are finished displaying the keyguard
1138 mShowKeyguardWakeLock.acquire();
1139 Message msg = mHandler.obtainMessage(SHOW, options);
1140 mHandler.sendMessage(msg);
1144 * Send message to keyguard telling it to hide itself
1145 * @see #handleHide()
1147 private void hideLocked() {
1148 if (DEBUG) Log.d(TAG, "hideLocked");
1149 Message msg = mHandler.obtainMessage(HIDE);
1150 mHandler.sendMessage(msg);
1153 public boolean isSecure() {
1154 return mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())
1155 || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
1159 * Update the newUserId. Call while holding WindowManagerService lock.
1160 * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.
1162 * @param newUserId The id of the incoming user.
1164 public void setCurrentUser(int newUserId) {
1165 KeyguardUpdateMonitor.setCurrentUser(newUserId);
1168 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1170 public void onReceive(Context context, Intent intent) {
1171 if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {
1172 final int sequence = intent.getIntExtra("seq", 0);
1173 if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
1174 + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
1175 synchronized (KeyguardViewMediator.this) {
1176 if (mDelayedShowingSequence == sequence) {
1177 doKeyguardLocked(null);
1184 public void keyguardDone(boolean authenticated) {
1185 if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated +")");
1186 EventLog.writeEvent(70000, 2);
1187 Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0);
1188 mHandler.sendMessage(msg);
1192 * This handler will be associated with the policy thread, which will also
1193 * be the UI thread of the keyguard. Since the apis of the policy, and therefore
1194 * this class, can be called by other threads, any action that directly
1195 * interacts with the keyguard ui should be posted to this handler, rather
1196 * than called directly.
1198 private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
1200 public void handleMessage(Message msg) {
1203 handleShow((Bundle) msg.obj);
1212 handleVerifyUnlock();
1214 case NOTIFY_STARTED_GOING_TO_SLEEP:
1215 handleNotifyStartedGoingToSleep();
1217 case NOTIFY_FINISHED_GOING_TO_SLEEP:
1218 handleNotifyFinishedGoingToSleep();
1220 case NOTIFY_SCREEN_TURNING_ON:
1221 handleNotifyScreenTurningOn((IKeyguardDrawnCallback) msg.obj);
1223 case NOTIFY_SCREEN_TURNED_ON:
1224 handleNotifyScreenTurnedOn();
1226 case NOTIFY_SCREEN_TURNED_OFF:
1227 handleNotifyScreenTurnedOff();
1229 case NOTIFY_STARTED_WAKING_UP:
1230 handleNotifyStartedWakingUp();
1233 handleKeyguardDone(msg.arg1 != 0);
1235 case KEYGUARD_DONE_DRAWING:
1236 handleKeyguardDoneDrawing();
1239 handleSetOccluded(msg.arg1 != 0);
1241 case KEYGUARD_TIMEOUT:
1242 synchronized (KeyguardViewMediator.this) {
1243 doKeyguardLocked((Bundle) msg.obj);
1249 case START_KEYGUARD_EXIT_ANIM:
1250 StartKeyguardExitAnimParams params = (StartKeyguardExitAnimParams) msg.obj;
1251 handleStartKeyguardExitAnimation(params.startTime, params.fadeoutDuration);
1253 case KEYGUARD_DONE_PENDING_TIMEOUT:
1254 Log.w(TAG, "Timeout while waiting for activity drawn!");
1256 case ON_ACTIVITY_DRAWN:
1257 handleOnActivityDrawn();
1264 * @see #keyguardDone
1265 * @see #KEYGUARD_DONE
1267 private void handleKeyguardDone(boolean authenticated) {
1268 if (DEBUG) Log.d(TAG, "handleKeyguardDone");
1269 synchronized (this) {
1270 resetKeyguardDonePendingLocked();
1273 if (authenticated) {
1274 mUpdateMonitor.clearFailedUnlockAttempts();
1276 mUpdateMonitor.clearFingerprintRecognized();
1278 if (mGoingToSleep) {
1279 Log.i(TAG, "Device is going to sleep, aborting keyguardDone");
1282 if (mExitSecureCallback != null) {
1284 mExitSecureCallback.onKeyguardExitResult(authenticated);
1285 } catch (RemoteException e) {
1286 Slog.w(TAG, "Failed to call onKeyguardExitResult(" + authenticated + ")", e);
1289 mExitSecureCallback = null;
1291 if (authenticated) {
1292 // after succesfully exiting securely, no need to reshow
1293 // the keyguard when they've released the lock
1294 mExternallyEnabled = true;
1295 mNeedToReshowWhenReenabled = false;
1296 updateInputRestricted();
1303 private void sendUserPresentBroadcast() {
1304 synchronized (this) {
1305 if (mBootCompleted) {
1306 final UserHandle currentUser = new UserHandle(KeyguardUpdateMonitor.getCurrentUser());
1307 final UserManager um = (UserManager) mContext.getSystemService(
1308 Context.USER_SERVICE);
1309 List <UserInfo> userHandles = um.getProfiles(currentUser.getIdentifier());
1310 for (UserInfo ui : userHandles) {
1311 mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, ui.getUserHandle());
1314 mBootSendUserPresent = true;
1320 * @see #keyguardDone
1321 * @see #KEYGUARD_DONE_DRAWING
1323 private void handleKeyguardDoneDrawing() {
1324 synchronized(this) {
1325 if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing");
1326 if (mWaitingUntilKeyguardVisible) {
1327 if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
1328 mWaitingUntilKeyguardVisible = false;
1331 // there will usually be two of these sent, one as a timeout, and one
1332 // as a result of the callback, so remove any remaining messages from
1334 mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
1339 private void playSounds(boolean locked) {
1340 playSound(locked ? mLockSoundId : mUnlockSoundId);
1343 private void playSound(int soundId) {
1344 if (soundId == 0) return;
1345 final ContentResolver cr = mContext.getContentResolver();
1346 if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
1348 mLockSounds.stop(mLockSoundStreamId);
1349 // Init mAudioManager
1350 if (mAudioManager == null) {
1351 mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
1352 if (mAudioManager == null) return;
1353 mUiSoundsStreamType = mAudioManager.getUiSoundsStreamType();
1355 // If the stream is muted, don't play the sound
1356 if (mAudioManager.isStreamMute(mUiSoundsStreamType)) return;
1358 mLockSoundStreamId = mLockSounds.play(soundId,
1359 mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
1363 private void playTrustedSound() {
1364 playSound(mTrustedSoundId);
1367 private void updateActivityLockScreenState() {
1369 ActivityManagerNative.getDefault().setLockScreenShown(mShowing && !mOccluded);
1370 } catch (RemoteException e) {
1375 * Handle message sent by {@link #showLocked}.
1378 private void handleShow(Bundle options) {
1379 synchronized (KeyguardViewMediator.this) {
1380 if (!mSystemReady) {
1381 if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready.");
1384 if (DEBUG) Log.d(TAG, "handleShow");
1387 setShowingLocked(true);
1388 mStatusBarKeyguardViewManager.show(options);
1390 mWakeAndUnlocking = false;
1391 resetKeyguardDonePendingLocked();
1392 mHideAnimationRun = false;
1393 updateActivityLockScreenState();
1394 adjustStatusBarLocked();
1397 mShowKeyguardWakeLock.release();
1399 mKeyguardDisplayManager.show();
1402 private final Runnable mKeyguardGoingAwayRunnable = new Runnable() {
1406 mStatusBarKeyguardViewManager.keyguardGoingAway();
1408 // Don't actually hide the Keyguard at the moment, wait for window
1409 // manager until it tells us it's safe to do so with
1410 // startKeyguardExitAnimation.
1411 ActivityManagerNative.getDefault().keyguardGoingAway(
1412 mStatusBarKeyguardViewManager.shouldDisableWindowAnimationsForUnlock()
1413 || mWakeAndUnlocking,
1414 mStatusBarKeyguardViewManager.isGoingToNotificationShade());
1415 } catch (RemoteException e) {
1416 Log.e(TAG, "Error while calling WindowManager", e);
1422 * Handle message sent by {@link #hideLocked()}
1425 private void handleHide() {
1426 synchronized (KeyguardViewMediator.this) {
1427 if (DEBUG) Log.d(TAG, "handleHide");
1430 if (mShowing && !mOccluded) {
1431 if (!mHideAnimationRun) {
1432 mStatusBarKeyguardViewManager.startPreHideAnimation(mKeyguardGoingAwayRunnable);
1434 mKeyguardGoingAwayRunnable.run();
1438 // Don't try to rely on WindowManager - if Keyguard wasn't showing, window
1439 // manager won't start the exit animation.
1440 handleStartKeyguardExitAnimation(
1441 SystemClock.uptimeMillis() + mHideAnimation.getStartOffset(),
1442 mHideAnimation.getDuration());
1447 private void handleOnActivityDrawn() {
1448 if (DEBUG) Log.d(TAG, "handleOnActivityDrawn: mKeyguardDonePending=" + mKeyguardDonePending);
1449 if (mKeyguardDonePending) {
1450 mStatusBarKeyguardViewManager.onActivityDrawn();
1454 private void handleStartKeyguardExitAnimation(long startTime, long fadeoutDuration) {
1455 synchronized (KeyguardViewMediator.this) {
1462 if (mWakeAndUnlocking && mDrawnCallback != null) {
1464 // Hack level over 9000: To speed up wake-and-unlock sequence, force it to report
1465 // the next draw from here so we don't have to wait for window manager to signal
1466 // this to our ViewRootImpl.
1467 mStatusBarKeyguardViewManager.getViewRootImpl().setReportNextDraw();
1468 notifyDrawn(mDrawnCallback);
1471 // only play "unlock" noises if not on a call (since the incall UI
1472 // disables the keyguard)
1473 if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
1477 setShowingLocked(false);
1478 mStatusBarKeyguardViewManager.hide(startTime, fadeoutDuration);
1479 resetKeyguardDonePendingLocked();
1480 mHideAnimationRun = false;
1481 updateActivityLockScreenState();
1482 adjustStatusBarLocked();
1483 sendUserPresentBroadcast();
1487 private void adjustStatusBarLocked() {
1488 if (mStatusBarManager == null) {
1489 mStatusBarManager = (StatusBarManager)
1490 mContext.getSystemService(Context.STATUS_BAR_SERVICE);
1492 if (mStatusBarManager == null) {
1493 Log.w(TAG, "Could not get status bar manager");
1495 // Disable aspects of the system/status/navigation bars that must not be re-enabled by
1496 // windows that appear on top, ever
1497 int flags = StatusBarManager.DISABLE_NONE;
1499 // Permanently disable components not available when keyguard is enabled
1500 // (like recents). Temporary enable/disable (e.g. the "back" button) are
1501 // done in KeyguardHostView.
1502 flags |= StatusBarManager.DISABLE_RECENT;
1503 flags |= StatusBarManager.DISABLE_SEARCH;
1505 if (isShowingAndNotOccluded()) {
1506 flags |= StatusBarManager.DISABLE_HOME;
1510 Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mOccluded=" + mOccluded
1511 + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
1514 if (!(mContext instanceof Activity)) {
1515 mStatusBarManager.disable(flags);
1521 * Handle message sent by {@link #resetStateLocked}
1524 private void handleReset() {
1525 synchronized (KeyguardViewMediator.this) {
1526 if (DEBUG) Log.d(TAG, "handleReset");
1527 mStatusBarKeyguardViewManager.reset();
1532 * Handle message sent by {@link #verifyUnlock}
1533 * @see #VERIFY_UNLOCK
1535 private void handleVerifyUnlock() {
1536 synchronized (KeyguardViewMediator.this) {
1537 if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
1538 setShowingLocked(true);
1539 mStatusBarKeyguardViewManager.verifyUnlock();
1540 updateActivityLockScreenState();
1544 private void handleNotifyStartedGoingToSleep() {
1545 synchronized (KeyguardViewMediator.this) {
1546 if (DEBUG) Log.d(TAG, "handleNotifyStartedGoingToSleep");
1547 mStatusBarKeyguardViewManager.onStartedGoingToSleep();
1552 * Handle message sent by {@link #notifyFinishedGoingToSleep()}
1553 * @see #NOTIFY_FINISHED_GOING_TO_SLEEP
1555 private void handleNotifyFinishedGoingToSleep() {
1556 synchronized (KeyguardViewMediator.this) {
1557 if (DEBUG) Log.d(TAG, "handleNotifyFinishedGoingToSleep");
1558 mStatusBarKeyguardViewManager.onFinishedGoingToSleep();
1562 private void handleNotifyStartedWakingUp() {
1563 synchronized (KeyguardViewMediator.this) {
1564 if (DEBUG) Log.d(TAG, "handleNotifyWakingUp");
1565 mStatusBarKeyguardViewManager.onStartedWakingUp();
1569 private void handleNotifyScreenTurningOn(IKeyguardDrawnCallback callback) {
1570 synchronized (KeyguardViewMediator.this) {
1571 if (DEBUG) Log.d(TAG, "handleNotifyScreenTurningOn");
1572 mStatusBarKeyguardViewManager.onScreenTurningOn();
1573 if (callback != null) {
1574 if (mWakeAndUnlocking) {
1575 mDrawnCallback = callback;
1577 notifyDrawn(callback);
1583 private void handleNotifyScreenTurnedOn() {
1584 synchronized (this) {
1585 if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOn");
1586 mStatusBarKeyguardViewManager.onScreenTurnedOn();
1590 private void handleNotifyScreenTurnedOff() {
1591 synchronized (this) {
1592 if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOff");
1593 mStatusBarKeyguardViewManager.onScreenTurnedOff();
1594 mWakeAndUnlocking = false;
1598 private void notifyDrawn(final IKeyguardDrawnCallback callback) {
1601 } catch (RemoteException e) {
1602 Slog.w(TAG, "Exception calling onDrawn():", e);
1606 private void resetKeyguardDonePendingLocked() {
1607 mKeyguardDonePending = false;
1608 mHandler.removeMessages(KEYGUARD_DONE_PENDING_TIMEOUT);
1611 public void onBootCompleted() {
1612 mUpdateMonitor.dispatchBootCompleted();
1613 synchronized (this) {
1614 mBootCompleted = true;
1615 if (mBootSendUserPresent) {
1616 sendUserPresentBroadcast();
1621 public void onWakeAndUnlocking() {
1622 mWakeAndUnlocking = true;
1623 keyguardDone(true /* authenticated */);
1626 public StatusBarKeyguardViewManager registerStatusBar(PhoneStatusBar phoneStatusBar,
1627 ViewGroup container, StatusBarWindowManager statusBarWindowManager,
1628 ScrimController scrimController,
1629 FingerprintUnlockController fingerprintUnlockController) {
1630 mStatusBarKeyguardViewManager.registerStatusBar(phoneStatusBar, container,
1631 statusBarWindowManager, scrimController, fingerprintUnlockController);
1632 return mStatusBarKeyguardViewManager;
1635 public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
1636 Message msg = mHandler.obtainMessage(START_KEYGUARD_EXIT_ANIM,
1637 new StartKeyguardExitAnimParams(startTime, fadeoutDuration));
1638 mHandler.sendMessage(msg);
1641 public void onActivityDrawn() {
1642 mHandler.sendEmptyMessage(ON_ACTIVITY_DRAWN);
1644 public ViewMediatorCallback getViewMediatorCallback() {
1645 return mViewMediatorCallback;
1649 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1650 pw.print(" mSystemReady: "); pw.println(mSystemReady);
1651 pw.print(" mBootCompleted: "); pw.println(mBootCompleted);
1652 pw.print(" mBootSendUserPresent: "); pw.println(mBootSendUserPresent);
1653 pw.print(" mExternallyEnabled: "); pw.println(mExternallyEnabled);
1654 pw.print(" mNeedToReshowWhenReenabled: "); pw.println(mNeedToReshowWhenReenabled);
1655 pw.print(" mShowing: "); pw.println(mShowing);
1656 pw.print(" mInputRestricted: "); pw.println(mInputRestricted);
1657 pw.print(" mOccluded: "); pw.println(mOccluded);
1658 pw.print(" mDelayedShowingSequence: "); pw.println(mDelayedShowingSequence);
1659 pw.print(" mExitSecureCallback: "); pw.println(mExitSecureCallback);
1660 pw.print(" mDeviceInteractive: "); pw.println(mDeviceInteractive);
1661 pw.print(" mGoingToSleep: "); pw.println(mGoingToSleep);
1662 pw.print(" mHiding: "); pw.println(mHiding);
1663 pw.print(" mWaitingUntilKeyguardVisible: "); pw.println(mWaitingUntilKeyguardVisible);
1664 pw.print(" mKeyguardDonePending: "); pw.println(mKeyguardDonePending);
1665 pw.print(" mHideAnimationRun: "); pw.println(mHideAnimationRun);
1666 pw.print(" mPendingReset: "); pw.println(mPendingReset);
1667 pw.print(" mPendingLock: "); pw.println(mPendingLock);
1668 pw.print(" mWakeAndUnlocking: "); pw.println(mWakeAndUnlocking);
1669 pw.print(" mDrawnCallback: "); pw.println(mDrawnCallback);
1672 private static class StartKeyguardExitAnimParams {
1675 long fadeoutDuration;
1677 private StartKeyguardExitAnimParams(long startTime, long fadeoutDuration) {
1678 this.startTime = startTime;
1679 this.fadeoutDuration = fadeoutDuration;
1683 private void setShowingLocked(boolean showing) {
1684 if (showing != mShowing) {
1686 int size = mKeyguardStateCallbacks.size();
1687 for (int i = size - 1; i >= 0; i--) {
1689 mKeyguardStateCallbacks.get(i).onShowingStateChanged(showing);
1690 } catch (RemoteException e) {
1691 Slog.w(TAG, "Failed to call onShowingStateChanged", e);
1692 if (e instanceof DeadObjectException) {
1693 mKeyguardStateCallbacks.remove(i);
1697 updateInputRestrictedLocked();
1698 mTrustManager.reportKeyguardShowingChanged();
1702 public void addStateMonitorCallback(IKeyguardStateCallback callback) {
1703 synchronized (this) {
1704 mKeyguardStateCallbacks.add(callback);
1706 callback.onSimSecureStateChanged(mUpdateMonitor.isSimPinSecure());
1707 callback.onShowingStateChanged(mShowing);
1708 callback.onInputRestrictedStateChanged(mInputRestricted);
1709 } catch (RemoteException e) {
1710 Slog.w(TAG, "Failed to call onShowingStateChanged or onSimSecureStateChanged or onInputRestrictedStateChanged", e);