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