KeyguardViewMediator.java revision 87d0e254cdc639347b73aa5f60ec8ab6c5327c7e
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 android.app.Activity; 20import android.app.ActivityManager; 21import android.app.ActivityManagerNative; 22import android.app.AlarmManager; 23import android.app.PendingIntent; 24import android.app.SearchManager; 25import android.app.StatusBarManager; 26import android.app.trust.TrustManager; 27import android.content.BroadcastReceiver; 28import android.content.ContentResolver; 29import android.content.Context; 30import android.content.Intent; 31import android.content.IntentFilter; 32import android.content.pm.UserInfo; 33import android.media.AudioManager; 34import android.media.SoundPool; 35import android.os.Bundle; 36import android.os.DeadObjectException; 37import android.os.Handler; 38import android.os.Looper; 39import android.os.Message; 40import android.os.PowerManager; 41import android.os.RemoteException; 42import android.os.SystemClock; 43import android.os.SystemProperties; 44import android.os.UserHandle; 45import android.os.UserManager; 46import android.provider.Settings; 47import android.telephony.SubscriptionManager; 48import android.telephony.TelephonyManager; 49import android.util.EventLog; 50import android.util.Log; 51import android.util.Slog; 52import android.view.IWindowManager; 53import android.view.ViewGroup; 54import android.view.WindowManagerGlobal; 55import android.view.WindowManagerPolicy; 56import android.view.animation.Animation; 57import android.view.animation.AnimationUtils; 58 59import com.android.internal.policy.IKeyguardDrawnCallback; 60import com.android.internal.policy.IKeyguardExitCallback; 61import com.android.internal.policy.IKeyguardStateCallback; 62import com.android.internal.telephony.IccCardConstants; 63import com.android.internal.widget.LockPatternUtils; 64import com.android.keyguard.KeyguardConstants; 65import com.android.keyguard.KeyguardDisplayManager; 66import com.android.keyguard.KeyguardSecurityView; 67import com.android.keyguard.KeyguardUpdateMonitor; 68import com.android.keyguard.KeyguardUpdateMonitorCallback; 69import com.android.keyguard.ViewMediatorCallback; 70import com.android.systemui.SystemUI; 71import com.android.systemui.statusbar.phone.PhoneStatusBar; 72import com.android.systemui.statusbar.phone.ScrimController; 73import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager; 74import com.android.systemui.statusbar.phone.StatusBarWindowManager; 75 76import java.util.ArrayList; 77import java.util.List; 78 79import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT; 80 81/** 82 * Mediates requests related to the keyguard. This includes queries about the 83 * state of the keyguard, power management events that effect whether the keyguard 84 * should be shown or reset, callbacks to the phone window manager to notify 85 * it of when the keyguard is showing, and events from the keyguard view itself 86 * stating that the keyguard was succesfully unlocked. 87 * 88 * Note that the keyguard view is shown when the screen is off (as appropriate) 89 * so that once the screen comes on, it will be ready immediately. 90 * 91 * Example queries about the keyguard: 92 * - is {movement, key} one that should wake the keygaurd? 93 * - is the keyguard showing? 94 * - are input events restricted due to the state of the keyguard? 95 * 96 * Callbacks to the phone window manager: 97 * - the keyguard is showing 98 * 99 * Example external events that translate to keyguard view changes: 100 * - screen turned off -> reset the keyguard, and show it so it will be ready 101 * next time the screen turns on 102 * - keyboard is slid open -> if the keyguard is not secure, hide it 103 * 104 * Events from the keyguard view: 105 * - user succesfully unlocked keyguard -> hide keyguard view, and no longer 106 * restrict input events. 107 * 108 * Note: in addition to normal power managment events that effect the state of 109 * whether the keyguard should be showing, external apps and services may request 110 * that the keyguard be disabled via {@link #setKeyguardEnabled(boolean)}. When 111 * false, this will override all other conditions for turning on the keyguard. 112 * 113 * Threading and synchronization: 114 * This class is created by the initialization routine of the {@link android.view.WindowManagerPolicy}, 115 * and runs on its thread. The keyguard UI is created from that thread in the 116 * constructor of this class. The apis may be called from other threads, including the 117 * {@link com.android.server.input.InputManagerService}'s and {@link android.view.WindowManager}'s. 118 * Therefore, methods on this class are synchronized, and any action that is pointed 119 * directly to the keyguard UI is posted to a {@link android.os.Handler} to ensure it is taken on the UI 120 * thread of the keyguard. 121 */ 122public class KeyguardViewMediator extends SystemUI { 123 private static final int KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000; 124 private static final long KEYGUARD_DONE_PENDING_TIMEOUT_MS = 3000; 125 126 private static final boolean DEBUG = KeyguardConstants.DEBUG; 127 private static final boolean DEBUG_SIM_STATES = KeyguardConstants.DEBUG_SIM_STATES; 128 private final static boolean DBG_WAKE = false; 129 130 private final static String TAG = "KeyguardViewMediator"; 131 132 private static final String DELAYED_KEYGUARD_ACTION = 133 "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_KEYGUARD"; 134 135 // used for handler messages 136 private static final int SHOW = 2; 137 private static final int HIDE = 3; 138 private static final int RESET = 4; 139 private static final int VERIFY_UNLOCK = 5; 140 private static final int NOTIFY_FINISHED_GOING_TO_SLEEP = 6; 141 private static final int NOTIFY_SCREEN_TURNING_ON = 7; 142 private static final int KEYGUARD_DONE = 9; 143 private static final int KEYGUARD_DONE_DRAWING = 10; 144 private static final int KEYGUARD_DONE_AUTHENTICATING = 11; 145 private static final int SET_OCCLUDED = 12; 146 private static final int KEYGUARD_TIMEOUT = 13; 147 private static final int DISMISS = 17; 148 private static final int START_KEYGUARD_EXIT_ANIM = 18; 149 private static final int ON_ACTIVITY_DRAWN = 19; 150 private static final int KEYGUARD_DONE_PENDING_TIMEOUT = 20; 151 private static final int NOTIFY_STARTED_WAKING_UP = 21; 152 private static final int NOTIFY_SCREEN_TURNED_ON = 22; 153 private static final int NOTIFY_SCREEN_TURNED_OFF = 23; 154 155 /** 156 * The default amount of time we stay awake (used for all key input) 157 */ 158 public static final int AWAKE_INTERVAL_DEFAULT_MS = 10000; 159 160 /** 161 * How long to wait after the screen turns off due to timeout before 162 * turning on the keyguard (i.e, the user has this much time to turn 163 * the screen back on without having to face the keyguard). 164 */ 165 private static final int KEYGUARD_LOCK_AFTER_DELAY_DEFAULT = 5000; 166 167 /** 168 * How long we'll wait for the {@link ViewMediatorCallback#keyguardDoneDrawing()} 169 * callback before unblocking a call to {@link #setKeyguardEnabled(boolean)} 170 * that is reenabling the keyguard. 171 */ 172 private static final int KEYGUARD_DONE_DRAWING_TIMEOUT_MS = 2000; 173 174 /** 175 * Secure setting whether analytics are collected on the keyguard. 176 */ 177 private static final String KEYGUARD_ANALYTICS_SETTING = "keyguard_analytics"; 178 179 /** 180 * How much faster we collapse the lockscreen when authenticating with fingerprint. 181 */ 182 private static final float FINGERPRINT_COLLAPSE_SPEEDUP_FACTOR = 1.3f; 183 184 /** The stream type that the lock sounds are tied to. */ 185 private int mUiSoundsStreamType; 186 187 private AlarmManager mAlarmManager; 188 private AudioManager mAudioManager; 189 private StatusBarManager mStatusBarManager; 190 private boolean mSwitchingUser; 191 192 private boolean mSystemReady; 193 private boolean mBootCompleted; 194 private boolean mBootSendUserPresent; 195 196 /** High level access to the power manager for WakeLocks */ 197 private PowerManager mPM; 198 199 /** High level access to the window manager for dismissing keyguard animation */ 200 private IWindowManager mWM; 201 202 203 /** TrustManager for letting it know when we change visibility */ 204 private TrustManager mTrustManager; 205 206 /** SearchManager for determining whether or not search assistant is available */ 207 private SearchManager mSearchManager; 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 * If the user has disabled the keyguard, then requests to exit, this is 249 * how we'll ultimately let them know whether it was successful. We use this 250 * var being non-null as an indicator that there is an in progress request. 251 */ 252 private IKeyguardExitCallback mExitSecureCallback; 253 254 // the properties of the keyguard 255 256 private KeyguardUpdateMonitor mUpdateMonitor; 257 258 private boolean mDeviceInteractive; 259 private boolean mGoingToSleep; 260 261 // last known state of the cellular connection 262 private String mPhoneState = TelephonyManager.EXTRA_STATE_IDLE; 263 264 /** 265 * Whether a hide is pending an we are just waiting for #startKeyguardExitAnimation to be 266 * called. 267 * */ 268 private boolean mHiding; 269 270 /** 271 * we send this intent when the keyguard is dismissed. 272 */ 273 private static final Intent USER_PRESENT_INTENT = new Intent(Intent.ACTION_USER_PRESENT) 274 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING 275 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 276 277 /** 278 * {@link #setKeyguardEnabled} waits on this condition when it reenables 279 * the keyguard. 280 */ 281 private boolean mWaitingUntilKeyguardVisible = false; 282 private LockPatternUtils mLockPatternUtils; 283 private boolean mKeyguardDonePending = false; 284 private boolean mHideAnimationRun = false; 285 286 private SoundPool mLockSounds; 287 private int mLockSoundId; 288 private int mUnlockSoundId; 289 private int mTrustedSoundId; 290 private int mLockSoundStreamId; 291 292 /** 293 * The animation used for hiding keyguard. This is used to fetch the animation timings if 294 * WindowManager is not providing us with them. 295 */ 296 private Animation mHideAnimation; 297 298 /** 299 * The volume applied to the lock/unlock sounds. 300 */ 301 private float mLockSoundVolume; 302 303 /** 304 * For managing external displays 305 */ 306 private KeyguardDisplayManager mKeyguardDisplayManager; 307 308 private final ArrayList<IKeyguardStateCallback> mKeyguardStateCallbacks = new ArrayList<>(); 309 310 /** 311 * When starting going to sleep, we figured out that we need to reset Keyguard state and this 312 * should be committed when finished going to sleep. 313 */ 314 private boolean mPendingReset; 315 316 /** 317 * When starting going to sleep, we figured out that we need to lock Keyguard and this should be 318 * committed when finished going to sleep. 319 */ 320 private boolean mPendingLock; 321 322 private boolean mWakeAndUnlocking; 323 private IKeyguardDrawnCallback mDrawnCallback; 324 325 KeyguardUpdateMonitorCallback mUpdateCallback = new KeyguardUpdateMonitorCallback() { 326 327 @Override 328 public void onUserSwitching(int userId) { 329 // Note that the mLockPatternUtils user has already been updated from setCurrentUser. 330 // We need to force a reset of the views, since lockNow (called by 331 // ActivityManagerService) will not reconstruct the keyguard if it is already showing. 332 synchronized (KeyguardViewMediator.this) { 333 mSwitchingUser = true; 334 resetKeyguardDonePendingLocked(); 335 resetStateLocked(); 336 adjustStatusBarLocked(); 337 } 338 } 339 340 @Override 341 public void onUserSwitchComplete(int userId) { 342 mSwitchingUser = false; 343 if (userId != UserHandle.USER_SYSTEM) { 344 UserInfo info = UserManager.get(mContext).getUserInfo(userId); 345 if (info != null && info.isGuest()) { 346 // If we just switched to a guest, try to dismiss keyguard. 347 dismiss(); 348 } 349 } 350 } 351 352 @Override 353 public void onUserInfoChanged(int userId) { 354 } 355 356 @Override 357 public void onPhoneStateChanged(int phoneState) { 358 synchronized (KeyguardViewMediator.this) { 359 if (TelephonyManager.CALL_STATE_IDLE == phoneState // call ending 360 && !mDeviceInteractive // screen off 361 && mExternallyEnabled) { // not disabled by any app 362 363 // note: this is a way to gracefully reenable the keyguard when the call 364 // ends and the screen is off without always reenabling the keyguard 365 // each time the screen turns off while in call (and having an occasional ugly 366 // flicker while turning back on the screen and disabling the keyguard again). 367 if (DEBUG) Log.d(TAG, "screen is off and call ended, let's make sure the " 368 + "keyguard is showing"); 369 doKeyguardLocked(null); 370 } 371 } 372 } 373 374 @Override 375 public void onClockVisibilityChanged() { 376 adjustStatusBarLocked(); 377 } 378 379 @Override 380 public void onDeviceProvisioned() { 381 sendUserPresentBroadcast(); 382 } 383 384 @Override 385 public void onSimStateChanged(int subId, int slotId, IccCardConstants.State simState) { 386 387 if (DEBUG_SIM_STATES) { 388 Log.d(TAG, "onSimStateChanged(subId=" + subId + ", slotId=" + slotId 389 + ",state=" + simState + ")"); 390 } 391 392 int size = mKeyguardStateCallbacks.size(); 393 boolean simPinSecure = mUpdateMonitor.isSimPinSecure(); 394 for (int i = size - 1; i >= 0; i--) { 395 try { 396 mKeyguardStateCallbacks.get(i).onSimSecureStateChanged(simPinSecure); 397 } catch (RemoteException e) { 398 Slog.w(TAG, "Failed to call onSimSecureStateChanged", e); 399 if (e instanceof DeadObjectException) { 400 mKeyguardStateCallbacks.remove(i); 401 } 402 } 403 } 404 405 switch (simState) { 406 case NOT_READY: 407 case ABSENT: 408 // only force lock screen in case of missing sim if user hasn't 409 // gone through setup wizard 410 synchronized (this) { 411 if (shouldWaitForProvisioning()) { 412 if (!mShowing) { 413 if (DEBUG_SIM_STATES) Log.d(TAG, "ICC_ABSENT isn't showing," 414 + " we need to show the keyguard since the " 415 + "device isn't provisioned yet."); 416 doKeyguardLocked(null); 417 } else { 418 resetStateLocked(); 419 } 420 } 421 } 422 break; 423 case PIN_REQUIRED: 424 case PUK_REQUIRED: 425 synchronized (this) { 426 if (!mShowing) { 427 if (DEBUG_SIM_STATES) Log.d(TAG, 428 "INTENT_VALUE_ICC_LOCKED and keygaurd isn't " 429 + "showing; need to show keyguard so user can enter sim pin"); 430 doKeyguardLocked(null); 431 } else { 432 resetStateLocked(); 433 } 434 } 435 break; 436 case PERM_DISABLED: 437 synchronized (this) { 438 if (!mShowing) { 439 if (DEBUG_SIM_STATES) Log.d(TAG, "PERM_DISABLED and " 440 + "keygaurd isn't showing."); 441 doKeyguardLocked(null); 442 } else { 443 if (DEBUG_SIM_STATES) Log.d(TAG, "PERM_DISABLED, resetStateLocked to" 444 + "show permanently disabled message in lockscreen."); 445 resetStateLocked(); 446 } 447 } 448 break; 449 case READY: 450 synchronized (this) { 451 if (mShowing) { 452 resetStateLocked(); 453 } 454 } 455 break; 456 default: 457 if (DEBUG_SIM_STATES) Log.v(TAG, "Ignoring state: " + simState); 458 break; 459 } 460 } 461 462 @Override 463 public void onFingerprintAuthenticated(int userId, boolean wakeAndUnlocking) { 464 boolean unlockingWithFingerprintAllowed = 465 mUpdateMonitor.isUnlockingWithFingerprintAllowed(); 466 if (mStatusBarKeyguardViewManager.isBouncerShowing()) { 467 if (unlockingWithFingerprintAllowed) { 468 mStatusBarKeyguardViewManager.notifyKeyguardAuthenticated(); 469 } 470 } else { 471 if (wakeAndUnlocking && mShowing && unlockingWithFingerprintAllowed) { 472 mWakeAndUnlocking = true; 473 mStatusBarKeyguardViewManager.setWakeAndUnlocking(); 474 keyguardDone(true, true); 475 } else if (mShowing && mDeviceInteractive) { 476 if (wakeAndUnlocking) { 477 mStatusBarKeyguardViewManager.notifyDeviceWakeUpRequested(); 478 } 479 mStatusBarKeyguardViewManager.animateCollapsePanels( 480 FINGERPRINT_COLLAPSE_SPEEDUP_FACTOR); 481 } 482 } 483 }; 484 485 }; 486 487 ViewMediatorCallback mViewMediatorCallback = new ViewMediatorCallback() { 488 489 public void userActivity() { 490 KeyguardViewMediator.this.userActivity(); 491 } 492 493 public void keyguardDone(boolean authenticated) { 494 if (!mKeyguardDonePending) { 495 KeyguardViewMediator.this.keyguardDone(authenticated, true); 496 } 497 } 498 499 public void keyguardDoneDrawing() { 500 mHandler.sendEmptyMessage(KEYGUARD_DONE_DRAWING); 501 } 502 503 @Override 504 public void setNeedsInput(boolean needsInput) { 505 mStatusBarKeyguardViewManager.setNeedsInput(needsInput); 506 } 507 508 @Override 509 public void keyguardDonePending() { 510 mKeyguardDonePending = true; 511 mHideAnimationRun = true; 512 mStatusBarKeyguardViewManager.startPreHideAnimation(null /* finishRunnable */); 513 mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_PENDING_TIMEOUT, 514 KEYGUARD_DONE_PENDING_TIMEOUT_MS); 515 } 516 517 @Override 518 public void keyguardGone() { 519 mKeyguardDisplayManager.hide(); 520 } 521 522 @Override 523 public void readyForKeyguardDone() { 524 if (mKeyguardDonePending) { 525 // Somebody has called keyguardDonePending before, which means that we are 526 // authenticated 527 KeyguardViewMediator.this.keyguardDone(true /* authenticated */, true /* wakeUp */); 528 } 529 } 530 531 @Override 532 public void resetKeyguard() { 533 resetStateLocked(); 534 } 535 536 @Override 537 public void playTrustedSound() { 538 KeyguardViewMediator.this.playTrustedSound(); 539 } 540 541 @Override 542 public boolean isInputRestricted() { 543 return KeyguardViewMediator.this.isInputRestricted(); 544 } 545 546 @Override 547 public boolean isScreenOn() { 548 return mDeviceInteractive; 549 } 550 551 @Override 552 public int getBouncerPromptReason() { 553 int currentUser = ActivityManager.getCurrentUser(); 554 if ((mUpdateMonitor.getUserTrustIsManaged(currentUser) 555 || mUpdateMonitor.isUnlockWithFingerPrintPossible(currentUser)) 556 && !mTrustManager.hasUserAuthenticatedSinceBoot(currentUser)) { 557 return KeyguardSecurityView.PROMPT_REASON_RESTART; 558 } 559 return KeyguardSecurityView.PROMPT_REASON_NONE; 560 } 561 }; 562 563 public void userActivity() { 564 mPM.userActivity(SystemClock.uptimeMillis(), false); 565 } 566 567 private void setupLocked() { 568 mPM = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); 569 mWM = WindowManagerGlobal.getWindowManagerService(); 570 mTrustManager = (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE); 571 572 mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "show keyguard"); 573 mShowKeyguardWakeLock.setReferenceCounted(false); 574 575 mContext.registerReceiver(mBroadcastReceiver, new IntentFilter(DELAYED_KEYGUARD_ACTION)); 576 577 mKeyguardDisplayManager = new KeyguardDisplayManager(mContext); 578 579 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); 580 581 mUpdateMonitor = KeyguardUpdateMonitor.getInstance(mContext); 582 583 mLockPatternUtils = new LockPatternUtils(mContext); 584 KeyguardUpdateMonitor.setCurrentUser(ActivityManager.getCurrentUser()); 585 586 // Assume keyguard is showing (unless it's disabled) until we know for sure... 587 setShowingLocked(!shouldWaitForProvisioning() && !mLockPatternUtils.isLockScreenDisabled( 588 KeyguardUpdateMonitor.getCurrentUser())); 589 updateInputRestrictedLocked(); 590 mTrustManager.reportKeyguardShowingChanged(); 591 592 mStatusBarKeyguardViewManager = new StatusBarKeyguardViewManager(mContext, 593 mViewMediatorCallback, mLockPatternUtils); 594 final ContentResolver cr = mContext.getContentResolver(); 595 596 mDeviceInteractive = mPM.isInteractive(); 597 598 mLockSounds = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0); 599 String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND); 600 if (soundPath != null) { 601 mLockSoundId = mLockSounds.load(soundPath, 1); 602 } 603 if (soundPath == null || mLockSoundId == 0) { 604 Log.w(TAG, "failed to load lock sound from " + soundPath); 605 } 606 soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND); 607 if (soundPath != null) { 608 mUnlockSoundId = mLockSounds.load(soundPath, 1); 609 } 610 if (soundPath == null || mUnlockSoundId == 0) { 611 Log.w(TAG, "failed to load unlock sound from " + soundPath); 612 } 613 soundPath = Settings.Global.getString(cr, Settings.Global.TRUSTED_SOUND); 614 if (soundPath != null) { 615 mTrustedSoundId = mLockSounds.load(soundPath, 1); 616 } 617 if (soundPath == null || mTrustedSoundId == 0) { 618 Log.w(TAG, "failed to load trusted sound from " + soundPath); 619 } 620 621 int lockSoundDefaultAttenuation = mContext.getResources().getInteger( 622 com.android.internal.R.integer.config_lockSoundVolumeDb); 623 mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20); 624 625 mHideAnimation = AnimationUtils.loadAnimation(mContext, 626 com.android.internal.R.anim.lock_screen_behind_enter); 627 } 628 629 @Override 630 public void start() { 631 synchronized (this) { 632 setupLocked(); 633 } 634 putComponent(KeyguardViewMediator.class, this); 635 } 636 637 /** 638 * Let us know that the system is ready after startup. 639 */ 640 public void onSystemReady() { 641 mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE); 642 synchronized (this) { 643 if (DEBUG) Log.d(TAG, "onSystemReady"); 644 mSystemReady = true; 645 doKeyguardLocked(null); 646 mUpdateMonitor.registerCallback(mUpdateCallback); 647 } 648 // Most services aren't available until the system reaches the ready state, so we 649 // send it here when the device first boots. 650 maybeSendUserPresentBroadcast(); 651 } 652 653 /** 654 * Called to let us know the screen was turned off. 655 * @param why either {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_USER} or 656 * {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT}. 657 */ 658 public void onStartedGoingToSleep(int why) { 659 if (DEBUG) Log.d(TAG, "onStartedGoingToSleep(" + why + ")"); 660 synchronized (this) { 661 mDeviceInteractive = false; 662 mGoingToSleep = true; 663 664 // Lock immediately based on setting if secure (user has a pin/pattern/password). 665 // This also "locks" the device when not secure to provide easy access to the 666 // camera while preventing unwanted input. 667 int currentUser = KeyguardUpdateMonitor.getCurrentUser(); 668 final boolean lockImmediately = 669 mLockPatternUtils.getPowerButtonInstantlyLocks(currentUser) 670 || !mLockPatternUtils.isSecure(currentUser); 671 672 if (mExitSecureCallback != null) { 673 if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled"); 674 try { 675 mExitSecureCallback.onKeyguardExitResult(false); 676 } catch (RemoteException e) { 677 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); 678 } 679 mExitSecureCallback = null; 680 if (!mExternallyEnabled) { 681 hideLocked(); 682 } 683 } else if (mShowing) { 684 mPendingReset = true; 685 } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT 686 || (why == WindowManagerPolicy.OFF_BECAUSE_OF_USER && !lockImmediately)) { 687 doKeyguardLaterLocked(); 688 } else if (!mLockPatternUtils.isLockScreenDisabled(currentUser)) { 689 mPendingLock = true; 690 } 691 692 if (mPendingLock) { 693 playSounds(true); 694 } 695 } 696 } 697 698 public void onFinishedGoingToSleep(int why) { 699 if (DEBUG) Log.d(TAG, "onFinishedGoingToSleep(" + why + ")"); 700 synchronized (this) { 701 mDeviceInteractive = false; 702 mGoingToSleep = false; 703 704 resetKeyguardDonePendingLocked(); 705 mHideAnimationRun = false; 706 707 notifyFinishedGoingToSleep(); 708 709 if (mPendingReset) { 710 resetStateLocked(); 711 mPendingReset = false; 712 } 713 if (mPendingLock) { 714 doKeyguardLocked(null); 715 mPendingLock = false; 716 } 717 } 718 KeyguardUpdateMonitor.getInstance(mContext).dispatchFinishedGoingToSleep(why); 719 } 720 721 private void doKeyguardLaterLocked() { 722 // if the screen turned off because of timeout or the user hit the power button 723 // and we don't need to lock immediately, set an alarm 724 // to enable it a little bit later (i.e, give the user a chance 725 // to turn the screen back on within a certain window without 726 // having to unlock the screen) 727 final ContentResolver cr = mContext.getContentResolver(); 728 729 // From DisplaySettings 730 long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT, 731 KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT); 732 733 // From SecuritySettings 734 final long lockAfterTimeout = Settings.Secure.getInt(cr, 735 Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 736 KEYGUARD_LOCK_AFTER_DELAY_DEFAULT); 737 738 // From DevicePolicyAdmin 739 final long policyTimeout = mLockPatternUtils.getDevicePolicyManager() 740 .getMaximumTimeToLock(null, KeyguardUpdateMonitor.getCurrentUser()); 741 742 long timeout; 743 if (policyTimeout > 0) { 744 // policy in effect. Make sure we don't go beyond policy limit. 745 displayTimeout = Math.max(displayTimeout, 0); // ignore negative values 746 timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout); 747 } else { 748 timeout = lockAfterTimeout; 749 } 750 751 if (timeout <= 0) { 752 // Lock now 753 doKeyguardLocked(null); 754 } else { 755 // Lock in the future 756 long when = SystemClock.elapsedRealtime() + timeout; 757 Intent intent = new Intent(DELAYED_KEYGUARD_ACTION); 758 intent.putExtra("seq", mDelayedShowingSequence); 759 PendingIntent sender = PendingIntent.getBroadcast(mContext, 760 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); 761 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender); 762 if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = " 763 + mDelayedShowingSequence); 764 } 765 } 766 767 private void cancelDoKeyguardLaterLocked() { 768 mDelayedShowingSequence++; 769 } 770 771 /** 772 * Let's us know when the device is waking up. 773 */ 774 public void onStartedWakingUp() { 775 776 // TODO: Rename all screen off/on references to interactive/sleeping 777 synchronized (this) { 778 mDeviceInteractive = true; 779 cancelDoKeyguardLaterLocked(); 780 if (DEBUG) Log.d(TAG, "onStartedWakingUp, seq = " + mDelayedShowingSequence); 781 notifyStartedWakingUp(); 782 } 783 KeyguardUpdateMonitor.getInstance(mContext).dispatchStartedWakingUp(); 784 maybeSendUserPresentBroadcast(); 785 } 786 787 public void onScreenTurningOn(IKeyguardDrawnCallback callback) { 788 notifyScreenOn(callback); 789 } 790 791 public void onScreenTurnedOn() { 792 notifyScreenTurnedOn(); 793 mUpdateMonitor.dispatchScreenTurnedOn(); 794 } 795 796 public void onScreenTurnedOff() { 797 notifyScreenTurnedOff(); 798 mUpdateMonitor.dispatchScreenTurnedOff(); 799 } 800 801 private void maybeSendUserPresentBroadcast() { 802 if (mSystemReady && mLockPatternUtils.isLockScreenDisabled( 803 KeyguardUpdateMonitor.getCurrentUser())) { 804 // Lock screen is disabled because the user has set the preference to "None". 805 // In this case, send out ACTION_USER_PRESENT here instead of in 806 // handleKeyguardDone() 807 sendUserPresentBroadcast(); 808 } 809 } 810 811 /** 812 * A dream started. We should lock after the usual screen-off lock timeout but only 813 * if there is a secure lock pattern. 814 */ 815 public void onDreamingStarted() { 816 synchronized (this) { 817 if (mDeviceInteractive 818 && mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())) { 819 doKeyguardLaterLocked(); 820 } 821 } 822 } 823 824 /** 825 * A dream stopped. 826 */ 827 public void onDreamingStopped() { 828 synchronized (this) { 829 if (mDeviceInteractive) { 830 cancelDoKeyguardLaterLocked(); 831 } 832 } 833 } 834 835 /** 836 * Same semantics as {@link android.view.WindowManagerPolicy#enableKeyguard}; provide 837 * a way for external stuff to override normal keyguard behavior. For instance 838 * the phone app disables the keyguard when it receives incoming calls. 839 */ 840 public void setKeyguardEnabled(boolean enabled) { 841 synchronized (this) { 842 if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")"); 843 844 if (isSecure()) { 845 Log.d(TAG, "current mode is SecurityMode, ignore hide keyguard"); 846 return; 847 } 848 849 mExternallyEnabled = enabled; 850 851 if (!enabled && mShowing) { 852 if (mExitSecureCallback != null) { 853 if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring"); 854 // we're in the process of handling a request to verify the user 855 // can get past the keyguard. ignore extraneous requests to disable / reenable 856 return; 857 } 858 859 // hiding keyguard that is showing, remember to reshow later 860 if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, " 861 + "disabling status bar expansion"); 862 mNeedToReshowWhenReenabled = true; 863 updateInputRestrictedLocked(); 864 hideLocked(); 865 } else if (enabled && mNeedToReshowWhenReenabled) { 866 // reenabled after previously hidden, reshow 867 if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling " 868 + "status bar expansion"); 869 mNeedToReshowWhenReenabled = false; 870 updateInputRestrictedLocked(); 871 872 if (mExitSecureCallback != null) { 873 if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting"); 874 try { 875 mExitSecureCallback.onKeyguardExitResult(false); 876 } catch (RemoteException e) { 877 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); 878 } 879 mExitSecureCallback = null; 880 resetStateLocked(); 881 } else { 882 showLocked(null); 883 884 // block until we know the keygaurd is done drawing (and post a message 885 // to unblock us after a timeout so we don't risk blocking too long 886 // and causing an ANR). 887 mWaitingUntilKeyguardVisible = true; 888 mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS); 889 if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false"); 890 while (mWaitingUntilKeyguardVisible) { 891 try { 892 wait(); 893 } catch (InterruptedException e) { 894 Thread.currentThread().interrupt(); 895 } 896 } 897 if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible"); 898 } 899 } 900 } 901 } 902 903 /** 904 * @see android.app.KeyguardManager#exitKeyguardSecurely 905 */ 906 public void verifyUnlock(IKeyguardExitCallback callback) { 907 synchronized (this) { 908 if (DEBUG) Log.d(TAG, "verifyUnlock"); 909 if (shouldWaitForProvisioning()) { 910 // don't allow this api when the device isn't provisioned 911 if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned"); 912 try { 913 callback.onKeyguardExitResult(false); 914 } catch (RemoteException e) { 915 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); 916 } 917 } else if (mExternallyEnabled) { 918 // this only applies when the user has externally disabled the 919 // keyguard. this is unexpected and means the user is not 920 // using the api properly. 921 Log.w(TAG, "verifyUnlock called when not externally disabled"); 922 try { 923 callback.onKeyguardExitResult(false); 924 } catch (RemoteException e) { 925 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); 926 } 927 } else if (mExitSecureCallback != null) { 928 // already in progress with someone else 929 try { 930 callback.onKeyguardExitResult(false); 931 } catch (RemoteException e) { 932 Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e); 933 } 934 } else { 935 mExitSecureCallback = callback; 936 verifyUnlockLocked(); 937 } 938 } 939 } 940 941 /** 942 * Is the keyguard currently showing and not being force hidden? 943 */ 944 public boolean isShowingAndNotOccluded() { 945 return mShowing && !mOccluded; 946 } 947 948 /** 949 * Notify us when the keyguard is occluded by another window 950 */ 951 public void setOccluded(boolean isOccluded) { 952 if (DEBUG) Log.d(TAG, "setOccluded " + isOccluded); 953 mHandler.removeMessages(SET_OCCLUDED); 954 Message msg = mHandler.obtainMessage(SET_OCCLUDED, (isOccluded ? 1 : 0), 0); 955 mHandler.sendMessage(msg); 956 } 957 958 /** 959 * Handles SET_OCCLUDED message sent by setOccluded() 960 */ 961 private void handleSetOccluded(boolean isOccluded) { 962 synchronized (KeyguardViewMediator.this) { 963 if (mHiding && isOccluded) { 964 // We're in the process of going away but WindowManager wants to show a 965 // SHOW_WHEN_LOCKED activity instead. 966 startKeyguardExitAnimation(0, 0); 967 } 968 969 if (mOccluded != isOccluded) { 970 mOccluded = isOccluded; 971 mStatusBarKeyguardViewManager.setOccluded(isOccluded); 972 updateActivityLockScreenState(); 973 adjustStatusBarLocked(); 974 } 975 } 976 } 977 978 /** 979 * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout. 980 * This must be safe to call from any thread and with any window manager locks held. 981 */ 982 public void doKeyguardTimeout(Bundle options) { 983 mHandler.removeMessages(KEYGUARD_TIMEOUT); 984 Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options); 985 mHandler.sendMessage(msg); 986 } 987 988 /** 989 * Given the state of the keyguard, is the input restricted? 990 * Input is restricted when the keyguard is showing, or when the keyguard 991 * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet. 992 */ 993 public boolean isInputRestricted() { 994 return mShowing || mNeedToReshowWhenReenabled; 995 } 996 997 private void updateInputRestricted() { 998 synchronized (this) { 999 updateInputRestrictedLocked(); 1000 } 1001 } 1002 private void updateInputRestrictedLocked() { 1003 boolean inputRestricted = isInputRestricted(); 1004 if (mInputRestricted != inputRestricted) { 1005 mInputRestricted = inputRestricted; 1006 int size = mKeyguardStateCallbacks.size(); 1007 for (int i = size - 1; i >= 0; i--) { 1008 try { 1009 mKeyguardStateCallbacks.get(i).onInputRestrictedStateChanged(inputRestricted); 1010 } catch (RemoteException e) { 1011 Slog.w(TAG, "Failed to call onDeviceProvisioned", e); 1012 if (e instanceof DeadObjectException) { 1013 mKeyguardStateCallbacks.remove(i); 1014 } 1015 } 1016 } 1017 } 1018 } 1019 1020 /** 1021 * Enable the keyguard if the settings are appropriate. 1022 */ 1023 private void doKeyguardLocked(Bundle options) { 1024 // if another app is disabling us, don't show 1025 if (!mExternallyEnabled) { 1026 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled"); 1027 1028 // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes 1029 // for an occasional ugly flicker in this situation: 1030 // 1) receive a call with the screen on (no keyguard) or make a call 1031 // 2) screen times out 1032 // 3) user hits key to turn screen back on 1033 // instead, we reenable the keyguard when we know the screen is off and the call 1034 // ends (see the broadcast receiver below) 1035 // TODO: clean this up when we have better support at the window manager level 1036 // for apps that wish to be on top of the keyguard 1037 return; 1038 } 1039 1040 // if the keyguard is already showing, don't bother 1041 if (mStatusBarKeyguardViewManager.isShowing()) { 1042 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing"); 1043 resetStateLocked(); 1044 return; 1045 } 1046 1047 // In split system user mode, we never unlock system user. 1048 if (!UserManager.isSplitSystemUser() 1049 || KeyguardUpdateMonitor.getCurrentUser() != UserHandle.USER_SYSTEM) { 1050 1051 // if the setup wizard hasn't run yet, don't show 1052 final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim", false); 1053 final boolean absent = SubscriptionManager.isValidSubscriptionId( 1054 mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.ABSENT)); 1055 final boolean disabled = SubscriptionManager.isValidSubscriptionId( 1056 mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.PERM_DISABLED)); 1057 final boolean lockedOrMissing = mUpdateMonitor.isSimPinSecure() 1058 || ((absent || disabled) && requireSim); 1059 1060 if (!lockedOrMissing && shouldWaitForProvisioning()) { 1061 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned" 1062 + " and the sim is not locked or missing"); 1063 return; 1064 } 1065 1066 if (mLockPatternUtils.isLockScreenDisabled(KeyguardUpdateMonitor.getCurrentUser()) 1067 && !lockedOrMissing) { 1068 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off"); 1069 return; 1070 } 1071 1072 if (mLockPatternUtils.checkVoldPassword(KeyguardUpdateMonitor.getCurrentUser())) { 1073 if (DEBUG) Log.d(TAG, "Not showing lock screen since just decrypted"); 1074 // Without this, settings is not enabled until the lock screen first appears 1075 setShowingLocked(false); 1076 hideLocked(); 1077 return; 1078 } 1079 } 1080 1081 if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen"); 1082 showLocked(options); 1083 } 1084 1085 private boolean shouldWaitForProvisioning() { 1086 return !mUpdateMonitor.isDeviceProvisioned() && !isSecure(); 1087 } 1088 1089 /** 1090 * Dismiss the keyguard through the security layers. 1091 */ 1092 public void handleDismiss() { 1093 if (mShowing && !mOccluded) { 1094 mStatusBarKeyguardViewManager.dismiss(); 1095 } 1096 } 1097 1098 public void dismiss() { 1099 mHandler.sendEmptyMessage(DISMISS); 1100 } 1101 1102 /** 1103 * Send message to keyguard telling it to reset its state. 1104 * @see #handleReset 1105 */ 1106 private void resetStateLocked() { 1107 if (DEBUG) Log.e(TAG, "resetStateLocked"); 1108 Message msg = mHandler.obtainMessage(RESET); 1109 mHandler.sendMessage(msg); 1110 } 1111 1112 /** 1113 * Send message to keyguard telling it to verify unlock 1114 * @see #handleVerifyUnlock() 1115 */ 1116 private void verifyUnlockLocked() { 1117 if (DEBUG) Log.d(TAG, "verifyUnlockLocked"); 1118 mHandler.sendEmptyMessage(VERIFY_UNLOCK); 1119 } 1120 1121 private void notifyFinishedGoingToSleep() { 1122 if (DEBUG) Log.d(TAG, "notifyFinishedGoingToSleep"); 1123 mHandler.sendEmptyMessage(NOTIFY_FINISHED_GOING_TO_SLEEP); 1124 } 1125 1126 private void notifyStartedWakingUp() { 1127 if (DEBUG) Log.d(TAG, "notifyStartedWakingUp"); 1128 mHandler.sendEmptyMessage(NOTIFY_STARTED_WAKING_UP); 1129 } 1130 1131 private void notifyScreenOn(IKeyguardDrawnCallback callback) { 1132 if (DEBUG) Log.d(TAG, "notifyScreenOn"); 1133 Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNING_ON, callback); 1134 mHandler.sendMessage(msg); 1135 } 1136 1137 private void notifyScreenTurnedOn() { 1138 if (DEBUG) Log.d(TAG, "notifyScreenTurnedOn"); 1139 Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNED_ON); 1140 mHandler.sendMessage(msg); 1141 } 1142 1143 private void notifyScreenTurnedOff() { 1144 if (DEBUG) Log.d(TAG, "notifyScreenTurnedOff"); 1145 Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNED_OFF); 1146 mHandler.sendMessage(msg); 1147 } 1148 1149 /** 1150 * Send message to keyguard telling it to show itself 1151 * @see #handleShow 1152 */ 1153 private void showLocked(Bundle options) { 1154 if (DEBUG) Log.d(TAG, "showLocked"); 1155 // ensure we stay awake until we are finished displaying the keyguard 1156 mShowKeyguardWakeLock.acquire(); 1157 Message msg = mHandler.obtainMessage(SHOW, options); 1158 mHandler.sendMessage(msg); 1159 } 1160 1161 /** 1162 * Send message to keyguard telling it to hide itself 1163 * @see #handleHide() 1164 */ 1165 private void hideLocked() { 1166 if (DEBUG) Log.d(TAG, "hideLocked"); 1167 Message msg = mHandler.obtainMessage(HIDE); 1168 mHandler.sendMessage(msg); 1169 } 1170 1171 public boolean isSecure() { 1172 return mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser()) 1173 || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure(); 1174 } 1175 1176 /** 1177 * Update the newUserId. Call while holding WindowManagerService lock. 1178 * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing. 1179 * 1180 * @param newUserId The id of the incoming user. 1181 */ 1182 public void setCurrentUser(int newUserId) { 1183 KeyguardUpdateMonitor.setCurrentUser(newUserId); 1184 } 1185 1186 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { 1187 @Override 1188 public void onReceive(Context context, Intent intent) { 1189 if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) { 1190 final int sequence = intent.getIntExtra("seq", 0); 1191 if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = " 1192 + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence); 1193 synchronized (KeyguardViewMediator.this) { 1194 if (mDelayedShowingSequence == sequence) { 1195 doKeyguardLocked(null); 1196 } 1197 } 1198 } 1199 } 1200 }; 1201 1202 public void keyguardDone(boolean authenticated, boolean wakeup) { 1203 if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated + ")"); 1204 EventLog.writeEvent(70000, 2); 1205 Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0, wakeup ? 1 : 0); 1206 mHandler.sendMessage(msg); 1207 } 1208 1209 /** 1210 * This handler will be associated with the policy thread, which will also 1211 * be the UI thread of the keyguard. Since the apis of the policy, and therefore 1212 * this class, can be called by other threads, any action that directly 1213 * interacts with the keyguard ui should be posted to this handler, rather 1214 * than called directly. 1215 */ 1216 private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) { 1217 @Override 1218 public void handleMessage(Message msg) { 1219 switch (msg.what) { 1220 case SHOW: 1221 handleShow((Bundle) msg.obj); 1222 break; 1223 case HIDE: 1224 handleHide(); 1225 break; 1226 case RESET: 1227 handleReset(); 1228 break; 1229 case VERIFY_UNLOCK: 1230 handleVerifyUnlock(); 1231 break; 1232 case NOTIFY_FINISHED_GOING_TO_SLEEP: 1233 handleNotifyFinishedGoingToSleep(); 1234 break; 1235 case NOTIFY_SCREEN_TURNING_ON: 1236 handleNotifyScreenTurningOn((IKeyguardDrawnCallback) msg.obj); 1237 break; 1238 case NOTIFY_SCREEN_TURNED_ON: 1239 handleNotifyScreenTurnedOn(); 1240 break; 1241 case NOTIFY_SCREEN_TURNED_OFF: 1242 handleNotifyScreenTurnedOff(); 1243 break; 1244 case NOTIFY_STARTED_WAKING_UP: 1245 handleNotifyStartedWakingUp(); 1246 break; 1247 case KEYGUARD_DONE: 1248 handleKeyguardDone(msg.arg1 != 0, msg.arg2 != 0); 1249 break; 1250 case KEYGUARD_DONE_DRAWING: 1251 handleKeyguardDoneDrawing(); 1252 break; 1253 case KEYGUARD_DONE_AUTHENTICATING: 1254 keyguardDone(true, true); 1255 break; 1256 case SET_OCCLUDED: 1257 handleSetOccluded(msg.arg1 != 0); 1258 break; 1259 case KEYGUARD_TIMEOUT: 1260 synchronized (KeyguardViewMediator.this) { 1261 doKeyguardLocked((Bundle) msg.obj); 1262 } 1263 break; 1264 case DISMISS: 1265 handleDismiss(); 1266 break; 1267 case START_KEYGUARD_EXIT_ANIM: 1268 StartKeyguardExitAnimParams params = (StartKeyguardExitAnimParams) msg.obj; 1269 handleStartKeyguardExitAnimation(params.startTime, params.fadeoutDuration); 1270 break; 1271 case KEYGUARD_DONE_PENDING_TIMEOUT: 1272 Log.w(TAG, "Timeout while waiting for activity drawn!"); 1273 // Fall through. 1274 case ON_ACTIVITY_DRAWN: 1275 handleOnActivityDrawn(); 1276 break; 1277 } 1278 } 1279 }; 1280 1281 /** 1282 * @see #keyguardDone 1283 * @see #KEYGUARD_DONE 1284 */ 1285 private void handleKeyguardDone(boolean authenticated, boolean wakeup) { 1286 if (DEBUG) Log.d(TAG, "handleKeyguardDone"); 1287 synchronized (this) { 1288 resetKeyguardDonePendingLocked(); 1289 } 1290 1291 if (authenticated) { 1292 mUpdateMonitor.clearFailedUnlockAttempts(); 1293 } 1294 mUpdateMonitor.clearFingerprintRecognized(); 1295 1296 if (mGoingToSleep) { 1297 Log.i(TAG, "Device is going to sleep, aborting keyguardDone"); 1298 return; 1299 } 1300 if (mExitSecureCallback != null) { 1301 try { 1302 mExitSecureCallback.onKeyguardExitResult(authenticated); 1303 } catch (RemoteException e) { 1304 Slog.w(TAG, "Failed to call onKeyguardExitResult(" + authenticated + ")", e); 1305 } 1306 1307 mExitSecureCallback = null; 1308 1309 if (authenticated) { 1310 // after succesfully exiting securely, no need to reshow 1311 // the keyguard when they've released the lock 1312 mExternallyEnabled = true; 1313 mNeedToReshowWhenReenabled = false; 1314 updateInputRestricted(); 1315 } 1316 } 1317 1318 handleHide(); 1319 } 1320 1321 private void sendUserPresentBroadcast() { 1322 synchronized (this) { 1323 if (mBootCompleted) { 1324 final UserHandle currentUser = new UserHandle(KeyguardUpdateMonitor.getCurrentUser()); 1325 final UserManager um = (UserManager) mContext.getSystemService( 1326 Context.USER_SERVICE); 1327 List <UserInfo> userHandles = um.getProfiles(currentUser.getIdentifier()); 1328 for (UserInfo ui : userHandles) { 1329 mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, ui.getUserHandle()); 1330 } 1331 } else { 1332 mBootSendUserPresent = true; 1333 } 1334 } 1335 } 1336 1337 /** 1338 * @see #keyguardDone 1339 * @see #KEYGUARD_DONE_DRAWING 1340 */ 1341 private void handleKeyguardDoneDrawing() { 1342 synchronized(this) { 1343 if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing"); 1344 if (mWaitingUntilKeyguardVisible) { 1345 if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible"); 1346 mWaitingUntilKeyguardVisible = false; 1347 notifyAll(); 1348 1349 // there will usually be two of these sent, one as a timeout, and one 1350 // as a result of the callback, so remove any remaining messages from 1351 // the queue 1352 mHandler.removeMessages(KEYGUARD_DONE_DRAWING); 1353 } 1354 } 1355 } 1356 1357 private void playSounds(boolean locked) { 1358 playSound(locked ? mLockSoundId : mUnlockSoundId); 1359 } 1360 1361 private void playSound(int soundId) { 1362 if (soundId == 0) return; 1363 final ContentResolver cr = mContext.getContentResolver(); 1364 if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) { 1365 1366 mLockSounds.stop(mLockSoundStreamId); 1367 // Init mAudioManager 1368 if (mAudioManager == null) { 1369 mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 1370 if (mAudioManager == null) return; 1371 mUiSoundsStreamType = mAudioManager.getUiSoundsStreamType(); 1372 } 1373 // If the stream is muted, don't play the sound 1374 if (mAudioManager.isStreamMute(mUiSoundsStreamType)) return; 1375 1376 mLockSoundStreamId = mLockSounds.play(soundId, 1377 mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/); 1378 } 1379 } 1380 1381 private void playTrustedSound() { 1382 playSound(mTrustedSoundId); 1383 } 1384 1385 private void updateActivityLockScreenState() { 1386 try { 1387 ActivityManagerNative.getDefault().setLockScreenShown(mShowing && !mOccluded); 1388 } catch (RemoteException e) { 1389 } 1390 } 1391 1392 /** 1393 * Handle message sent by {@link #showLocked}. 1394 * @see #SHOW 1395 */ 1396 private void handleShow(Bundle options) { 1397 synchronized (KeyguardViewMediator.this) { 1398 if (!mSystemReady) { 1399 if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready."); 1400 return; 1401 } else { 1402 if (DEBUG) Log.d(TAG, "handleShow"); 1403 } 1404 1405 setShowingLocked(true); 1406 mStatusBarKeyguardViewManager.show(options); 1407 mHiding = false; 1408 mWakeAndUnlocking = false; 1409 resetKeyguardDonePendingLocked(); 1410 mHideAnimationRun = false; 1411 updateActivityLockScreenState(); 1412 adjustStatusBarLocked(); 1413 userActivity(); 1414 1415 mShowKeyguardWakeLock.release(); 1416 } 1417 mKeyguardDisplayManager.show(); 1418 } 1419 1420 private final Runnable mKeyguardGoingAwayRunnable = new Runnable() { 1421 @Override 1422 public void run() { 1423 try { 1424 mStatusBarKeyguardViewManager.keyguardGoingAway(); 1425 1426 // Don't actually hide the Keyguard at the moment, wait for window 1427 // manager until it tells us it's safe to do so with 1428 // startKeyguardExitAnimation. 1429 ActivityManagerNative.getDefault().keyguardGoingAway( 1430 mStatusBarKeyguardViewManager.shouldDisableWindowAnimationsForUnlock() 1431 || mWakeAndUnlocking, 1432 mStatusBarKeyguardViewManager.isGoingToNotificationShade()); 1433 } catch (RemoteException e) { 1434 Log.e(TAG, "Error while calling WindowManager", e); 1435 } 1436 } 1437 }; 1438 1439 /** 1440 * Handle message sent by {@link #hideLocked()} 1441 * @see #HIDE 1442 */ 1443 private void handleHide() { 1444 synchronized (KeyguardViewMediator.this) { 1445 if (DEBUG) Log.d(TAG, "handleHide"); 1446 1447 if (UserManager.isSplitSystemUser() 1448 && KeyguardUpdateMonitor.getCurrentUser() == UserHandle.USER_SYSTEM) { 1449 // In split system user mode, we never unlock system user. The end user has to 1450 // switch to another user. 1451 // TODO: We should stop it early by disabling the swipe up flow. Right now swipe up 1452 // still completes and makes the screen blank. 1453 if (DEBUG) Log.d(TAG, "Split system user, quit unlocking."); 1454 return; 1455 } 1456 mHiding = true; 1457 if (mShowing && !mOccluded) { 1458 if (!mHideAnimationRun) { 1459 mStatusBarKeyguardViewManager.startPreHideAnimation(mKeyguardGoingAwayRunnable); 1460 } else { 1461 mKeyguardGoingAwayRunnable.run(); 1462 } 1463 } else { 1464 1465 // Don't try to rely on WindowManager - if Keyguard wasn't showing, window 1466 // manager won't start the exit animation. 1467 handleStartKeyguardExitAnimation( 1468 SystemClock.uptimeMillis() + mHideAnimation.getStartOffset(), 1469 mHideAnimation.getDuration()); 1470 } 1471 } 1472 } 1473 1474 private void handleOnActivityDrawn() { 1475 if (DEBUG) Log.d(TAG, "handleOnActivityDrawn: mKeyguardDonePending=" + mKeyguardDonePending); 1476 if (mKeyguardDonePending) { 1477 mStatusBarKeyguardViewManager.onActivityDrawn(); 1478 } 1479 } 1480 1481 private void handleStartKeyguardExitAnimation(long startTime, long fadeoutDuration) { 1482 synchronized (KeyguardViewMediator.this) { 1483 1484 if (!mHiding) { 1485 return; 1486 } 1487 mHiding = false; 1488 1489 // only play "unlock" noises if not on a call (since the incall UI 1490 // disables the keyguard) 1491 if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) { 1492 playSounds(false); 1493 } 1494 1495 setShowingLocked(false); 1496 mStatusBarKeyguardViewManager.hide(startTime, fadeoutDuration); 1497 resetKeyguardDonePendingLocked(); 1498 mHideAnimationRun = false; 1499 updateActivityLockScreenState(); 1500 adjustStatusBarLocked(); 1501 sendUserPresentBroadcast(); 1502 if (mWakeAndUnlocking && mDrawnCallback != null) { 1503 notifyDrawn(mDrawnCallback); 1504 } 1505 } 1506 } 1507 1508 private void adjustStatusBarLocked() { 1509 if (mStatusBarManager == null) { 1510 mStatusBarManager = (StatusBarManager) 1511 mContext.getSystemService(Context.STATUS_BAR_SERVICE); 1512 } 1513 if (mStatusBarManager == null) { 1514 Log.w(TAG, "Could not get status bar manager"); 1515 } else { 1516 // Disable aspects of the system/status/navigation bars that must not be re-enabled by 1517 // windows that appear on top, ever 1518 int flags = StatusBarManager.DISABLE_NONE; 1519 if (mShowing) { 1520 // Permanently disable components not available when keyguard is enabled 1521 // (like recents). Temporary enable/disable (e.g. the "back" button) are 1522 // done in KeyguardHostView. 1523 flags |= StatusBarManager.DISABLE_RECENT; 1524 flags |= StatusBarManager.DISABLE_SEARCH; 1525 } 1526 if (isShowingAndNotOccluded()) { 1527 flags |= StatusBarManager.DISABLE_HOME; 1528 } 1529 1530 if (DEBUG) { 1531 Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mOccluded=" + mOccluded 1532 + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags)); 1533 } 1534 1535 if (!(mContext instanceof Activity)) { 1536 mStatusBarManager.disable(flags); 1537 } 1538 } 1539 } 1540 1541 /** 1542 * Handle message sent by {@link #resetStateLocked} 1543 * @see #RESET 1544 */ 1545 private void handleReset() { 1546 synchronized (KeyguardViewMediator.this) { 1547 if (DEBUG) Log.d(TAG, "handleReset"); 1548 mStatusBarKeyguardViewManager.reset(); 1549 } 1550 } 1551 1552 /** 1553 * Handle message sent by {@link #verifyUnlock} 1554 * @see #VERIFY_UNLOCK 1555 */ 1556 private void handleVerifyUnlock() { 1557 synchronized (KeyguardViewMediator.this) { 1558 if (DEBUG) Log.d(TAG, "handleVerifyUnlock"); 1559 setShowingLocked(true); 1560 mStatusBarKeyguardViewManager.verifyUnlock(); 1561 updateActivityLockScreenState(); 1562 } 1563 } 1564 1565 /** 1566 * Handle message sent by {@link #notifyFinishedGoingToSleep()} 1567 * @see #NOTIFY_FINISHED_GOING_TO_SLEEP 1568 */ 1569 private void handleNotifyFinishedGoingToSleep() { 1570 synchronized (KeyguardViewMediator.this) { 1571 if (DEBUG) Log.d(TAG, "handleNotifyFinishedGoingToSleep"); 1572 mStatusBarKeyguardViewManager.onFinishedGoingToSleep(); 1573 } 1574 } 1575 1576 private void handleNotifyStartedWakingUp() { 1577 synchronized (KeyguardViewMediator.this) { 1578 if (DEBUG) Log.d(TAG, "handleNotifyWakingUp"); 1579 mStatusBarKeyguardViewManager.onStartedWakingUp(); 1580 } 1581 } 1582 1583 private void handleNotifyScreenTurningOn(IKeyguardDrawnCallback callback) { 1584 synchronized (KeyguardViewMediator.this) { 1585 if (DEBUG) Log.d(TAG, "handleNotifyScreenTurningOn"); 1586 if (callback != null) { 1587 if (mWakeAndUnlocking) { 1588 mDrawnCallback = callback; 1589 } else { 1590 notifyDrawn(callback); 1591 } 1592 } 1593 } 1594 } 1595 1596 private void handleNotifyScreenTurnedOn() { 1597 synchronized (this) { 1598 if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOn"); 1599 mStatusBarKeyguardViewManager.onScreenTurnedOn(); 1600 } 1601 } 1602 1603 private void handleNotifyScreenTurnedOff() { 1604 synchronized (this) { 1605 if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOff"); 1606 mStatusBarKeyguardViewManager.onScreenTurnedOff(); 1607 } 1608 } 1609 1610 private void notifyDrawn(final IKeyguardDrawnCallback callback) { 1611 try { 1612 callback.onDrawn(); 1613 } catch (RemoteException e) { 1614 Slog.w(TAG, "Exception calling onDrawn():", e); 1615 } 1616 } 1617 1618 private void resetKeyguardDonePendingLocked() { 1619 mKeyguardDonePending = false; 1620 mHandler.removeMessages(KEYGUARD_DONE_PENDING_TIMEOUT); 1621 } 1622 1623 public void onBootCompleted() { 1624 mUpdateMonitor.dispatchBootCompleted(); 1625 synchronized (this) { 1626 mBootCompleted = true; 1627 if (mBootSendUserPresent) { 1628 sendUserPresentBroadcast(); 1629 } 1630 } 1631 } 1632 1633 public StatusBarKeyguardViewManager registerStatusBar(PhoneStatusBar phoneStatusBar, 1634 ViewGroup container, StatusBarWindowManager statusBarWindowManager, 1635 ScrimController scrimController) { 1636 mStatusBarKeyguardViewManager.registerStatusBar(phoneStatusBar, container, 1637 statusBarWindowManager, scrimController); 1638 return mStatusBarKeyguardViewManager; 1639 } 1640 1641 public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) { 1642 Message msg = mHandler.obtainMessage(START_KEYGUARD_EXIT_ANIM, 1643 new StartKeyguardExitAnimParams(startTime, fadeoutDuration)); 1644 mHandler.sendMessage(msg); 1645 } 1646 1647 public void onActivityDrawn() { 1648 mHandler.sendEmptyMessage(ON_ACTIVITY_DRAWN); 1649 } 1650 public ViewMediatorCallback getViewMediatorCallback() { 1651 return mViewMediatorCallback; 1652 } 1653 1654 private static class StartKeyguardExitAnimParams { 1655 1656 long startTime; 1657 long fadeoutDuration; 1658 1659 private StartKeyguardExitAnimParams(long startTime, long fadeoutDuration) { 1660 this.startTime = startTime; 1661 this.fadeoutDuration = fadeoutDuration; 1662 } 1663 } 1664 1665 private void setShowingLocked(boolean showing) { 1666 if (showing != mShowing) { 1667 mShowing = showing; 1668 int size = mKeyguardStateCallbacks.size(); 1669 for (int i = size - 1; i >= 0; i--) { 1670 try { 1671 mKeyguardStateCallbacks.get(i).onShowingStateChanged(showing); 1672 } catch (RemoteException e) { 1673 Slog.w(TAG, "Failed to call onShowingStateChanged", e); 1674 if (e instanceof DeadObjectException) { 1675 mKeyguardStateCallbacks.remove(i); 1676 } 1677 } 1678 } 1679 updateInputRestrictedLocked(); 1680 mTrustManager.reportKeyguardShowingChanged(); 1681 } 1682 } 1683 1684 public void addStateMonitorCallback(IKeyguardStateCallback callback) { 1685 synchronized (this) { 1686 mKeyguardStateCallbacks.add(callback); 1687 try { 1688 callback.onSimSecureStateChanged(mUpdateMonitor.isSimPinSecure()); 1689 callback.onShowingStateChanged(mShowing); 1690 callback.onInputRestrictedStateChanged(mInputRestricted); 1691 } catch (RemoteException e) { 1692 Slog.w(TAG, "Failed to call onShowingStateChanged or onSimSecureStateChanged or onInputRestrictedStateChanged", e); 1693 } 1694 } 1695 } 1696} 1697