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