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