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