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