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