1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License 15 */ 16 17 package com.android.systemui.keyguard; 18 19 import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT; 20 21 import static com.android.internal.telephony.IccCardConstants.State.ABSENT; 22 import static com.android.internal.telephony.IccCardConstants.State.PIN_REQUIRED; 23 import static com.android.internal.telephony.IccCardConstants.State.PUK_REQUIRED; 24 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.SOME_AUTH_REQUIRED_AFTER_USER_REQUEST; 25 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW; 26 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_LOCKOUT; 27 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_TIMEOUT; 28 29 import android.app.ActivityManager; 30 import android.app.ActivityTaskManager; 31 import android.app.AlarmManager; 32 import android.app.PendingIntent; 33 import android.app.StatusBarManager; 34 import android.app.trust.TrustManager; 35 import android.content.BroadcastReceiver; 36 import android.content.ContentResolver; 37 import android.content.Context; 38 import android.content.Intent; 39 import android.content.IntentFilter; 40 import android.content.pm.UserInfo; 41 import android.hardware.biometrics.BiometricSourceType; 42 import android.media.AudioAttributes; 43 import android.media.AudioManager; 44 import android.media.SoundPool; 45 import android.os.Bundle; 46 import android.os.DeadObjectException; 47 import android.os.Handler; 48 import android.os.Looper; 49 import android.os.Message; 50 import android.os.PowerManager; 51 import android.os.RemoteException; 52 import android.os.SystemClock; 53 import android.os.SystemProperties; 54 import android.os.Trace; 55 import android.os.UserHandle; 56 import android.os.UserManager; 57 import android.provider.Settings; 58 import android.telephony.SubscriptionManager; 59 import android.telephony.TelephonyManager; 60 import android.util.EventLog; 61 import android.util.Log; 62 import android.util.Slog; 63 import android.util.SparseArray; 64 import android.view.ViewGroup; 65 import android.view.WindowManagerPolicyConstants; 66 import android.view.animation.Animation; 67 import android.view.animation.AnimationUtils; 68 69 import com.android.internal.policy.IKeyguardDismissCallback; 70 import com.android.internal.policy.IKeyguardDrawnCallback; 71 import com.android.internal.policy.IKeyguardExitCallback; 72 import com.android.internal.policy.IKeyguardStateCallback; 73 import com.android.internal.telephony.IccCardConstants; 74 import com.android.internal.util.LatencyTracker; 75 import com.android.internal.widget.LockPatternUtils; 76 import com.android.keyguard.KeyguardConstants; 77 import com.android.keyguard.KeyguardDisplayManager; 78 import com.android.keyguard.KeyguardSecurityView; 79 import com.android.keyguard.KeyguardUpdateMonitor; 80 import com.android.keyguard.KeyguardUpdateMonitorCallback; 81 import com.android.keyguard.ViewMediatorCallback; 82 import com.android.systemui.Dependency; 83 import com.android.systemui.SystemUI; 84 import com.android.systemui.SystemUIFactory; 85 import com.android.systemui.UiOffloadThread; 86 import com.android.systemui.classifier.FalsingManagerFactory; 87 import com.android.systemui.statusbar.phone.BiometricUnlockController; 88 import com.android.systemui.statusbar.phone.NotificationPanelView; 89 import com.android.systemui.statusbar.phone.StatusBar; 90 import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager; 91 import com.android.systemui.util.InjectionInflationController; 92 93 import java.io.FileDescriptor; 94 import java.io.PrintWriter; 95 import java.util.ArrayList; 96 97 /** 98 * Mediates requests related to the keyguard. This includes queries about the 99 * state of the keyguard, power management events that effect whether the keyguard 100 * should be shown or reset, callbacks to the phone window manager to notify 101 * it of when the keyguard is showing, and events from the keyguard view itself 102 * stating that the keyguard was succesfully unlocked. 103 * 104 * Note that the keyguard view is shown when the screen is off (as appropriate) 105 * so that once the screen comes on, it will be ready immediately. 106 * 107 * Example queries about the keyguard: 108 * - is {movement, key} one that should wake the keygaurd? 109 * - is the keyguard showing? 110 * - are input events restricted due to the state of the keyguard? 111 * 112 * Callbacks to the phone window manager: 113 * - the keyguard is showing 114 * 115 * Example external events that translate to keyguard view changes: 116 * - screen turned off -> reset the keyguard, and show it so it will be ready 117 * next time the screen turns on 118 * - keyboard is slid open -> if the keyguard is not secure, hide it 119 * 120 * Events from the keyguard view: 121 * - user succesfully unlocked keyguard -> hide keyguard view, and no longer 122 * restrict input events. 123 * 124 * Note: in addition to normal power managment events that effect the state of 125 * whether the keyguard should be showing, external apps and services may request 126 * that the keyguard be disabled via {@link #setKeyguardEnabled(boolean)}. When 127 * false, this will override all other conditions for turning on the keyguard. 128 * 129 * Threading and synchronization: 130 * This class is created by the initialization routine of the {@link WindowManagerPolicyConstants}, 131 * and runs on its thread. The keyguard UI is created from that thread in the 132 * constructor of this class. The apis may be called from other threads, including the 133 * {@link com.android.server.input.InputManagerService}'s and {@link android.view.WindowManager}'s. 134 * Therefore, methods on this class are synchronized, and any action that is pointed 135 * directly to the keyguard UI is posted to a {@link android.os.Handler} to ensure it is taken on the UI 136 * thread of the keyguard. 137 */ 138 public class KeyguardViewMediator extends SystemUI { 139 private static final int KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000; 140 private static final long KEYGUARD_DONE_PENDING_TIMEOUT_MS = 3000; 141 142 private static final boolean DEBUG = KeyguardConstants.DEBUG; 143 private static final boolean DEBUG_SIM_STATES = KeyguardConstants.DEBUG_SIM_STATES; 144 145 private final static String TAG = "KeyguardViewMediator"; 146 147 private static final String DELAYED_KEYGUARD_ACTION = 148 "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_KEYGUARD"; 149 private static final String DELAYED_LOCK_PROFILE_ACTION = 150 "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_LOCK"; 151 152 private static final String SYSTEMUI_PERMISSION = "com.android.systemui.permission.SELF"; 153 154 // used for handler messages 155 private static final int SHOW = 1; 156 private static final int HIDE = 2; 157 private static final int RESET = 3; 158 private static final int VERIFY_UNLOCK = 4; 159 private static final int NOTIFY_FINISHED_GOING_TO_SLEEP = 5; 160 private static final int NOTIFY_SCREEN_TURNING_ON = 6; 161 private static final int KEYGUARD_DONE = 7; 162 private static final int KEYGUARD_DONE_DRAWING = 8; 163 private static final int SET_OCCLUDED = 9; 164 private static final int KEYGUARD_TIMEOUT = 10; 165 private static final int DISMISS = 11; 166 private static final int START_KEYGUARD_EXIT_ANIM = 12; 167 private static final int KEYGUARD_DONE_PENDING_TIMEOUT = 13; 168 private static final int NOTIFY_STARTED_WAKING_UP = 14; 169 private static final int NOTIFY_SCREEN_TURNED_ON = 15; 170 private static final int NOTIFY_SCREEN_TURNED_OFF = 16; 171 private static final int NOTIFY_STARTED_GOING_TO_SLEEP = 17; 172 private static final int SYSTEM_READY = 18; 173 174 /** 175 * The default amount of time we stay awake (used for all key input) 176 */ 177 public static final int AWAKE_INTERVAL_DEFAULT_MS = 10000; 178 179 /** 180 * How long to wait after the screen turns off due to timeout before 181 * turning on the keyguard (i.e, the user has this much time to turn 182 * the screen back on without having to face the keyguard). 183 */ 184 private static final int KEYGUARD_LOCK_AFTER_DELAY_DEFAULT = 5000; 185 186 /** 187 * How long we'll wait for the {@link ViewMediatorCallback#keyguardDoneDrawing()} 188 * callback before unblocking a call to {@link #setKeyguardEnabled(boolean)} 189 * that is reenabling the keyguard. 190 */ 191 private static final int KEYGUARD_DONE_DRAWING_TIMEOUT_MS = 2000; 192 193 /** 194 * Boolean option for doKeyguardLocked/doKeyguardTimeout which, when set to true, forces the 195 * keyguard to show even if it is disabled for the current user. 196 */ 197 public static final String OPTION_FORCE_SHOW = "force_show"; 198 199 /** The stream type that the lock sounds are tied to. */ 200 private int mUiSoundsStreamType; 201 202 private AlarmManager mAlarmManager; 203 private AudioManager mAudioManager; 204 private StatusBarManager mStatusBarManager; 205 private final UiOffloadThread mUiOffloadThread = Dependency.get(UiOffloadThread.class); 206 207 private boolean mSystemReady; 208 private boolean mBootCompleted; 209 private boolean mBootSendUserPresent; 210 private boolean mShuttingDown; 211 212 /** High level access to the power manager for WakeLocks */ 213 private PowerManager mPM; 214 215 /** TrustManager for letting it know when we change visibility */ 216 private TrustManager mTrustManager; 217 218 /** 219 * Used to keep the device awake while to ensure the keyguard finishes opening before 220 * we sleep. 221 */ 222 private PowerManager.WakeLock mShowKeyguardWakeLock; 223 224 private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager; 225 226 // these are protected by synchronized (this) 227 228 /** 229 * External apps (like the phone app) can tell us to disable the keygaurd. 230 */ 231 private boolean mExternallyEnabled = true; 232 233 /** 234 * Remember if an external call to {@link #setKeyguardEnabled} with value 235 * false caused us to hide the keyguard, so that we need to reshow it once 236 * the keygaurd is reenabled with another call with value true. 237 */ 238 private boolean mNeedToReshowWhenReenabled = false; 239 240 // cached value of whether we are showing (need to know this to quickly 241 // answer whether the input should be restricted) 242 private boolean mShowing; 243 244 // AOD is enabled and status bar is in AOD state. 245 private boolean mAodShowing; 246 247 /** Cached value of #isInputRestricted */ 248 private boolean mInputRestricted; 249 250 // true if the keyguard is hidden by another window 251 private boolean mOccluded = false; 252 253 /** 254 * Helps remember whether the screen has turned on since the last time 255 * it turned off due to timeout. see {@link #onScreenTurnedOff(int)} 256 */ 257 private int mDelayedShowingSequence; 258 259 /** 260 * Simiar to {@link #mDelayedProfileShowingSequence}, but it is for profile case. 261 */ 262 private int mDelayedProfileShowingSequence; 263 264 /** 265 * If the user has disabled the keyguard, then requests to exit, this is 266 * how we'll ultimately let them know whether it was successful. We use this 267 * var being non-null as an indicator that there is an in progress request. 268 */ 269 private IKeyguardExitCallback mExitSecureCallback; 270 private final DismissCallbackRegistry mDismissCallbackRegistry = new DismissCallbackRegistry(); 271 272 // the properties of the keyguard 273 274 private KeyguardUpdateMonitor mUpdateMonitor; 275 276 /** 277 * Last SIM state reported by the telephony system. 278 * Index is the slotId - in case of multiple SIM cards. 279 */ 280 private final SparseArray<IccCardConstants.State> mLastSimStates = new SparseArray<>(); 281 282 private boolean mDeviceInteractive; 283 private boolean mGoingToSleep; 284 285 // last known state of the cellular connection 286 private String mPhoneState = TelephonyManager.EXTRA_STATE_IDLE; 287 288 /** 289 * Whether a hide is pending an we are just waiting for #startKeyguardExitAnimation to be 290 * called. 291 * */ 292 private boolean mHiding; 293 294 /** 295 * we send this intent when the keyguard is dismissed. 296 */ 297 private static final Intent USER_PRESENT_INTENT = new Intent(Intent.ACTION_USER_PRESENT) 298 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING 299 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT 300 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); 301 302 /** 303 * {@link #setKeyguardEnabled} waits on this condition when it reenables 304 * the keyguard. 305 */ 306 private boolean mWaitingUntilKeyguardVisible = false; 307 private LockPatternUtils mLockPatternUtils; 308 private boolean mKeyguardDonePending = false; 309 private boolean mHideAnimationRun = false; 310 private boolean mHideAnimationRunning = false; 311 312 private SoundPool mLockSounds; 313 private int mLockSoundId; 314 private int mUnlockSoundId; 315 private int mTrustedSoundId; 316 private int mLockSoundStreamId; 317 318 /** 319 * The animation used for hiding keyguard. This is used to fetch the animation timings if 320 * WindowManager is not providing us with them. 321 */ 322 private Animation mHideAnimation; 323 324 /** 325 * The volume applied to the lock/unlock sounds. 326 */ 327 private float mLockSoundVolume; 328 329 /** 330 * For managing external displays 331 */ 332 private KeyguardDisplayManager mKeyguardDisplayManager; 333 334 private final ArrayList<IKeyguardStateCallback> mKeyguardStateCallbacks = new ArrayList<>(); 335 336 /** 337 * When starting going to sleep, we figured out that we need to reset Keyguard state and this 338 * should be committed when finished going to sleep. 339 */ 340 private boolean mPendingReset; 341 342 /** 343 * When starting going to sleep, we figured out that we need to lock Keyguard and this should be 344 * committed when finished going to sleep. 345 */ 346 private boolean mPendingLock; 347 348 /** 349 * Controller for showing individual "work challenge" lock screen windows inside managed profile 350 * tasks when the current user has been unlocked but the profile is still locked. 351 */ 352 private WorkLockActivityController mWorkLockController; 353 354 /** 355 * @see #setPulsing(boolean) 356 */ 357 private boolean mPulsing; 358 359 private boolean mLockLater; 360 361 private boolean mWakeAndUnlocking; 362 private IKeyguardDrawnCallback mDrawnCallback; 363 private CharSequence mCustomMessage; 364 365 KeyguardUpdateMonitorCallback mUpdateCallback = new KeyguardUpdateMonitorCallback() { 366 367 @Override 368 public void onUserSwitching(int userId) { 369 // Note that the mLockPatternUtils user has already been updated from setCurrentUser. 370 // We need to force a reset of the views, since lockNow (called by 371 // ActivityManagerService) will not reconstruct the keyguard if it is already showing. 372 synchronized (KeyguardViewMediator.this) { 373 resetKeyguardDonePendingLocked(); 374 if (mLockPatternUtils.isLockScreenDisabled(userId)) { 375 // If we switching to a user that has keyguard disabled, dismiss keyguard. 376 dismiss(null /* callback */, null /* message */); 377 } else { 378 resetStateLocked(); 379 } 380 adjustStatusBarLocked(); 381 } 382 } 383 384 @Override 385 public void onUserSwitchComplete(int userId) { 386 if (userId != UserHandle.USER_SYSTEM) { 387 UserInfo info = UserManager.get(mContext).getUserInfo(userId); 388 // Don't try to dismiss if the user has Pin/Patter/Password set 389 if (info == null || mLockPatternUtils.isSecure(userId)) { 390 return; 391 } else if (info.isGuest() || info.isDemo()) { 392 // If we just switched to a guest, try to dismiss keyguard. 393 dismiss(null /* callback */, null /* message */); 394 } 395 } 396 } 397 398 @Override 399 public void onUserInfoChanged(int userId) { 400 } 401 402 @Override 403 public void onClockVisibilityChanged() { 404 adjustStatusBarLocked(); 405 } 406 407 @Override 408 public void onDeviceProvisioned() { 409 sendUserPresentBroadcast(); 410 synchronized (KeyguardViewMediator.this) { 411 // If system user is provisioned, we might want to lock now to avoid showing launcher 412 if (mustNotUnlockCurrentUser()) { 413 doKeyguardLocked(null); 414 } 415 } 416 } 417 418 @Override 419 public void onSimStateChanged(int subId, int slotId, IccCardConstants.State simState) { 420 421 if (DEBUG_SIM_STATES) { 422 Log.d(TAG, "onSimStateChanged(subId=" + subId + ", slotId=" + slotId 423 + ",state=" + simState + ")"); 424 } 425 426 int size = mKeyguardStateCallbacks.size(); 427 boolean simPinSecure = mUpdateMonitor.isSimPinSecure(); 428 for (int i = size - 1; i >= 0; i--) { 429 try { 430 mKeyguardStateCallbacks.get(i).onSimSecureStateChanged(simPinSecure); 431 } catch (RemoteException e) { 432 Slog.w(TAG, "Failed to call onSimSecureStateChanged", e); 433 if (e instanceof DeadObjectException) { 434 mKeyguardStateCallbacks.remove(i); 435 } 436 } 437 } 438 439 boolean simWasLocked; 440 synchronized (KeyguardViewMediator.this) { 441 IccCardConstants.State lastState = mLastSimStates.get(slotId); 442 simWasLocked = (lastState == PIN_REQUIRED || lastState == PUK_REQUIRED); 443 mLastSimStates.append(slotId, simState); 444 } 445 446 switch (simState) { 447 case NOT_READY: 448 case ABSENT: 449 // only force lock screen in case of missing sim if user hasn't 450 // gone through setup wizard 451 synchronized (KeyguardViewMediator.this) { 452 if (shouldWaitForProvisioning()) { 453 if (!mShowing) { 454 if (DEBUG_SIM_STATES) Log.d(TAG, "ICC_ABSENT isn't showing," 455 + " we need to show the keyguard since the " 456 + "device isn't provisioned yet."); 457 doKeyguardLocked(null); 458 } else { 459 resetStateLocked(); 460 } 461 } 462 if (simState == ABSENT) { 463 // MVNO SIMs can become transiently NOT_READY when switching networks, 464 // so we should only lock when they are ABSENT. 465 if (simWasLocked) { 466 if (DEBUG_SIM_STATES) Log.d(TAG, "SIM moved to ABSENT when the " 467 + "previous state was locked. Reset the state."); 468 resetStateLocked(); 469 } 470 } 471 } 472 break; 473 case PIN_REQUIRED: 474 case PUK_REQUIRED: 475 synchronized (KeyguardViewMediator.this) { 476 if (!mShowing) { 477 if (DEBUG_SIM_STATES) Log.d(TAG, 478 "INTENT_VALUE_ICC_LOCKED and keygaurd isn't " 479 + "showing; need to show keyguard so user can enter sim pin"); 480 doKeyguardLocked(null); 481 } else { 482 resetStateLocked(); 483 } 484 } 485 break; 486 case PERM_DISABLED: 487 synchronized (KeyguardViewMediator.this) { 488 if (!mShowing) { 489 if (DEBUG_SIM_STATES) Log.d(TAG, "PERM_DISABLED and " 490 + "keygaurd isn't showing."); 491 doKeyguardLocked(null); 492 } else { 493 if (DEBUG_SIM_STATES) Log.d(TAG, "PERM_DISABLED, resetStateLocked to" 494 + "show permanently disabled message in lockscreen."); 495 resetStateLocked(); 496 } 497 } 498 break; 499 case READY: 500 synchronized (KeyguardViewMediator.this) { 501 if (DEBUG_SIM_STATES) Log.d(TAG, "READY, reset state? " + mShowing); 502 if (mShowing && simWasLocked) { 503 if (DEBUG_SIM_STATES) Log.d(TAG, "SIM moved to READY when the " 504 + "previous state was locked. Reset the state."); 505 resetStateLocked(); 506 } 507 } 508 break; 509 default: 510 if (DEBUG_SIM_STATES) Log.v(TAG, "Unspecific state: " + simState); 511 break; 512 } 513 } 514 515 @Override 516 public void onBiometricAuthFailed(BiometricSourceType biometricSourceType) { 517 final int currentUser = KeyguardUpdateMonitor.getCurrentUser(); 518 if (mLockPatternUtils.isSecure(currentUser)) { 519 mLockPatternUtils.getDevicePolicyManager().reportFailedBiometricAttempt( 520 currentUser); 521 } 522 } 523 524 @Override 525 public void onBiometricAuthenticated(int userId, BiometricSourceType biometricSourceType) { 526 if (mLockPatternUtils.isSecure(userId)) { 527 mLockPatternUtils.getDevicePolicyManager().reportSuccessfulBiometricAttempt( 528 userId); 529 } 530 } 531 532 @Override 533 public void onTrustChanged(int userId) { 534 if (userId == KeyguardUpdateMonitor.getCurrentUser()) { 535 synchronized (KeyguardViewMediator.this) { 536 notifyTrustedChangedLocked(mUpdateMonitor.getUserHasTrust(userId)); 537 } 538 } 539 } 540 541 @Override 542 public void onHasLockscreenWallpaperChanged(boolean hasLockscreenWallpaper) { 543 synchronized (KeyguardViewMediator.this) { 544 notifyHasLockscreenWallpaperChanged(hasLockscreenWallpaper); 545 } 546 } 547 }; 548 549 ViewMediatorCallback mViewMediatorCallback = new ViewMediatorCallback() { 550 551 @Override 552 public void userActivity() { 553 KeyguardViewMediator.this.userActivity(); 554 } 555 556 @Override 557 public void keyguardDone(boolean strongAuth, int targetUserId) { 558 if (targetUserId != ActivityManager.getCurrentUser()) { 559 return; 560 } 561 562 tryKeyguardDone(); 563 } 564 565 @Override 566 public void keyguardDoneDrawing() { 567 Trace.beginSection("KeyguardViewMediator.mViewMediatorCallback#keyguardDoneDrawing"); 568 mHandler.sendEmptyMessage(KEYGUARD_DONE_DRAWING); 569 Trace.endSection(); 570 } 571 572 @Override 573 public void setNeedsInput(boolean needsInput) { 574 mStatusBarKeyguardViewManager.setNeedsInput(needsInput); 575 } 576 577 @Override 578 public void keyguardDonePending(boolean strongAuth, int targetUserId) { 579 Trace.beginSection("KeyguardViewMediator.mViewMediatorCallback#keyguardDonePending"); 580 if (targetUserId != ActivityManager.getCurrentUser()) { 581 Trace.endSection(); 582 return; 583 } 584 585 mKeyguardDonePending = true; 586 mHideAnimationRun = true; 587 mHideAnimationRunning = true; 588 mStatusBarKeyguardViewManager.startPreHideAnimation(mHideAnimationFinishedRunnable); 589 mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_PENDING_TIMEOUT, 590 KEYGUARD_DONE_PENDING_TIMEOUT_MS); 591 Trace.endSection(); 592 } 593 594 @Override 595 public void keyguardGone() { 596 Trace.beginSection("KeyguardViewMediator.mViewMediatorCallback#keyguardGone"); 597 mKeyguardDisplayManager.hide(); 598 Trace.endSection(); 599 } 600 601 @Override 602 public void readyForKeyguardDone() { 603 Trace.beginSection("KeyguardViewMediator.mViewMediatorCallback#readyForKeyguardDone"); 604 if (mKeyguardDonePending) { 605 mKeyguardDonePending = false; 606 tryKeyguardDone(); 607 } 608 Trace.endSection(); 609 } 610 611 @Override 612 public void resetKeyguard() { 613 resetStateLocked(); 614 } 615 616 @Override 617 public void onCancelClicked() { 618 mStatusBarKeyguardViewManager.onCancelClicked(); 619 } 620 621 @Override 622 public void onBouncerVisiblityChanged(boolean shown) { 623 synchronized (KeyguardViewMediator.this) { 624 adjustStatusBarLocked(shown); 625 } 626 } 627 628 @Override 629 public void playTrustedSound() { 630 KeyguardViewMediator.this.playTrustedSound(); 631 } 632 633 @Override 634 public boolean isScreenOn() { 635 return mDeviceInteractive; 636 } 637 638 @Override 639 public int getBouncerPromptReason() { 640 int currentUser = ActivityManager.getCurrentUser(); 641 boolean trust = mTrustManager.isTrustUsuallyManaged(currentUser); 642 boolean biometrics = mUpdateMonitor.isUnlockingWithBiometricsPossible(currentUser); 643 boolean any = trust || biometrics; 644 KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker = 645 mUpdateMonitor.getStrongAuthTracker(); 646 int strongAuth = strongAuthTracker.getStrongAuthForUser(currentUser); 647 648 if (any && !strongAuthTracker.hasUserAuthenticatedSinceBoot()) { 649 return KeyguardSecurityView.PROMPT_REASON_RESTART; 650 } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_TIMEOUT) != 0) { 651 return KeyguardSecurityView.PROMPT_REASON_TIMEOUT; 652 } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW) != 0) { 653 return KeyguardSecurityView.PROMPT_REASON_DEVICE_ADMIN; 654 } else if (trust && (strongAuth & SOME_AUTH_REQUIRED_AFTER_USER_REQUEST) != 0) { 655 return KeyguardSecurityView.PROMPT_REASON_USER_REQUEST; 656 } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_LOCKOUT) != 0) { 657 return KeyguardSecurityView.PROMPT_REASON_AFTER_LOCKOUT; 658 } 659 return KeyguardSecurityView.PROMPT_REASON_NONE; 660 } 661 662 @Override 663 public CharSequence consumeCustomMessage() { 664 final CharSequence message = mCustomMessage; 665 mCustomMessage = null; 666 return message; 667 } 668 }; 669 userActivity()670 public void userActivity() { 671 mPM.userActivity(SystemClock.uptimeMillis(), false); 672 } 673 mustNotUnlockCurrentUser()674 boolean mustNotUnlockCurrentUser() { 675 return UserManager.isSplitSystemUser() 676 && KeyguardUpdateMonitor.getCurrentUser() == UserHandle.USER_SYSTEM; 677 } 678 setupLocked()679 private void setupLocked() { 680 mPM = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); 681 mTrustManager = (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE); 682 683 mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "show keyguard"); 684 mShowKeyguardWakeLock.setReferenceCounted(false); 685 686 IntentFilter filter = new IntentFilter(); 687 filter.addAction(Intent.ACTION_SHUTDOWN); 688 mContext.registerReceiver(mBroadcastReceiver, filter); 689 690 final IntentFilter delayedActionFilter = new IntentFilter(); 691 delayedActionFilter.addAction(DELAYED_KEYGUARD_ACTION); 692 delayedActionFilter.addAction(DELAYED_LOCK_PROFILE_ACTION); 693 mContext.registerReceiver(mDelayedLockBroadcastReceiver, delayedActionFilter, 694 SYSTEMUI_PERMISSION, null /* scheduler */); 695 696 InjectionInflationController injectionInflationController = 697 new InjectionInflationController(SystemUIFactory.getInstance().getRootComponent()); 698 mKeyguardDisplayManager = new KeyguardDisplayManager(mContext, 699 injectionInflationController); 700 701 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); 702 703 mUpdateMonitor = KeyguardUpdateMonitor.getInstance(mContext); 704 705 mLockPatternUtils = new LockPatternUtils(mContext); 706 KeyguardUpdateMonitor.setCurrentUser(ActivityManager.getCurrentUser()); 707 708 // Assume keyguard is showing (unless it's disabled) until we know for sure, unless Keyguard 709 // is disabled. 710 if (mContext.getResources().getBoolean( 711 com.android.keyguard.R.bool.config_enableKeyguardService)) { 712 setShowingLocked(!shouldWaitForProvisioning() 713 && !mLockPatternUtils.isLockScreenDisabled( 714 KeyguardUpdateMonitor.getCurrentUser()), 715 mAodShowing, true /* forceCallbacks */); 716 } else { 717 // The system's keyguard is disabled or missing. 718 setShowingLocked(false, mAodShowing, true); 719 } 720 721 mStatusBarKeyguardViewManager = 722 SystemUIFactory.getInstance().createStatusBarKeyguardViewManager(mContext, 723 mViewMediatorCallback, mLockPatternUtils); 724 final ContentResolver cr = mContext.getContentResolver(); 725 726 mDeviceInteractive = mPM.isInteractive(); 727 728 mLockSounds = new SoundPool.Builder() 729 .setMaxStreams(1) 730 .setAudioAttributes( 731 new AudioAttributes.Builder() 732 .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION) 733 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) 734 .build()) 735 .build(); 736 String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND); 737 if (soundPath != null) { 738 mLockSoundId = mLockSounds.load(soundPath, 1); 739 } 740 if (soundPath == null || mLockSoundId == 0) { 741 Log.w(TAG, "failed to load lock sound from " + soundPath); 742 } 743 soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND); 744 if (soundPath != null) { 745 mUnlockSoundId = mLockSounds.load(soundPath, 1); 746 } 747 if (soundPath == null || mUnlockSoundId == 0) { 748 Log.w(TAG, "failed to load unlock sound from " + soundPath); 749 } 750 soundPath = Settings.Global.getString(cr, Settings.Global.TRUSTED_SOUND); 751 if (soundPath != null) { 752 mTrustedSoundId = mLockSounds.load(soundPath, 1); 753 } 754 if (soundPath == null || mTrustedSoundId == 0) { 755 Log.w(TAG, "failed to load trusted sound from " + soundPath); 756 } 757 758 int lockSoundDefaultAttenuation = mContext.getResources().getInteger( 759 com.android.internal.R.integer.config_lockSoundVolumeDb); 760 mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20); 761 762 mHideAnimation = AnimationUtils.loadAnimation(mContext, 763 com.android.internal.R.anim.lock_screen_behind_enter); 764 765 mWorkLockController = new WorkLockActivityController(mContext); 766 } 767 768 @Override start()769 public void start() { 770 synchronized (this) { 771 setupLocked(); 772 } 773 putComponent(KeyguardViewMediator.class, this); 774 } 775 776 /** 777 * Let us know that the system is ready after startup. 778 */ onSystemReady()779 public void onSystemReady() { 780 mHandler.obtainMessage(SYSTEM_READY).sendToTarget(); 781 } 782 handleSystemReady()783 private void handleSystemReady() { 784 synchronized (this) { 785 if (DEBUG) Log.d(TAG, "onSystemReady"); 786 mSystemReady = true; 787 doKeyguardLocked(null); 788 mUpdateMonitor.registerCallback(mUpdateCallback); 789 } 790 // Most services aren't available until the system reaches the ready state, so we 791 // send it here when the device first boots. 792 maybeSendUserPresentBroadcast(); 793 } 794 795 /** 796 * Called to let us know the screen was turned off. 797 * @param why either {@link WindowManagerPolicyConstants#OFF_BECAUSE_OF_USER} or 798 * {@link WindowManagerPolicyConstants#OFF_BECAUSE_OF_TIMEOUT}. 799 */ onStartedGoingToSleep(int why)800 public void onStartedGoingToSleep(int why) { 801 if (DEBUG) Log.d(TAG, "onStartedGoingToSleep(" + why + ")"); 802 synchronized (this) { 803 mDeviceInteractive = false; 804 mGoingToSleep = true; 805 806 // Lock immediately based on setting if secure (user has a pin/pattern/password). 807 // This also "locks" the device when not secure to provide easy access to the 808 // camera while preventing unwanted input. 809 int currentUser = KeyguardUpdateMonitor.getCurrentUser(); 810 final boolean lockImmediately = 811 mLockPatternUtils.getPowerButtonInstantlyLocks(currentUser) 812 || !mLockPatternUtils.isSecure(currentUser); 813 long timeout = getLockTimeout(KeyguardUpdateMonitor.getCurrentUser()); 814 mLockLater = false; 815 if (mExitSecureCallback != null) { 816 if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled"); 817 try { 818 mExitSecureCallback.onKeyguardExitResult(false); 819 } catch (RemoteException e) { 820 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); 821 } 822 mExitSecureCallback = null; 823 if (!mExternallyEnabled) { 824 hideLocked(); 825 } 826 } else if (mShowing) { 827 mPendingReset = true; 828 } else if ((why == WindowManagerPolicyConstants.OFF_BECAUSE_OF_TIMEOUT && timeout > 0) 829 || (why == WindowManagerPolicyConstants.OFF_BECAUSE_OF_USER && !lockImmediately)) { 830 doKeyguardLaterLocked(timeout); 831 mLockLater = true; 832 } else if (!mLockPatternUtils.isLockScreenDisabled(currentUser)) { 833 mPendingLock = true; 834 } 835 836 if (mPendingLock) { 837 playSounds(true); 838 } 839 } 840 KeyguardUpdateMonitor.getInstance(mContext).dispatchStartedGoingToSleep(why); 841 notifyStartedGoingToSleep(); 842 } 843 onFinishedGoingToSleep(int why, boolean cameraGestureTriggered)844 public void onFinishedGoingToSleep(int why, boolean cameraGestureTriggered) { 845 if (DEBUG) Log.d(TAG, "onFinishedGoingToSleep(" + why + ")"); 846 synchronized (this) { 847 mDeviceInteractive = false; 848 mGoingToSleep = false; 849 mWakeAndUnlocking = false; 850 851 resetKeyguardDonePendingLocked(); 852 mHideAnimationRun = false; 853 854 notifyFinishedGoingToSleep(); 855 856 if (cameraGestureTriggered) { 857 Log.i(TAG, "Camera gesture was triggered, preventing Keyguard locking."); 858 859 // Just to make sure, make sure the device is awake. 860 mContext.getSystemService(PowerManager.class).wakeUp(SystemClock.uptimeMillis(), 861 PowerManager.WAKE_REASON_CAMERA_LAUNCH, 862 "com.android.systemui:CAMERA_GESTURE_PREVENT_LOCK"); 863 mPendingLock = false; 864 mPendingReset = false; 865 } 866 867 if (mPendingReset) { 868 resetStateLocked(); 869 mPendingReset = false; 870 } 871 872 if (mPendingLock) { 873 doKeyguardLocked(null); 874 mPendingLock = false; 875 } 876 877 // We do not have timeout and power button instant lock setting for profile lock. 878 // So we use the personal setting if there is any. But if there is no device 879 // we need to make sure we lock it immediately when the screen is off. 880 if (!mLockLater && !cameraGestureTriggered) { 881 doKeyguardForChildProfilesLocked(); 882 } 883 884 } 885 KeyguardUpdateMonitor.getInstance(mContext).dispatchFinishedGoingToSleep(why); 886 } 887 getLockTimeout(int userId)888 private long getLockTimeout(int userId) { 889 // if the screen turned off because of timeout or the user hit the power button 890 // and we don't need to lock immediately, set an alarm 891 // to enable it a little bit later (i.e, give the user a chance 892 // to turn the screen back on within a certain window without 893 // having to unlock the screen) 894 final ContentResolver cr = mContext.getContentResolver(); 895 896 // From SecuritySettings 897 final long lockAfterTimeout = Settings.Secure.getInt(cr, 898 Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 899 KEYGUARD_LOCK_AFTER_DELAY_DEFAULT); 900 901 // From DevicePolicyAdmin 902 final long policyTimeout = mLockPatternUtils.getDevicePolicyManager() 903 .getMaximumTimeToLock(null, userId); 904 905 long timeout; 906 907 if (policyTimeout <= 0) { 908 timeout = lockAfterTimeout; 909 } else { 910 // From DisplaySettings 911 long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT, 912 KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT); 913 914 // policy in effect. Make sure we don't go beyond policy limit. 915 displayTimeout = Math.max(displayTimeout, 0); // ignore negative values 916 timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout); 917 timeout = Math.max(timeout, 0); 918 } 919 return timeout; 920 } 921 doKeyguardLaterLocked()922 private void doKeyguardLaterLocked() { 923 long timeout = getLockTimeout(KeyguardUpdateMonitor.getCurrentUser()); 924 if (timeout == 0) { 925 doKeyguardLocked(null); 926 } else { 927 doKeyguardLaterLocked(timeout); 928 } 929 } 930 doKeyguardLaterLocked(long timeout)931 private void doKeyguardLaterLocked(long timeout) { 932 // Lock in the future 933 long when = SystemClock.elapsedRealtime() + timeout; 934 Intent intent = new Intent(DELAYED_KEYGUARD_ACTION); 935 intent.putExtra("seq", mDelayedShowingSequence); 936 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 937 PendingIntent sender = PendingIntent.getBroadcast(mContext, 938 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); 939 mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender); 940 if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = " 941 + mDelayedShowingSequence); 942 doKeyguardLaterForChildProfilesLocked(); 943 } 944 doKeyguardLaterForChildProfilesLocked()945 private void doKeyguardLaterForChildProfilesLocked() { 946 UserManager um = UserManager.get(mContext); 947 for (int profileId : um.getEnabledProfileIds(UserHandle.myUserId())) { 948 if (mLockPatternUtils.isSeparateProfileChallengeEnabled(profileId)) { 949 long userTimeout = getLockTimeout(profileId); 950 if (userTimeout == 0) { 951 doKeyguardForChildProfilesLocked(); 952 } else { 953 long userWhen = SystemClock.elapsedRealtime() + userTimeout; 954 Intent lockIntent = new Intent(DELAYED_LOCK_PROFILE_ACTION); 955 lockIntent.putExtra("seq", mDelayedProfileShowingSequence); 956 lockIntent.putExtra(Intent.EXTRA_USER_ID, profileId); 957 lockIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 958 PendingIntent lockSender = PendingIntent.getBroadcast( 959 mContext, 0, lockIntent, PendingIntent.FLAG_CANCEL_CURRENT); 960 mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, 961 userWhen, lockSender); 962 } 963 } 964 } 965 } 966 doKeyguardForChildProfilesLocked()967 private void doKeyguardForChildProfilesLocked() { 968 UserManager um = UserManager.get(mContext); 969 for (int profileId : um.getEnabledProfileIds(UserHandle.myUserId())) { 970 if (mLockPatternUtils.isSeparateProfileChallengeEnabled(profileId)) { 971 lockProfile(profileId); 972 } 973 } 974 } 975 cancelDoKeyguardLaterLocked()976 private void cancelDoKeyguardLaterLocked() { 977 mDelayedShowingSequence++; 978 } 979 cancelDoKeyguardForChildProfilesLocked()980 private void cancelDoKeyguardForChildProfilesLocked() { 981 mDelayedProfileShowingSequence++; 982 } 983 984 /** 985 * Let's us know when the device is waking up. 986 */ onStartedWakingUp()987 public void onStartedWakingUp() { 988 Trace.beginSection("KeyguardViewMediator#onStartedWakingUp"); 989 990 // TODO: Rename all screen off/on references to interactive/sleeping 991 synchronized (this) { 992 mDeviceInteractive = true; 993 cancelDoKeyguardLaterLocked(); 994 cancelDoKeyguardForChildProfilesLocked(); 995 if (DEBUG) Log.d(TAG, "onStartedWakingUp, seq = " + mDelayedShowingSequence); 996 notifyStartedWakingUp(); 997 } 998 KeyguardUpdateMonitor.getInstance(mContext).dispatchStartedWakingUp(); 999 maybeSendUserPresentBroadcast(); 1000 Trace.endSection(); 1001 } 1002 onScreenTurningOn(IKeyguardDrawnCallback callback)1003 public void onScreenTurningOn(IKeyguardDrawnCallback callback) { 1004 Trace.beginSection("KeyguardViewMediator#onScreenTurningOn"); 1005 notifyScreenOn(callback); 1006 Trace.endSection(); 1007 } 1008 onScreenTurnedOn()1009 public void onScreenTurnedOn() { 1010 Trace.beginSection("KeyguardViewMediator#onScreenTurnedOn"); 1011 notifyScreenTurnedOn(); 1012 mUpdateMonitor.dispatchScreenTurnedOn(); 1013 Trace.endSection(); 1014 } 1015 onScreenTurnedOff()1016 public void onScreenTurnedOff() { 1017 notifyScreenTurnedOff(); 1018 mUpdateMonitor.dispatchScreenTurnedOff(); 1019 } 1020 maybeSendUserPresentBroadcast()1021 private void maybeSendUserPresentBroadcast() { 1022 if (mSystemReady && mLockPatternUtils.isLockScreenDisabled( 1023 KeyguardUpdateMonitor.getCurrentUser())) { 1024 // Lock screen is disabled because the user has set the preference to "None". 1025 // In this case, send out ACTION_USER_PRESENT here instead of in 1026 // handleKeyguardDone() 1027 sendUserPresentBroadcast(); 1028 } else if (mSystemReady && shouldWaitForProvisioning()) { 1029 // Skipping the lockscreen because we're not yet provisioned, but we still need to 1030 // notify the StrongAuthTracker that it's now safe to run trust agents, in case the 1031 // user sets a credential later. 1032 getLockPatternUtils().userPresent(KeyguardUpdateMonitor.getCurrentUser()); 1033 } 1034 } 1035 1036 /** 1037 * A dream started. We should lock after the usual screen-off lock timeout but only 1038 * if there is a secure lock pattern. 1039 */ onDreamingStarted()1040 public void onDreamingStarted() { 1041 KeyguardUpdateMonitor.getInstance(mContext).dispatchDreamingStarted(); 1042 synchronized (this) { 1043 if (mDeviceInteractive 1044 && mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())) { 1045 doKeyguardLaterLocked(); 1046 } 1047 } 1048 } 1049 1050 /** 1051 * A dream stopped. 1052 */ onDreamingStopped()1053 public void onDreamingStopped() { 1054 KeyguardUpdateMonitor.getInstance(mContext).dispatchDreamingStopped(); 1055 synchronized (this) { 1056 if (mDeviceInteractive) { 1057 cancelDoKeyguardLaterLocked(); 1058 } 1059 } 1060 } 1061 1062 /** 1063 * Same semantics as {@link WindowManagerPolicyConstants#enableKeyguard}; provide 1064 * a way for external stuff to override normal keyguard behavior. For instance 1065 * the phone app disables the keyguard when it receives incoming calls. 1066 */ setKeyguardEnabled(boolean enabled)1067 public void setKeyguardEnabled(boolean enabled) { 1068 synchronized (this) { 1069 if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")"); 1070 1071 mExternallyEnabled = enabled; 1072 1073 if (!enabled && mShowing) { 1074 if (mExitSecureCallback != null) { 1075 if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring"); 1076 // we're in the process of handling a request to verify the user 1077 // can get past the keyguard. ignore extraneous requests to disable / reenable 1078 return; 1079 } 1080 1081 // hiding keyguard that is showing, remember to reshow later 1082 if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, " 1083 + "disabling status bar expansion"); 1084 mNeedToReshowWhenReenabled = true; 1085 updateInputRestrictedLocked(); 1086 hideLocked(); 1087 } else if (enabled && mNeedToReshowWhenReenabled) { 1088 // reenabled after previously hidden, reshow 1089 if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling " 1090 + "status bar expansion"); 1091 mNeedToReshowWhenReenabled = false; 1092 updateInputRestrictedLocked(); 1093 1094 if (mExitSecureCallback != null) { 1095 if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting"); 1096 try { 1097 mExitSecureCallback.onKeyguardExitResult(false); 1098 } catch (RemoteException e) { 1099 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); 1100 } 1101 mExitSecureCallback = null; 1102 resetStateLocked(); 1103 } else { 1104 showLocked(null); 1105 1106 // block until we know the keygaurd is done drawing (and post a message 1107 // to unblock us after a timeout so we don't risk blocking too long 1108 // and causing an ANR). 1109 mWaitingUntilKeyguardVisible = true; 1110 mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS); 1111 if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false"); 1112 while (mWaitingUntilKeyguardVisible) { 1113 try { 1114 wait(); 1115 } catch (InterruptedException e) { 1116 Thread.currentThread().interrupt(); 1117 } 1118 } 1119 if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible"); 1120 } 1121 } 1122 } 1123 } 1124 1125 /** 1126 * @see android.app.KeyguardManager#exitKeyguardSecurely 1127 */ verifyUnlock(IKeyguardExitCallback callback)1128 public void verifyUnlock(IKeyguardExitCallback callback) { 1129 Trace.beginSection("KeyguardViewMediator#verifyUnlock"); 1130 synchronized (this) { 1131 if (DEBUG) Log.d(TAG, "verifyUnlock"); 1132 if (shouldWaitForProvisioning()) { 1133 // don't allow this api when the device isn't provisioned 1134 if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned"); 1135 try { 1136 callback.onKeyguardExitResult(false); 1137 } catch (RemoteException e) { 1138 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); 1139 } 1140 } else if (mExternallyEnabled) { 1141 // this only applies when the user has externally disabled the 1142 // keyguard. this is unexpected and means the user is not 1143 // using the api properly. 1144 Log.w(TAG, "verifyUnlock called when not externally disabled"); 1145 try { 1146 callback.onKeyguardExitResult(false); 1147 } catch (RemoteException e) { 1148 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); 1149 } 1150 } else if (mExitSecureCallback != null) { 1151 // already in progress with someone else 1152 try { 1153 callback.onKeyguardExitResult(false); 1154 } catch (RemoteException e) { 1155 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); 1156 } 1157 } else if (!isSecure()) { 1158 1159 // Keyguard is not secure, no need to do anything, and we don't need to reshow 1160 // the Keyguard after the client releases the Keyguard lock. 1161 mExternallyEnabled = true; 1162 mNeedToReshowWhenReenabled = false; 1163 updateInputRestricted(); 1164 try { 1165 callback.onKeyguardExitResult(true); 1166 } catch (RemoteException e) { 1167 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); 1168 } 1169 } else { 1170 1171 // Since we prevent apps from hiding the Keyguard if we are secure, this should be 1172 // a no-op as well. 1173 try { 1174 callback.onKeyguardExitResult(false); 1175 } catch (RemoteException e) { 1176 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); 1177 } 1178 } 1179 } 1180 Trace.endSection(); 1181 } 1182 1183 /** 1184 * Is the keyguard currently showing and not being force hidden? 1185 */ isShowingAndNotOccluded()1186 public boolean isShowingAndNotOccluded() { 1187 return mShowing && !mOccluded; 1188 } 1189 1190 /** 1191 * Notify us when the keyguard is occluded by another window 1192 */ setOccluded(boolean isOccluded, boolean animate)1193 public void setOccluded(boolean isOccluded, boolean animate) { 1194 Trace.beginSection("KeyguardViewMediator#setOccluded"); 1195 if (DEBUG) Log.d(TAG, "setOccluded " + isOccluded); 1196 mHandler.removeMessages(SET_OCCLUDED); 1197 Message msg = mHandler.obtainMessage(SET_OCCLUDED, isOccluded ? 1 : 0, animate ? 1 : 0); 1198 mHandler.sendMessage(msg); 1199 Trace.endSection(); 1200 } 1201 isHiding()1202 public boolean isHiding() { 1203 return mHiding; 1204 } 1205 1206 /** 1207 * Handles SET_OCCLUDED message sent by setOccluded() 1208 */ handleSetOccluded(boolean isOccluded, boolean animate)1209 private void handleSetOccluded(boolean isOccluded, boolean animate) { 1210 Trace.beginSection("KeyguardViewMediator#handleSetOccluded"); 1211 synchronized (KeyguardViewMediator.this) { 1212 if (mHiding && isOccluded) { 1213 // We're in the process of going away but WindowManager wants to show a 1214 // SHOW_WHEN_LOCKED activity instead. 1215 startKeyguardExitAnimation(0, 0); 1216 } 1217 1218 if (mOccluded != isOccluded) { 1219 mOccluded = isOccluded; 1220 mUpdateMonitor.setKeyguardOccluded(isOccluded); 1221 mStatusBarKeyguardViewManager.setOccluded(isOccluded, animate 1222 && mDeviceInteractive); 1223 adjustStatusBarLocked(); 1224 } 1225 } 1226 Trace.endSection(); 1227 } 1228 1229 /** 1230 * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout. 1231 * This must be safe to call from any thread and with any window manager locks held. 1232 */ doKeyguardTimeout(Bundle options)1233 public void doKeyguardTimeout(Bundle options) { 1234 mHandler.removeMessages(KEYGUARD_TIMEOUT); 1235 Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options); 1236 mHandler.sendMessage(msg); 1237 } 1238 1239 /** 1240 * Given the state of the keyguard, is the input restricted? 1241 * Input is restricted when the keyguard is showing, or when the keyguard 1242 * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet. 1243 */ isInputRestricted()1244 public boolean isInputRestricted() { 1245 return mShowing || mNeedToReshowWhenReenabled; 1246 } 1247 updateInputRestricted()1248 private void updateInputRestricted() { 1249 synchronized (this) { 1250 updateInputRestrictedLocked(); 1251 } 1252 } 1253 updateInputRestrictedLocked()1254 private void updateInputRestrictedLocked() { 1255 boolean inputRestricted = isInputRestricted(); 1256 if (mInputRestricted != inputRestricted) { 1257 mInputRestricted = inputRestricted; 1258 int size = mKeyguardStateCallbacks.size(); 1259 for (int i = size - 1; i >= 0; i--) { 1260 final IKeyguardStateCallback callback = mKeyguardStateCallbacks.get(i); 1261 try { 1262 callback.onInputRestrictedStateChanged(inputRestricted); 1263 } catch (RemoteException e) { 1264 Slog.w(TAG, "Failed to call onDeviceProvisioned", e); 1265 if (e instanceof DeadObjectException) { 1266 mKeyguardStateCallbacks.remove(callback); 1267 } 1268 } 1269 } 1270 } 1271 } 1272 1273 /** 1274 * Enable the keyguard if the settings are appropriate. 1275 */ doKeyguardLocked(Bundle options)1276 private void doKeyguardLocked(Bundle options) { 1277 if (KeyguardUpdateMonitor.CORE_APPS_ONLY) { 1278 // Don't show keyguard during half-booted cryptkeeper stage. 1279 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because booting to cryptkeeper"); 1280 return; 1281 } 1282 1283 // if another app is disabling us, don't show 1284 if (!mExternallyEnabled) { 1285 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled"); 1286 1287 mNeedToReshowWhenReenabled = true; 1288 return; 1289 } 1290 1291 // if the keyguard is already showing, don't bother 1292 if (mStatusBarKeyguardViewManager.isShowing()) { 1293 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing"); 1294 resetStateLocked(); 1295 return; 1296 } 1297 1298 // In split system user mode, we never unlock system user. 1299 if (!mustNotUnlockCurrentUser() 1300 || !mUpdateMonitor.isDeviceProvisioned()) { 1301 1302 // if the setup wizard hasn't run yet, don't show 1303 final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim", false); 1304 final boolean absent = SubscriptionManager.isValidSubscriptionId( 1305 mUpdateMonitor.getNextSubIdForState(ABSENT)); 1306 final boolean disabled = SubscriptionManager.isValidSubscriptionId( 1307 mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.PERM_DISABLED)); 1308 final boolean lockedOrMissing = mUpdateMonitor.isSimPinSecure() 1309 || ((absent || disabled) && requireSim); 1310 1311 if (!lockedOrMissing && shouldWaitForProvisioning()) { 1312 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned" 1313 + " and the sim is not locked or missing"); 1314 return; 1315 } 1316 1317 boolean forceShow = options != null && options.getBoolean(OPTION_FORCE_SHOW, false); 1318 if (mLockPatternUtils.isLockScreenDisabled(KeyguardUpdateMonitor.getCurrentUser()) 1319 && !lockedOrMissing && !forceShow) { 1320 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off"); 1321 return; 1322 } 1323 1324 if (mLockPatternUtils.checkVoldPassword(KeyguardUpdateMonitor.getCurrentUser())) { 1325 if (DEBUG) Log.d(TAG, "Not showing lock screen since just decrypted"); 1326 // Without this, settings is not enabled until the lock screen first appears 1327 setShowingLocked(false, mAodShowing); 1328 hideLocked(); 1329 return; 1330 } 1331 } 1332 1333 if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen"); 1334 showLocked(options); 1335 } 1336 lockProfile(int userId)1337 private void lockProfile(int userId) { 1338 mTrustManager.setDeviceLockedForUser(userId, true); 1339 } 1340 shouldWaitForProvisioning()1341 private boolean shouldWaitForProvisioning() { 1342 return !mUpdateMonitor.isDeviceProvisioned() && !isSecure(); 1343 } 1344 1345 /** 1346 * Dismiss the keyguard through the security layers. 1347 * @param callback Callback to be informed about the result 1348 * @param message Message that should be displayed on the bouncer. 1349 */ handleDismiss(IKeyguardDismissCallback callback, CharSequence message)1350 private void handleDismiss(IKeyguardDismissCallback callback, CharSequence message) { 1351 if (mShowing) { 1352 if (callback != null) { 1353 mDismissCallbackRegistry.addCallback(callback); 1354 } 1355 mCustomMessage = message; 1356 mStatusBarKeyguardViewManager.dismissAndCollapse(); 1357 } else if (callback != null) { 1358 new DismissCallbackWrapper(callback).notifyDismissError(); 1359 } 1360 } 1361 dismiss(IKeyguardDismissCallback callback, CharSequence message)1362 public void dismiss(IKeyguardDismissCallback callback, CharSequence message) { 1363 mHandler.obtainMessage(DISMISS, new DismissMessage(callback, message)).sendToTarget(); 1364 } 1365 1366 /** 1367 * Send message to keyguard telling it to reset its state. 1368 * @see #handleReset 1369 */ resetStateLocked()1370 private void resetStateLocked() { 1371 if (DEBUG) Log.e(TAG, "resetStateLocked"); 1372 Message msg = mHandler.obtainMessage(RESET); 1373 mHandler.sendMessage(msg); 1374 } 1375 1376 /** 1377 * Send message to keyguard telling it to verify unlock 1378 * @see #handleVerifyUnlock() 1379 */ verifyUnlockLocked()1380 private void verifyUnlockLocked() { 1381 if (DEBUG) Log.d(TAG, "verifyUnlockLocked"); 1382 mHandler.sendEmptyMessage(VERIFY_UNLOCK); 1383 } 1384 notifyStartedGoingToSleep()1385 private void notifyStartedGoingToSleep() { 1386 if (DEBUG) Log.d(TAG, "notifyStartedGoingToSleep"); 1387 mHandler.sendEmptyMessage(NOTIFY_STARTED_GOING_TO_SLEEP); 1388 } 1389 notifyFinishedGoingToSleep()1390 private void notifyFinishedGoingToSleep() { 1391 if (DEBUG) Log.d(TAG, "notifyFinishedGoingToSleep"); 1392 mHandler.sendEmptyMessage(NOTIFY_FINISHED_GOING_TO_SLEEP); 1393 } 1394 notifyStartedWakingUp()1395 private void notifyStartedWakingUp() { 1396 if (DEBUG) Log.d(TAG, "notifyStartedWakingUp"); 1397 mHandler.sendEmptyMessage(NOTIFY_STARTED_WAKING_UP); 1398 } 1399 notifyScreenOn(IKeyguardDrawnCallback callback)1400 private void notifyScreenOn(IKeyguardDrawnCallback callback) { 1401 if (DEBUG) Log.d(TAG, "notifyScreenOn"); 1402 Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNING_ON, callback); 1403 mHandler.sendMessage(msg); 1404 } 1405 notifyScreenTurnedOn()1406 private void notifyScreenTurnedOn() { 1407 if (DEBUG) Log.d(TAG, "notifyScreenTurnedOn"); 1408 Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNED_ON); 1409 mHandler.sendMessage(msg); 1410 } 1411 notifyScreenTurnedOff()1412 private void notifyScreenTurnedOff() { 1413 if (DEBUG) Log.d(TAG, "notifyScreenTurnedOff"); 1414 Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNED_OFF); 1415 mHandler.sendMessage(msg); 1416 } 1417 1418 /** 1419 * Send message to keyguard telling it to show itself 1420 * @see #handleShow 1421 */ showLocked(Bundle options)1422 private void showLocked(Bundle options) { 1423 Trace.beginSection("KeyguardViewMediator#showLocked aqcuiring mShowKeyguardWakeLock"); 1424 if (DEBUG) Log.d(TAG, "showLocked"); 1425 // ensure we stay awake until we are finished displaying the keyguard 1426 mShowKeyguardWakeLock.acquire(); 1427 Message msg = mHandler.obtainMessage(SHOW, options); 1428 mHandler.sendMessage(msg); 1429 Trace.endSection(); 1430 } 1431 1432 /** 1433 * Send message to keyguard telling it to hide itself 1434 * @see #handleHide() 1435 */ hideLocked()1436 private void hideLocked() { 1437 Trace.beginSection("KeyguardViewMediator#hideLocked"); 1438 if (DEBUG) Log.d(TAG, "hideLocked"); 1439 Message msg = mHandler.obtainMessage(HIDE); 1440 mHandler.sendMessage(msg); 1441 Trace.endSection(); 1442 } 1443 isSecure()1444 public boolean isSecure() { 1445 return isSecure(KeyguardUpdateMonitor.getCurrentUser()); 1446 } 1447 isSecure(int userId)1448 public boolean isSecure(int userId) { 1449 return mLockPatternUtils.isSecure(userId) 1450 || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure(); 1451 } 1452 setSwitchingUser(boolean switching)1453 public void setSwitchingUser(boolean switching) { 1454 KeyguardUpdateMonitor.getInstance(mContext).setSwitchingUser(switching); 1455 } 1456 1457 /** 1458 * Update the newUserId. Call while holding WindowManagerService lock. 1459 * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing. 1460 * 1461 * @param newUserId The id of the incoming user. 1462 */ setCurrentUser(int newUserId)1463 public void setCurrentUser(int newUserId) { 1464 KeyguardUpdateMonitor.setCurrentUser(newUserId); 1465 synchronized (this) { 1466 notifyTrustedChangedLocked(mUpdateMonitor.getUserHasTrust(newUserId)); 1467 } 1468 } 1469 1470 /** 1471 * This broadcast receiver should be registered with the SystemUI permission. 1472 */ 1473 private final BroadcastReceiver mDelayedLockBroadcastReceiver = new BroadcastReceiver() { 1474 @Override 1475 public void onReceive(Context context, Intent intent) { 1476 if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) { 1477 final int sequence = intent.getIntExtra("seq", 0); 1478 if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = " 1479 + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence); 1480 synchronized (KeyguardViewMediator.this) { 1481 if (mDelayedShowingSequence == sequence) { 1482 doKeyguardLocked(null); 1483 } 1484 } 1485 } else if (DELAYED_LOCK_PROFILE_ACTION.equals(intent.getAction())) { 1486 final int sequence = intent.getIntExtra("seq", 0); 1487 int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, 0); 1488 if (userId != 0) { 1489 synchronized (KeyguardViewMediator.this) { 1490 if (mDelayedProfileShowingSequence == sequence) { 1491 lockProfile(userId); 1492 } 1493 } 1494 } 1495 } 1496 } 1497 }; 1498 1499 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { 1500 @Override 1501 public void onReceive(Context context, Intent intent) { 1502 if (Intent.ACTION_SHUTDOWN.equals(intent.getAction())) { 1503 synchronized (KeyguardViewMediator.this){ 1504 mShuttingDown = true; 1505 } 1506 } 1507 } 1508 }; 1509 keyguardDone()1510 public void keyguardDone() { 1511 Trace.beginSection("KeyguardViewMediator#keyguardDone"); 1512 if (DEBUG) Log.d(TAG, "keyguardDone()"); 1513 userActivity(); 1514 EventLog.writeEvent(70000, 2); 1515 Message msg = mHandler.obtainMessage(KEYGUARD_DONE); 1516 mHandler.sendMessage(msg); 1517 Trace.endSection(); 1518 } 1519 1520 /** 1521 * This handler will be associated with the policy thread, which will also 1522 * be the UI thread of the keyguard. Since the apis of the policy, and therefore 1523 * this class, can be called by other threads, any action that directly 1524 * interacts with the keyguard ui should be posted to this handler, rather 1525 * than called directly. 1526 */ 1527 private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) { 1528 @Override 1529 public void handleMessage(Message msg) { 1530 switch (msg.what) { 1531 case SHOW: 1532 handleShow((Bundle) msg.obj); 1533 break; 1534 case HIDE: 1535 handleHide(); 1536 break; 1537 case RESET: 1538 handleReset(); 1539 break; 1540 case VERIFY_UNLOCK: 1541 Trace.beginSection("KeyguardViewMediator#handleMessage VERIFY_UNLOCK"); 1542 handleVerifyUnlock(); 1543 Trace.endSection(); 1544 break; 1545 case NOTIFY_STARTED_GOING_TO_SLEEP: 1546 handleNotifyStartedGoingToSleep(); 1547 break; 1548 case NOTIFY_FINISHED_GOING_TO_SLEEP: 1549 handleNotifyFinishedGoingToSleep(); 1550 break; 1551 case NOTIFY_SCREEN_TURNING_ON: 1552 Trace.beginSection("KeyguardViewMediator#handleMessage NOTIFY_SCREEN_TURNING_ON"); 1553 handleNotifyScreenTurningOn((IKeyguardDrawnCallback) msg.obj); 1554 Trace.endSection(); 1555 break; 1556 case NOTIFY_SCREEN_TURNED_ON: 1557 Trace.beginSection("KeyguardViewMediator#handleMessage NOTIFY_SCREEN_TURNED_ON"); 1558 handleNotifyScreenTurnedOn(); 1559 Trace.endSection(); 1560 break; 1561 case NOTIFY_SCREEN_TURNED_OFF: 1562 handleNotifyScreenTurnedOff(); 1563 break; 1564 case NOTIFY_STARTED_WAKING_UP: 1565 Trace.beginSection("KeyguardViewMediator#handleMessage NOTIFY_STARTED_WAKING_UP"); 1566 handleNotifyStartedWakingUp(); 1567 Trace.endSection(); 1568 break; 1569 case KEYGUARD_DONE: 1570 Trace.beginSection("KeyguardViewMediator#handleMessage KEYGUARD_DONE"); 1571 handleKeyguardDone(); 1572 Trace.endSection(); 1573 break; 1574 case KEYGUARD_DONE_DRAWING: 1575 Trace.beginSection("KeyguardViewMediator#handleMessage KEYGUARD_DONE_DRAWING"); 1576 handleKeyguardDoneDrawing(); 1577 Trace.endSection(); 1578 break; 1579 case SET_OCCLUDED: 1580 Trace.beginSection("KeyguardViewMediator#handleMessage SET_OCCLUDED"); 1581 handleSetOccluded(msg.arg1 != 0, msg.arg2 != 0); 1582 Trace.endSection(); 1583 break; 1584 case KEYGUARD_TIMEOUT: 1585 synchronized (KeyguardViewMediator.this) { 1586 doKeyguardLocked((Bundle) msg.obj); 1587 } 1588 break; 1589 case DISMISS: 1590 final DismissMessage message = (DismissMessage) msg.obj; 1591 handleDismiss(message.getCallback(), message.getMessage()); 1592 break; 1593 case START_KEYGUARD_EXIT_ANIM: 1594 Trace.beginSection("KeyguardViewMediator#handleMessage START_KEYGUARD_EXIT_ANIM"); 1595 StartKeyguardExitAnimParams params = (StartKeyguardExitAnimParams) msg.obj; 1596 handleStartKeyguardExitAnimation(params.startTime, params.fadeoutDuration); 1597 FalsingManagerFactory.getInstance(mContext).onSucccessfulUnlock(); 1598 Trace.endSection(); 1599 break; 1600 case KEYGUARD_DONE_PENDING_TIMEOUT: 1601 Trace.beginSection("KeyguardViewMediator#handleMessage KEYGUARD_DONE_PENDING_TIMEOUT"); 1602 Log.w(TAG, "Timeout while waiting for activity drawn!"); 1603 Trace.endSection(); 1604 break; 1605 case SYSTEM_READY: 1606 handleSystemReady(); 1607 break; 1608 } 1609 } 1610 }; 1611 tryKeyguardDone()1612 private void tryKeyguardDone() { 1613 if (!mKeyguardDonePending && mHideAnimationRun && !mHideAnimationRunning) { 1614 handleKeyguardDone(); 1615 } else if (!mHideAnimationRun) { 1616 mHideAnimationRun = true; 1617 mHideAnimationRunning = true; 1618 mStatusBarKeyguardViewManager.startPreHideAnimation(mHideAnimationFinishedRunnable); 1619 } 1620 } 1621 1622 /** 1623 * @see #keyguardDone 1624 * @see #KEYGUARD_DONE 1625 */ handleKeyguardDone()1626 private void handleKeyguardDone() { 1627 Trace.beginSection("KeyguardViewMediator#handleKeyguardDone"); 1628 final int currentUser = KeyguardUpdateMonitor.getCurrentUser(); 1629 mUiOffloadThread.submit(() -> { 1630 if (mLockPatternUtils.isSecure(currentUser)) { 1631 mLockPatternUtils.getDevicePolicyManager().reportKeyguardDismissed(currentUser); 1632 } 1633 }); 1634 if (DEBUG) Log.d(TAG, "handleKeyguardDone"); 1635 synchronized (this) { 1636 resetKeyguardDonePendingLocked(); 1637 } 1638 1639 mUpdateMonitor.clearBiometricRecognized(); 1640 1641 if (mGoingToSleep) { 1642 Log.i(TAG, "Device is going to sleep, aborting keyguardDone"); 1643 return; 1644 } 1645 if (mExitSecureCallback != null) { 1646 try { 1647 mExitSecureCallback.onKeyguardExitResult(true /* authenciated */); 1648 } catch (RemoteException e) { 1649 Slog.w(TAG, "Failed to call onKeyguardExitResult()", e); 1650 } 1651 1652 mExitSecureCallback = null; 1653 1654 // after succesfully exiting securely, no need to reshow 1655 // the keyguard when they've released the lock 1656 mExternallyEnabled = true; 1657 mNeedToReshowWhenReenabled = false; 1658 updateInputRestricted(); 1659 } 1660 1661 handleHide(); 1662 Trace.endSection(); 1663 } 1664 sendUserPresentBroadcast()1665 private void sendUserPresentBroadcast() { 1666 synchronized (this) { 1667 if (mBootCompleted) { 1668 int currentUserId = KeyguardUpdateMonitor.getCurrentUser(); 1669 final UserHandle currentUser = new UserHandle(currentUserId); 1670 final UserManager um = (UserManager) mContext.getSystemService( 1671 Context.USER_SERVICE); 1672 mUiOffloadThread.submit(() -> { 1673 for (int profileId : um.getProfileIdsWithDisabled(currentUser.getIdentifier())) { 1674 mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, UserHandle.of(profileId)); 1675 } 1676 getLockPatternUtils().userPresent(currentUserId); 1677 }); 1678 } else { 1679 mBootSendUserPresent = true; 1680 } 1681 } 1682 } 1683 1684 /** 1685 * @see #keyguardDone 1686 * @see #KEYGUARD_DONE_DRAWING 1687 */ handleKeyguardDoneDrawing()1688 private void handleKeyguardDoneDrawing() { 1689 Trace.beginSection("KeyguardViewMediator#handleKeyguardDoneDrawing"); 1690 synchronized(this) { 1691 if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing"); 1692 if (mWaitingUntilKeyguardVisible) { 1693 if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible"); 1694 mWaitingUntilKeyguardVisible = false; 1695 notifyAll(); 1696 1697 // there will usually be two of these sent, one as a timeout, and one 1698 // as a result of the callback, so remove any remaining messages from 1699 // the queue 1700 mHandler.removeMessages(KEYGUARD_DONE_DRAWING); 1701 } 1702 } 1703 Trace.endSection(); 1704 } 1705 playSounds(boolean locked)1706 private void playSounds(boolean locked) { 1707 playSound(locked ? mLockSoundId : mUnlockSoundId); 1708 } 1709 playSound(int soundId)1710 private void playSound(int soundId) { 1711 if (soundId == 0) return; 1712 final ContentResolver cr = mContext.getContentResolver(); 1713 if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) { 1714 1715 mLockSounds.stop(mLockSoundStreamId); 1716 // Init mAudioManager 1717 if (mAudioManager == null) { 1718 mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 1719 if (mAudioManager == null) return; 1720 mUiSoundsStreamType = mAudioManager.getUiSoundsStreamType(); 1721 } 1722 1723 mUiOffloadThread.submit(() -> { 1724 // If the stream is muted, don't play the sound 1725 if (mAudioManager.isStreamMute(mUiSoundsStreamType)) return; 1726 1727 int id = mLockSounds.play(soundId, 1728 mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/); 1729 synchronized (this) { 1730 mLockSoundStreamId = id; 1731 } 1732 }); 1733 1734 } 1735 } 1736 playTrustedSound()1737 private void playTrustedSound() { 1738 playSound(mTrustedSoundId); 1739 } 1740 updateActivityLockScreenState(boolean showing, boolean aodShowing)1741 private void updateActivityLockScreenState(boolean showing, boolean aodShowing) { 1742 mUiOffloadThread.submit(() -> { 1743 try { 1744 ActivityTaskManager.getService().setLockScreenShown(showing, aodShowing); 1745 } catch (RemoteException e) { 1746 } 1747 }); 1748 } 1749 1750 /** 1751 * Handle message sent by {@link #showLocked}. 1752 * @see #SHOW 1753 */ handleShow(Bundle options)1754 private void handleShow(Bundle options) { 1755 Trace.beginSection("KeyguardViewMediator#handleShow"); 1756 final int currentUser = KeyguardUpdateMonitor.getCurrentUser(); 1757 if (mLockPatternUtils.isSecure(currentUser)) { 1758 mLockPatternUtils.getDevicePolicyManager().reportKeyguardSecured(currentUser); 1759 } 1760 synchronized (KeyguardViewMediator.this) { 1761 if (!mSystemReady) { 1762 if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready."); 1763 return; 1764 } else { 1765 if (DEBUG) Log.d(TAG, "handleShow"); 1766 } 1767 1768 setShowingLocked(true, mAodShowing); 1769 mStatusBarKeyguardViewManager.show(options); 1770 mHiding = false; 1771 mWakeAndUnlocking = false; 1772 resetKeyguardDonePendingLocked(); 1773 mHideAnimationRun = false; 1774 adjustStatusBarLocked(); 1775 userActivity(); 1776 mUpdateMonitor.setKeyguardGoingAway(false /* away */); 1777 mShowKeyguardWakeLock.release(); 1778 } 1779 mKeyguardDisplayManager.show(); 1780 Trace.endSection(); 1781 } 1782 1783 private final Runnable mKeyguardGoingAwayRunnable = new Runnable() { 1784 @Override 1785 public void run() { 1786 Trace.beginSection("KeyguardViewMediator.mKeyGuardGoingAwayRunnable"); 1787 if (DEBUG) Log.d(TAG, "keyguardGoingAway"); 1788 mStatusBarKeyguardViewManager.keyguardGoingAway(); 1789 1790 int flags = 0; 1791 if (mStatusBarKeyguardViewManager.shouldDisableWindowAnimationsForUnlock() 1792 || (mWakeAndUnlocking && !mPulsing)) { 1793 flags |= WindowManagerPolicyConstants 1794 .KEYGUARD_GOING_AWAY_FLAG_NO_WINDOW_ANIMATIONS; 1795 } 1796 if (mStatusBarKeyguardViewManager.isGoingToNotificationShade() 1797 || (mWakeAndUnlocking && mPulsing)) { 1798 flags |= WindowManagerPolicyConstants.KEYGUARD_GOING_AWAY_FLAG_TO_SHADE; 1799 } 1800 if (mStatusBarKeyguardViewManager.isUnlockWithWallpaper()) { 1801 flags |= WindowManagerPolicyConstants.KEYGUARD_GOING_AWAY_FLAG_WITH_WALLPAPER; 1802 } 1803 1804 mUpdateMonitor.setKeyguardGoingAway(true /* goingAway */); 1805 1806 // Don't actually hide the Keyguard at the moment, wait for window 1807 // manager until it tells us it's safe to do so with 1808 // startKeyguardExitAnimation. 1809 // Posting to mUiOffloadThread to ensure that calls to ActivityTaskManager will be in 1810 // order. 1811 final int keyguardFlag = flags; 1812 mUiOffloadThread.submit(() -> { 1813 try { 1814 ActivityTaskManager.getService().keyguardGoingAway(keyguardFlag); 1815 } catch (RemoteException e) { 1816 Log.e(TAG, "Error while calling WindowManager", e); 1817 } 1818 }); 1819 Trace.endSection(); 1820 } 1821 }; 1822 1823 private final Runnable mHideAnimationFinishedRunnable = () -> { 1824 mHideAnimationRunning = false; 1825 tryKeyguardDone(); 1826 }; 1827 1828 /** 1829 * Handle message sent by {@link #hideLocked()} 1830 * @see #HIDE 1831 */ handleHide()1832 private void handleHide() { 1833 Trace.beginSection("KeyguardViewMediator#handleHide"); 1834 1835 // It's possible that the device was unlocked in a dream state. It's time to wake up. 1836 if (mAodShowing) { 1837 PowerManager pm = mContext.getSystemService(PowerManager.class); 1838 pm.wakeUp(SystemClock.uptimeMillis(), PowerManager.WAKE_REASON_GESTURE, 1839 "com.android.systemui:BOUNCER_DOZING"); 1840 } 1841 1842 synchronized (KeyguardViewMediator.this) { 1843 if (DEBUG) Log.d(TAG, "handleHide"); 1844 1845 if (mustNotUnlockCurrentUser()) { 1846 // In split system user mode, we never unlock system user. The end user has to 1847 // switch to another user. 1848 // TODO: We should stop it early by disabling the swipe up flow. Right now swipe up 1849 // still completes and makes the screen blank. 1850 if (DEBUG) Log.d(TAG, "Split system user, quit unlocking."); 1851 return; 1852 } 1853 mHiding = true; 1854 1855 if (mShowing && !mOccluded) { 1856 mKeyguardGoingAwayRunnable.run(); 1857 } else { 1858 handleStartKeyguardExitAnimation( 1859 SystemClock.uptimeMillis() + mHideAnimation.getStartOffset(), 1860 mHideAnimation.getDuration()); 1861 } 1862 } 1863 Trace.endSection(); 1864 } 1865 handleStartKeyguardExitAnimation(long startTime, long fadeoutDuration)1866 private void handleStartKeyguardExitAnimation(long startTime, long fadeoutDuration) { 1867 Trace.beginSection("KeyguardViewMediator#handleStartKeyguardExitAnimation"); 1868 if (DEBUG) Log.d(TAG, "handleStartKeyguardExitAnimation startTime=" + startTime 1869 + " fadeoutDuration=" + fadeoutDuration); 1870 synchronized (KeyguardViewMediator.this) { 1871 1872 if (!mHiding) { 1873 // Tell ActivityManager that we canceled the keyguardExitAnimation. 1874 setShowingLocked(mShowing, mAodShowing, true /* force */); 1875 return; 1876 } 1877 mHiding = false; 1878 1879 if (mWakeAndUnlocking && mDrawnCallback != null) { 1880 1881 // Hack level over 9000: To speed up wake-and-unlock sequence, force it to report 1882 // the next draw from here so we don't have to wait for window manager to signal 1883 // this to our ViewRootImpl. 1884 mStatusBarKeyguardViewManager.getViewRootImpl().setReportNextDraw(); 1885 notifyDrawn(mDrawnCallback); 1886 mDrawnCallback = null; 1887 } 1888 1889 // only play "unlock" noises if not on a call (since the incall UI 1890 // disables the keyguard) 1891 if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) { 1892 playSounds(false); 1893 } 1894 1895 mWakeAndUnlocking = false; 1896 setShowingLocked(false, mAodShowing); 1897 mDismissCallbackRegistry.notifyDismissSucceeded(); 1898 mStatusBarKeyguardViewManager.hide(startTime, fadeoutDuration); 1899 resetKeyguardDonePendingLocked(); 1900 mHideAnimationRun = false; 1901 adjustStatusBarLocked(); 1902 sendUserPresentBroadcast(); 1903 } 1904 Trace.endSection(); 1905 } 1906 adjustStatusBarLocked()1907 private void adjustStatusBarLocked() { 1908 adjustStatusBarLocked(false /* forceHideHomeRecentsButtons */); 1909 } 1910 adjustStatusBarLocked(boolean forceHideHomeRecentsButtons)1911 private void adjustStatusBarLocked(boolean forceHideHomeRecentsButtons) { 1912 if (mStatusBarManager == null) { 1913 mStatusBarManager = (StatusBarManager) 1914 mContext.getSystemService(Context.STATUS_BAR_SERVICE); 1915 } 1916 1917 if (mStatusBarManager == null) { 1918 Log.w(TAG, "Could not get status bar manager"); 1919 } else { 1920 // Disable aspects of the system/status/navigation bars that must not be re-enabled by 1921 // windows that appear on top, ever 1922 int flags = StatusBarManager.DISABLE_NONE; 1923 if (forceHideHomeRecentsButtons || isShowingAndNotOccluded()) { 1924 flags |= StatusBarManager.DISABLE_HOME | StatusBarManager.DISABLE_RECENT; 1925 } 1926 1927 if (DEBUG) { 1928 Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mOccluded=" + mOccluded 1929 + " isSecure=" + isSecure() + " force=" + forceHideHomeRecentsButtons 1930 + " --> flags=0x" + Integer.toHexString(flags)); 1931 } 1932 1933 mStatusBarManager.disable(flags); 1934 } 1935 } 1936 1937 /** 1938 * Handle message sent by {@link #resetStateLocked} 1939 * @see #RESET 1940 */ handleReset()1941 private void handleReset() { 1942 synchronized (KeyguardViewMediator.this) { 1943 if (DEBUG) Log.d(TAG, "handleReset"); 1944 mStatusBarKeyguardViewManager.reset(true /* hideBouncerWhenShowing */); 1945 } 1946 } 1947 1948 /** 1949 * Handle message sent by {@link #verifyUnlock} 1950 * @see #VERIFY_UNLOCK 1951 */ handleVerifyUnlock()1952 private void handleVerifyUnlock() { 1953 Trace.beginSection("KeyguardViewMediator#handleVerifyUnlock"); 1954 synchronized (KeyguardViewMediator.this) { 1955 if (DEBUG) Log.d(TAG, "handleVerifyUnlock"); 1956 setShowingLocked(true, mAodShowing); 1957 mStatusBarKeyguardViewManager.dismissAndCollapse(); 1958 } 1959 Trace.endSection(); 1960 } 1961 handleNotifyStartedGoingToSleep()1962 private void handleNotifyStartedGoingToSleep() { 1963 synchronized (KeyguardViewMediator.this) { 1964 if (DEBUG) Log.d(TAG, "handleNotifyStartedGoingToSleep"); 1965 mStatusBarKeyguardViewManager.onStartedGoingToSleep(); 1966 } 1967 } 1968 1969 /** 1970 * Handle message sent by {@link #notifyFinishedGoingToSleep()} 1971 * @see #NOTIFY_FINISHED_GOING_TO_SLEEP 1972 */ handleNotifyFinishedGoingToSleep()1973 private void handleNotifyFinishedGoingToSleep() { 1974 synchronized (KeyguardViewMediator.this) { 1975 if (DEBUG) Log.d(TAG, "handleNotifyFinishedGoingToSleep"); 1976 mStatusBarKeyguardViewManager.onFinishedGoingToSleep(); 1977 } 1978 } 1979 handleNotifyStartedWakingUp()1980 private void handleNotifyStartedWakingUp() { 1981 Trace.beginSection("KeyguardViewMediator#handleMotifyStartedWakingUp"); 1982 synchronized (KeyguardViewMediator.this) { 1983 if (DEBUG) Log.d(TAG, "handleNotifyWakingUp"); 1984 mStatusBarKeyguardViewManager.onStartedWakingUp(); 1985 } 1986 Trace.endSection(); 1987 } 1988 handleNotifyScreenTurningOn(IKeyguardDrawnCallback callback)1989 private void handleNotifyScreenTurningOn(IKeyguardDrawnCallback callback) { 1990 Trace.beginSection("KeyguardViewMediator#handleNotifyScreenTurningOn"); 1991 synchronized (KeyguardViewMediator.this) { 1992 if (DEBUG) Log.d(TAG, "handleNotifyScreenTurningOn"); 1993 mStatusBarKeyguardViewManager.onScreenTurningOn(); 1994 if (callback != null) { 1995 if (mWakeAndUnlocking) { 1996 mDrawnCallback = callback; 1997 } else { 1998 notifyDrawn(callback); 1999 } 2000 } 2001 } 2002 Trace.endSection(); 2003 } 2004 handleNotifyScreenTurnedOn()2005 private void handleNotifyScreenTurnedOn() { 2006 Trace.beginSection("KeyguardViewMediator#handleNotifyScreenTurnedOn"); 2007 if (LatencyTracker.isEnabled(mContext)) { 2008 LatencyTracker.getInstance(mContext).onActionEnd(LatencyTracker.ACTION_TURN_ON_SCREEN); 2009 } 2010 synchronized (this) { 2011 if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOn"); 2012 mStatusBarKeyguardViewManager.onScreenTurnedOn(); 2013 } 2014 Trace.endSection(); 2015 } 2016 handleNotifyScreenTurnedOff()2017 private void handleNotifyScreenTurnedOff() { 2018 synchronized (this) { 2019 if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOff"); 2020 mDrawnCallback = null; 2021 } 2022 } 2023 notifyDrawn(final IKeyguardDrawnCallback callback)2024 private void notifyDrawn(final IKeyguardDrawnCallback callback) { 2025 Trace.beginSection("KeyguardViewMediator#notifyDrawn"); 2026 try { 2027 callback.onDrawn(); 2028 } catch (RemoteException e) { 2029 Slog.w(TAG, "Exception calling onDrawn():", e); 2030 } 2031 Trace.endSection(); 2032 } 2033 resetKeyguardDonePendingLocked()2034 private void resetKeyguardDonePendingLocked() { 2035 mKeyguardDonePending = false; 2036 mHandler.removeMessages(KEYGUARD_DONE_PENDING_TIMEOUT); 2037 } 2038 2039 @Override onBootCompleted()2040 public void onBootCompleted() { 2041 mUpdateMonitor.dispatchBootCompleted(); 2042 synchronized (this) { 2043 mBootCompleted = true; 2044 if (mBootSendUserPresent) { 2045 sendUserPresentBroadcast(); 2046 } 2047 } 2048 } 2049 onWakeAndUnlocking()2050 public void onWakeAndUnlocking() { 2051 Trace.beginSection("KeyguardViewMediator#onWakeAndUnlocking"); 2052 mWakeAndUnlocking = true; 2053 keyguardDone(); 2054 Trace.endSection(); 2055 } 2056 registerStatusBar(StatusBar statusBar, ViewGroup container, NotificationPanelView panelView, BiometricUnlockController biometricUnlockController, ViewGroup lockIconContainer)2057 public StatusBarKeyguardViewManager registerStatusBar(StatusBar statusBar, 2058 ViewGroup container, NotificationPanelView panelView, 2059 BiometricUnlockController biometricUnlockController, ViewGroup lockIconContainer) { 2060 mStatusBarKeyguardViewManager.registerStatusBar(statusBar, container, panelView, 2061 biometricUnlockController, mDismissCallbackRegistry, lockIconContainer); 2062 return mStatusBarKeyguardViewManager; 2063 } 2064 startKeyguardExitAnimation(long startTime, long fadeoutDuration)2065 public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) { 2066 Trace.beginSection("KeyguardViewMediator#startKeyguardExitAnimation"); 2067 Message msg = mHandler.obtainMessage(START_KEYGUARD_EXIT_ANIM, 2068 new StartKeyguardExitAnimParams(startTime, fadeoutDuration)); 2069 mHandler.sendMessage(msg); 2070 Trace.endSection(); 2071 } 2072 onShortPowerPressedGoHome()2073 public void onShortPowerPressedGoHome() { 2074 // do nothing 2075 } 2076 getViewMediatorCallback()2077 public ViewMediatorCallback getViewMediatorCallback() { 2078 return mViewMediatorCallback; 2079 } 2080 getLockPatternUtils()2081 public LockPatternUtils getLockPatternUtils() { 2082 return mLockPatternUtils; 2083 } 2084 2085 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2086 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2087 pw.print(" mSystemReady: "); pw.println(mSystemReady); 2088 pw.print(" mBootCompleted: "); pw.println(mBootCompleted); 2089 pw.print(" mBootSendUserPresent: "); pw.println(mBootSendUserPresent); 2090 pw.print(" mExternallyEnabled: "); pw.println(mExternallyEnabled); 2091 pw.print(" mShuttingDown: "); pw.println(mShuttingDown); 2092 pw.print(" mNeedToReshowWhenReenabled: "); pw.println(mNeedToReshowWhenReenabled); 2093 pw.print(" mShowing: "); pw.println(mShowing); 2094 pw.print(" mInputRestricted: "); pw.println(mInputRestricted); 2095 pw.print(" mOccluded: "); pw.println(mOccluded); 2096 pw.print(" mDelayedShowingSequence: "); pw.println(mDelayedShowingSequence); 2097 pw.print(" mExitSecureCallback: "); pw.println(mExitSecureCallback); 2098 pw.print(" mDeviceInteractive: "); pw.println(mDeviceInteractive); 2099 pw.print(" mGoingToSleep: "); pw.println(mGoingToSleep); 2100 pw.print(" mHiding: "); pw.println(mHiding); 2101 pw.print(" mWaitingUntilKeyguardVisible: "); pw.println(mWaitingUntilKeyguardVisible); 2102 pw.print(" mKeyguardDonePending: "); pw.println(mKeyguardDonePending); 2103 pw.print(" mHideAnimationRun: "); pw.println(mHideAnimationRun); 2104 pw.print(" mPendingReset: "); pw.println(mPendingReset); 2105 pw.print(" mPendingLock: "); pw.println(mPendingLock); 2106 pw.print(" mWakeAndUnlocking: "); pw.println(mWakeAndUnlocking); 2107 pw.print(" mDrawnCallback: "); pw.println(mDrawnCallback); 2108 } 2109 2110 /** 2111 * @param aodShowing true when AOD - or ambient mode - is showing. 2112 */ setAodShowing(boolean aodShowing)2113 public void setAodShowing(boolean aodShowing) { 2114 setShowingLocked(mShowing, aodShowing); 2115 } 2116 2117 /** 2118 * @param pulsing true when device temporarily wakes up to display an incoming notification. 2119 */ setPulsing(boolean pulsing)2120 public void setPulsing(boolean pulsing) { 2121 mPulsing = pulsing; 2122 } 2123 2124 private static class StartKeyguardExitAnimParams { 2125 2126 long startTime; 2127 long fadeoutDuration; 2128 StartKeyguardExitAnimParams(long startTime, long fadeoutDuration)2129 private StartKeyguardExitAnimParams(long startTime, long fadeoutDuration) { 2130 this.startTime = startTime; 2131 this.fadeoutDuration = fadeoutDuration; 2132 } 2133 } 2134 setShowingLocked(boolean showing, boolean aodShowing)2135 private void setShowingLocked(boolean showing, boolean aodShowing) { 2136 setShowingLocked(showing, aodShowing, false /* forceCallbacks */); 2137 } 2138 setShowingLocked(boolean showing, boolean aodShowing, boolean forceCallbacks)2139 private void setShowingLocked(boolean showing, boolean aodShowing, boolean forceCallbacks) { 2140 final boolean notifyDefaultDisplayCallbacks = showing != mShowing 2141 || aodShowing != mAodShowing || forceCallbacks; 2142 if (notifyDefaultDisplayCallbacks) { 2143 mShowing = showing; 2144 mAodShowing = aodShowing; 2145 if (notifyDefaultDisplayCallbacks) { 2146 notifyDefaultDisplayCallbacks(showing); 2147 } 2148 updateActivityLockScreenState(showing, aodShowing); 2149 } 2150 } 2151 notifyDefaultDisplayCallbacks(boolean showing)2152 private void notifyDefaultDisplayCallbacks(boolean showing) { 2153 int size = mKeyguardStateCallbacks.size(); 2154 for (int i = size - 1; i >= 0; i--) { 2155 IKeyguardStateCallback callback = mKeyguardStateCallbacks.get(i); 2156 try { 2157 callback.onShowingStateChanged(showing); 2158 } catch (RemoteException e) { 2159 Slog.w(TAG, "Failed to call onShowingStateChanged", e); 2160 if (e instanceof DeadObjectException) { 2161 mKeyguardStateCallbacks.remove(callback); 2162 } 2163 } 2164 } 2165 updateInputRestrictedLocked(); 2166 mUiOffloadThread.submit(() -> { 2167 mTrustManager.reportKeyguardShowingChanged(); 2168 }); 2169 } 2170 notifyTrustedChangedLocked(boolean trusted)2171 private void notifyTrustedChangedLocked(boolean trusted) { 2172 int size = mKeyguardStateCallbacks.size(); 2173 for (int i = size - 1; i >= 0; i--) { 2174 try { 2175 mKeyguardStateCallbacks.get(i).onTrustedChanged(trusted); 2176 } catch (RemoteException e) { 2177 Slog.w(TAG, "Failed to call notifyTrustedChangedLocked", e); 2178 if (e instanceof DeadObjectException) { 2179 mKeyguardStateCallbacks.remove(i); 2180 } 2181 } 2182 } 2183 } 2184 notifyHasLockscreenWallpaperChanged(boolean hasLockscreenWallpaper)2185 private void notifyHasLockscreenWallpaperChanged(boolean hasLockscreenWallpaper) { 2186 int size = mKeyguardStateCallbacks.size(); 2187 for (int i = size - 1; i >= 0; i--) { 2188 try { 2189 mKeyguardStateCallbacks.get(i).onHasLockscreenWallpaperChanged( 2190 hasLockscreenWallpaper); 2191 } catch (RemoteException e) { 2192 Slog.w(TAG, "Failed to call onHasLockscreenWallpaperChanged", e); 2193 if (e instanceof DeadObjectException) { 2194 mKeyguardStateCallbacks.remove(i); 2195 } 2196 } 2197 } 2198 } 2199 addStateMonitorCallback(IKeyguardStateCallback callback)2200 public void addStateMonitorCallback(IKeyguardStateCallback callback) { 2201 synchronized (this) { 2202 mKeyguardStateCallbacks.add(callback); 2203 try { 2204 callback.onSimSecureStateChanged(mUpdateMonitor.isSimPinSecure()); 2205 callback.onShowingStateChanged(mShowing); 2206 callback.onInputRestrictedStateChanged(mInputRestricted); 2207 callback.onTrustedChanged(mUpdateMonitor.getUserHasTrust( 2208 KeyguardUpdateMonitor.getCurrentUser())); 2209 callback.onHasLockscreenWallpaperChanged(mUpdateMonitor.hasLockscreenWallpaper()); 2210 } catch (RemoteException e) { 2211 Slog.w(TAG, "Failed to call to IKeyguardStateCallback", e); 2212 } 2213 } 2214 } 2215 2216 private static class DismissMessage { 2217 private final CharSequence mMessage; 2218 private final IKeyguardDismissCallback mCallback; 2219 DismissMessage(IKeyguardDismissCallback callback, CharSequence message)2220 DismissMessage(IKeyguardDismissCallback callback, CharSequence message) { 2221 mCallback = callback; 2222 mMessage = message; 2223 } 2224 getCallback()2225 public IKeyguardDismissCallback getCallback() { 2226 return mCallback; 2227 } 2228 getMessage()2229 public CharSequence getMessage() { 2230 return mMessage; 2231 } 2232 } 2233 } 2234