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