1 /* 2 * Copyright (C) 2008 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 17 package com.android.keyguard; 18 19 import static android.content.Intent.ACTION_USER_UNLOCKED; 20 import static android.os.BatteryManager.BATTERY_HEALTH_UNKNOWN; 21 import static android.os.BatteryManager.BATTERY_STATUS_FULL; 22 import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN; 23 import static android.os.BatteryManager.EXTRA_HEALTH; 24 import static android.os.BatteryManager.EXTRA_LEVEL; 25 import static android.os.BatteryManager.EXTRA_MAX_CHARGING_CURRENT; 26 import static android.os.BatteryManager.EXTRA_MAX_CHARGING_VOLTAGE; 27 import static android.os.BatteryManager.EXTRA_PLUGGED; 28 import static android.os.BatteryManager.EXTRA_STATUS; 29 30 import android.app.ActivityManager; 31 import android.app.AlarmManager; 32 import android.app.PendingIntent; 33 import android.app.UserSwitchObserver; 34 import android.app.admin.DevicePolicyManager; 35 import android.app.trust.TrustManager; 36 import android.content.BroadcastReceiver; 37 import android.content.ComponentName; 38 import android.content.Context; 39 import android.content.Intent; 40 import android.content.IntentFilter; 41 import android.content.pm.IPackageManager; 42 import android.content.pm.PackageManager; 43 import android.content.pm.ResolveInfo; 44 import android.database.ContentObserver; 45 import android.graphics.Bitmap; 46 import android.hardware.fingerprint.FingerprintManager; 47 import android.hardware.fingerprint.FingerprintManager.AuthenticationCallback; 48 import android.hardware.fingerprint.FingerprintManager.AuthenticationResult; 49 import android.media.AudioManager; 50 import android.os.BatteryManager; 51 import android.os.CancellationSignal; 52 import android.os.Handler; 53 import android.os.IBinder; 54 import android.os.IRemoteCallback; 55 import android.os.Message; 56 import android.os.RemoteException; 57 import android.os.ServiceManager; 58 import android.os.Trace; 59 import android.os.UserHandle; 60 import android.os.UserManager; 61 import android.provider.Settings; 62 import android.service.dreams.DreamService; 63 import android.service.dreams.IDreamManager; 64 import android.telephony.ServiceState; 65 import android.telephony.SubscriptionInfo; 66 import android.telephony.SubscriptionManager; 67 import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener; 68 import android.telephony.TelephonyManager; 69 import android.util.Log; 70 import android.util.SparseBooleanArray; 71 import android.util.SparseIntArray; 72 73 import com.android.internal.telephony.IccCardConstants; 74 import com.android.internal.telephony.IccCardConstants.State; 75 import com.android.internal.telephony.PhoneConstants; 76 import com.android.internal.telephony.TelephonyIntents; 77 import com.android.internal.widget.LockPatternUtils; 78 import com.android.systemui.recents.misc.SystemServicesProxy; 79 import com.android.systemui.recents.misc.SystemServicesProxy.TaskStackListener; 80 81 import com.google.android.collect.Lists; 82 83 import java.io.FileDescriptor; 84 import java.io.PrintWriter; 85 import java.lang.ref.WeakReference; 86 import java.util.ArrayList; 87 import java.util.HashMap; 88 import java.util.List; 89 import java.util.Map.Entry; 90 91 /** 92 * Watches for updates that may be interesting to the keyguard, and provides 93 * the up to date information as well as a registration for callbacks that care 94 * to be updated. 95 * 96 * Note: under time crunch, this has been extended to include some stuff that 97 * doesn't really belong here. see {@link #handleBatteryUpdate} where it shutdowns 98 * the device, and {@link #getFailedUnlockAttempts()}, {@link #reportFailedAttempt()} 99 * and {@link #clearFailedUnlockAttempts()}. Maybe we should rename this 'KeyguardContext'... 100 */ 101 public class KeyguardUpdateMonitor implements TrustManager.TrustListener { 102 103 private static final String TAG = "KeyguardUpdateMonitor"; 104 private static final boolean DEBUG = KeyguardConstants.DEBUG; 105 private static final boolean DEBUG_SIM_STATES = KeyguardConstants.DEBUG_SIM_STATES; 106 private static final int LOW_BATTERY_THRESHOLD = 20; 107 108 private static final String ACTION_FACE_UNLOCK_STARTED 109 = "com.android.facelock.FACE_UNLOCK_STARTED"; 110 private static final String ACTION_FACE_UNLOCK_STOPPED 111 = "com.android.facelock.FACE_UNLOCK_STOPPED"; 112 113 // Callback messages 114 private static final int MSG_TIME_UPDATE = 301; 115 private static final int MSG_BATTERY_UPDATE = 302; 116 private static final int MSG_SIM_STATE_CHANGE = 304; 117 private static final int MSG_RINGER_MODE_CHANGED = 305; 118 private static final int MSG_PHONE_STATE_CHANGED = 306; 119 private static final int MSG_DEVICE_PROVISIONED = 308; 120 private static final int MSG_DPM_STATE_CHANGED = 309; 121 private static final int MSG_USER_SWITCHING = 310; 122 private static final int MSG_KEYGUARD_RESET = 312; 123 private static final int MSG_BOOT_COMPLETED = 313; 124 private static final int MSG_USER_SWITCH_COMPLETE = 314; 125 private static final int MSG_USER_INFO_CHANGED = 317; 126 private static final int MSG_REPORT_EMERGENCY_CALL_ACTION = 318; 127 private static final int MSG_STARTED_WAKING_UP = 319; 128 private static final int MSG_FINISHED_GOING_TO_SLEEP = 320; 129 private static final int MSG_STARTED_GOING_TO_SLEEP = 321; 130 private static final int MSG_KEYGUARD_BOUNCER_CHANGED = 322; 131 private static final int MSG_FACE_UNLOCK_STATE_CHANGED = 327; 132 private static final int MSG_SIM_SUBSCRIPTION_INFO_CHANGED = 328; 133 private static final int MSG_AIRPLANE_MODE_CHANGED = 329; 134 private static final int MSG_SERVICE_STATE_CHANGE = 330; 135 private static final int MSG_SCREEN_TURNED_ON = 331; 136 private static final int MSG_SCREEN_TURNED_OFF = 332; 137 private static final int MSG_DREAMING_STATE_CHANGED = 333; 138 private static final int MSG_USER_UNLOCKED = 334; 139 private static final int MSG_ASSISTANT_STACK_CHANGED = 335; 140 private static final int MSG_FINGERPRINT_AUTHENTICATION_CONTINUE = 336; 141 142 /** Fingerprint state: Not listening to fingerprint. */ 143 private static final int FINGERPRINT_STATE_STOPPED = 0; 144 145 /** Fingerprint state: Listening. */ 146 private static final int FINGERPRINT_STATE_RUNNING = 1; 147 148 /** 149 * Fingerprint state: Cancelling and waiting for the confirmation from FingerprintService to 150 * send us the confirmation that cancellation has happened. 151 */ 152 private static final int FINGERPRINT_STATE_CANCELLING = 2; 153 154 /** 155 * Fingerprint state: During cancelling we got another request to start listening, so when we 156 * receive the cancellation done signal, we should start listening again. 157 */ 158 private static final int FINGERPRINT_STATE_CANCELLING_RESTARTING = 3; 159 160 private static final int DEFAULT_CHARGING_VOLTAGE_MICRO_VOLT = 5000000; 161 162 private static final ComponentName FALLBACK_HOME_COMPONENT = new ComponentName( 163 "com.android.settings", "com.android.settings.FallbackHome"); 164 165 166 /** 167 * If true, the system is in the half-boot-to-decryption-screen state. 168 * Prudently disable lockscreen. 169 */ 170 public static final boolean CORE_APPS_ONLY; 171 static { 172 try { 173 CORE_APPS_ONLY = IPackageManager.Stub.asInterface( 174 ServiceManager.getService("package")).isOnlyCoreApps(); 175 } catch (RemoteException e) { 176 throw e.rethrowFromSystemServer(); 177 } 178 } 179 180 private static KeyguardUpdateMonitor sInstance; 181 182 private final Context mContext; 183 HashMap<Integer, SimData> mSimDatas = new HashMap<Integer, SimData>(); 184 HashMap<Integer, ServiceState> mServiceStates = new HashMap<Integer, ServiceState>(); 185 186 private int mRingMode; 187 private int mPhoneState; 188 private boolean mKeyguardIsVisible; 189 private boolean mKeyguardGoingAway; 190 private boolean mGoingToSleep; 191 private boolean mBouncer; 192 private boolean mBootCompleted; 193 private boolean mNeedsSlowUnlockTransition; 194 private boolean mHasLockscreenWallpaper; 195 private boolean mAssistantVisible; 196 private boolean mKeyguardOccluded; 197 198 // Device provisioning state 199 private boolean mDeviceProvisioned; 200 201 // Battery status 202 private BatteryStatus mBatteryStatus; 203 204 // Password attempts 205 private SparseIntArray mFailedAttempts = new SparseIntArray(); 206 207 private final StrongAuthTracker mStrongAuthTracker; 208 209 private final ArrayList<WeakReference<KeyguardUpdateMonitorCallback>> 210 mCallbacks = Lists.newArrayList(); 211 private ContentObserver mDeviceProvisionedObserver; 212 213 private boolean mSwitchingUser; 214 215 private boolean mDeviceInteractive; 216 private boolean mScreenOn; 217 private SubscriptionManager mSubscriptionManager; 218 private List<SubscriptionInfo> mSubscriptionInfo; 219 private TrustManager mTrustManager; 220 private UserManager mUserManager; 221 private int mFingerprintRunningState = FINGERPRINT_STATE_STOPPED; 222 private LockPatternUtils mLockPatternUtils; 223 private final IDreamManager mDreamManager; 224 private boolean mIsDreaming; 225 226 /** 227 * Short delay before restarting fingerprint authentication after a successful try 228 * This should be slightly longer than the time between onFingerprintAuthenticated and 229 * setKeyguardGoingAway(true). 230 */ 231 private static final int FINGERPRINT_CONTINUE_DELAY_MS = 500; 232 233 // If FP daemon dies, keyguard should retry after a short delay 234 private int mHardwareUnavailableRetryCount = 0; 235 private static final int HW_UNAVAILABLE_TIMEOUT = 3000; // ms 236 private static final int HW_UNAVAILABLE_RETRY_MAX = 3; 237 238 private final Handler mHandler = new Handler() { 239 @Override 240 public void handleMessage(Message msg) { 241 switch (msg.what) { 242 case MSG_TIME_UPDATE: 243 handleTimeUpdate(); 244 break; 245 case MSG_BATTERY_UPDATE: 246 handleBatteryUpdate((BatteryStatus) msg.obj); 247 break; 248 case MSG_SIM_STATE_CHANGE: 249 handleSimStateChange(msg.arg1, msg.arg2, (State) msg.obj); 250 break; 251 case MSG_RINGER_MODE_CHANGED: 252 handleRingerModeChange(msg.arg1); 253 break; 254 case MSG_PHONE_STATE_CHANGED: 255 handlePhoneStateChanged((String) msg.obj); 256 break; 257 case MSG_DEVICE_PROVISIONED: 258 handleDeviceProvisioned(); 259 break; 260 case MSG_DPM_STATE_CHANGED: 261 handleDevicePolicyManagerStateChanged(); 262 break; 263 case MSG_USER_SWITCHING: 264 handleUserSwitching(msg.arg1, (IRemoteCallback) msg.obj); 265 break; 266 case MSG_USER_SWITCH_COMPLETE: 267 handleUserSwitchComplete(msg.arg1); 268 break; 269 case MSG_KEYGUARD_RESET: 270 handleKeyguardReset(); 271 break; 272 case MSG_KEYGUARD_BOUNCER_CHANGED: 273 handleKeyguardBouncerChanged(msg.arg1); 274 break; 275 case MSG_BOOT_COMPLETED: 276 handleBootCompleted(); 277 break; 278 case MSG_USER_INFO_CHANGED: 279 handleUserInfoChanged(msg.arg1); 280 break; 281 case MSG_REPORT_EMERGENCY_CALL_ACTION: 282 handleReportEmergencyCallAction(); 283 break; 284 case MSG_STARTED_GOING_TO_SLEEP: 285 handleStartedGoingToSleep(msg.arg1); 286 break; 287 case MSG_FINISHED_GOING_TO_SLEEP: 288 handleFinishedGoingToSleep(msg.arg1); 289 break; 290 case MSG_STARTED_WAKING_UP: 291 Trace.beginSection("KeyguardUpdateMonitor#handler MSG_STARTED_WAKING_UP"); 292 handleStartedWakingUp(); 293 Trace.endSection(); 294 break; 295 case MSG_FACE_UNLOCK_STATE_CHANGED: 296 Trace.beginSection("KeyguardUpdateMonitor#handler MSG_FACE_UNLOCK_STATE_CHANGED"); 297 handleFaceUnlockStateChanged(msg.arg1 != 0, msg.arg2); 298 Trace.endSection(); 299 break; 300 case MSG_SIM_SUBSCRIPTION_INFO_CHANGED: 301 handleSimSubscriptionInfoChanged(); 302 break; 303 case MSG_AIRPLANE_MODE_CHANGED: 304 handleAirplaneModeChanged(); 305 break; 306 case MSG_SERVICE_STATE_CHANGE: 307 handleServiceStateChange(msg.arg1, (ServiceState) msg.obj); 308 break; 309 case MSG_SCREEN_TURNED_ON: 310 handleScreenTurnedOn(); 311 break; 312 case MSG_SCREEN_TURNED_OFF: 313 Trace.beginSection("KeyguardUpdateMonitor#handler MSG_SCREEN_TURNED_ON"); 314 handleScreenTurnedOff(); 315 Trace.endSection(); 316 break; 317 case MSG_DREAMING_STATE_CHANGED: 318 handleDreamingStateChanged(msg.arg1); 319 break; 320 case MSG_USER_UNLOCKED: 321 handleUserUnlocked(); 322 break; 323 case MSG_ASSISTANT_STACK_CHANGED: 324 mAssistantVisible = (boolean)msg.obj; 325 updateFingerprintListeningState(); 326 break; 327 case MSG_FINGERPRINT_AUTHENTICATION_CONTINUE: 328 updateFingerprintListeningState(); 329 break; 330 } 331 } 332 }; 333 334 private OnSubscriptionsChangedListener mSubscriptionListener = 335 new OnSubscriptionsChangedListener() { 336 @Override 337 public void onSubscriptionsChanged() { 338 mHandler.sendEmptyMessage(MSG_SIM_SUBSCRIPTION_INFO_CHANGED); 339 } 340 }; 341 342 private SparseBooleanArray mUserHasTrust = new SparseBooleanArray(); 343 private SparseBooleanArray mUserTrustIsManaged = new SparseBooleanArray(); 344 private SparseBooleanArray mUserFingerprintAuthenticated = new SparseBooleanArray(); 345 private SparseBooleanArray mUserFaceUnlockRunning = new SparseBooleanArray(); 346 347 private static int sCurrentUser; 348 setCurrentUser(int currentUser)349 public synchronized static void setCurrentUser(int currentUser) { 350 sCurrentUser = currentUser; 351 } 352 getCurrentUser()353 public synchronized static int getCurrentUser() { 354 return sCurrentUser; 355 } 356 357 @Override onTrustChanged(boolean enabled, int userId, int flags)358 public void onTrustChanged(boolean enabled, int userId, int flags) { 359 mUserHasTrust.put(userId, enabled); 360 for (int i = 0; i < mCallbacks.size(); i++) { 361 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 362 if (cb != null) { 363 cb.onTrustChanged(userId); 364 if (enabled && flags != 0) { 365 cb.onTrustGrantedWithFlags(flags, userId); 366 } 367 } 368 } 369 } 370 handleSimSubscriptionInfoChanged()371 protected void handleSimSubscriptionInfoChanged() { 372 if (DEBUG_SIM_STATES) { 373 Log.v(TAG, "onSubscriptionInfoChanged()"); 374 List<SubscriptionInfo> sil = mSubscriptionManager.getActiveSubscriptionInfoList(); 375 if (sil != null) { 376 for (SubscriptionInfo subInfo : sil) { 377 Log.v(TAG, "SubInfo:" + subInfo); 378 } 379 } else { 380 Log.v(TAG, "onSubscriptionInfoChanged: list is null"); 381 } 382 } 383 List<SubscriptionInfo> subscriptionInfos = getSubscriptionInfo(true /* forceReload */); 384 385 // Hack level over 9000: Because the subscription id is not yet valid when we see the 386 // first update in handleSimStateChange, we need to force refresh all all SIM states 387 // so the subscription id for them is consistent. 388 ArrayList<SubscriptionInfo> changedSubscriptions = new ArrayList<>(); 389 for (int i = 0; i < subscriptionInfos.size(); i++) { 390 SubscriptionInfo info = subscriptionInfos.get(i); 391 boolean changed = refreshSimState(info.getSubscriptionId(), info.getSimSlotIndex()); 392 if (changed) { 393 changedSubscriptions.add(info); 394 } 395 } 396 for (int i = 0; i < changedSubscriptions.size(); i++) { 397 SimData data = mSimDatas.get(changedSubscriptions.get(i).getSubscriptionId()); 398 for (int j = 0; j < mCallbacks.size(); j++) { 399 KeyguardUpdateMonitorCallback cb = mCallbacks.get(j).get(); 400 if (cb != null) { 401 cb.onSimStateChanged(data.subId, data.slotId, data.simState); 402 } 403 } 404 } 405 for (int j = 0; j < mCallbacks.size(); j++) { 406 KeyguardUpdateMonitorCallback cb = mCallbacks.get(j).get(); 407 if (cb != null) { 408 cb.onRefreshCarrierInfo(); 409 } 410 } 411 } 412 handleAirplaneModeChanged()413 private void handleAirplaneModeChanged() { 414 for (int j = 0; j < mCallbacks.size(); j++) { 415 KeyguardUpdateMonitorCallback cb = mCallbacks.get(j).get(); 416 if (cb != null) { 417 cb.onRefreshCarrierInfo(); 418 } 419 } 420 } 421 422 /** @return List of SubscriptionInfo records, maybe empty but never null */ getSubscriptionInfo(boolean forceReload)423 public List<SubscriptionInfo> getSubscriptionInfo(boolean forceReload) { 424 List<SubscriptionInfo> sil = mSubscriptionInfo; 425 if (sil == null || forceReload) { 426 sil = mSubscriptionManager.getActiveSubscriptionInfoList(); 427 } 428 if (sil == null) { 429 // getActiveSubscriptionInfoList was null callers expect an empty list. 430 mSubscriptionInfo = new ArrayList<SubscriptionInfo>(); 431 } else { 432 mSubscriptionInfo = sil; 433 } 434 return mSubscriptionInfo; 435 } 436 437 @Override onTrustManagedChanged(boolean managed, int userId)438 public void onTrustManagedChanged(boolean managed, int userId) { 439 mUserTrustIsManaged.put(userId, managed); 440 441 for (int i = 0; i < mCallbacks.size(); i++) { 442 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 443 if (cb != null) { 444 cb.onTrustManagedChanged(userId); 445 } 446 } 447 } 448 449 /** 450 * Updates KeyguardUpdateMonitor's internal state to know if keyguard is goingAway 451 * @param goingAway 452 */ setKeyguardGoingAway(boolean goingAway)453 public void setKeyguardGoingAway(boolean goingAway) { 454 mKeyguardGoingAway = goingAway; 455 } 456 457 /** 458 * Updates KeyguardUpdateMonitor's internal state to know if keyguard is occluded 459 * @param occluded 460 */ setKeyguardOccluded(boolean occluded)461 public void setKeyguardOccluded(boolean occluded) { 462 mKeyguardOccluded = occluded; 463 updateFingerprintListeningState(); 464 } 465 466 /** 467 * @return a cached version of DreamManager.isDreaming() 468 */ isDreaming()469 public boolean isDreaming() { 470 return mIsDreaming; 471 } 472 473 /** 474 * If the device is dreaming, awakens the device 475 */ awakenFromDream()476 public void awakenFromDream() { 477 if (mIsDreaming && mDreamManager != null) { 478 try { 479 mDreamManager.awaken(); 480 } catch (RemoteException e) { 481 Log.e(TAG, "Unable to awaken from dream"); 482 } 483 } 484 } 485 onFingerprintAuthenticated(int userId)486 private void onFingerprintAuthenticated(int userId) { 487 Trace.beginSection("KeyGuardUpdateMonitor#onFingerPrintAuthenticated"); 488 mUserFingerprintAuthenticated.put(userId, true); 489 // Update/refresh trust state only if user can skip bouncer 490 if (getUserCanSkipBouncer(userId)) { 491 mTrustManager.unlockedByFingerprintForUser(userId); 492 } 493 // Don't send cancel if authentication succeeds 494 mFingerprintCancelSignal = null; 495 for (int i = 0; i < mCallbacks.size(); i++) { 496 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 497 if (cb != null) { 498 cb.onFingerprintAuthenticated(userId); 499 } 500 } 501 502 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_FINGERPRINT_AUTHENTICATION_CONTINUE), 503 FINGERPRINT_CONTINUE_DELAY_MS); 504 505 // Only authenticate fingerprint once when assistant is visible 506 mAssistantVisible = false; 507 508 Trace.endSection(); 509 } 510 handleFingerprintAuthFailed()511 private void handleFingerprintAuthFailed() { 512 for (int i = 0; i < mCallbacks.size(); i++) { 513 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 514 if (cb != null) { 515 cb.onFingerprintAuthFailed(); 516 } 517 } 518 handleFingerprintHelp(-1, mContext.getString(R.string.fingerprint_not_recognized)); 519 } 520 handleFingerprintAcquired(int acquireInfo)521 private void handleFingerprintAcquired(int acquireInfo) { 522 if (acquireInfo != FingerprintManager.FINGERPRINT_ACQUIRED_GOOD) { 523 return; 524 } 525 for (int i = 0; i < mCallbacks.size(); i++) { 526 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 527 if (cb != null) { 528 cb.onFingerprintAcquired(); 529 } 530 } 531 } 532 handleFingerprintAuthenticated(int authUserId)533 private void handleFingerprintAuthenticated(int authUserId) { 534 Trace.beginSection("KeyGuardUpdateMonitor#handlerFingerPrintAuthenticated"); 535 try { 536 final int userId; 537 try { 538 userId = ActivityManager.getService().getCurrentUser().id; 539 } catch (RemoteException e) { 540 Log.e(TAG, "Failed to get current user id: ", e); 541 return; 542 } 543 if (userId != authUserId) { 544 Log.d(TAG, "Fingerprint authenticated for wrong user: " + authUserId); 545 return; 546 } 547 if (isFingerprintDisabled(userId)) { 548 Log.d(TAG, "Fingerprint disabled by DPM for userId: " + userId); 549 return; 550 } 551 onFingerprintAuthenticated(userId); 552 } finally { 553 setFingerprintRunningState(FINGERPRINT_STATE_STOPPED); 554 } 555 Trace.endSection(); 556 } 557 handleFingerprintHelp(int msgId, String helpString)558 private void handleFingerprintHelp(int msgId, String helpString) { 559 for (int i = 0; i < mCallbacks.size(); i++) { 560 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 561 if (cb != null) { 562 cb.onFingerprintHelp(msgId, helpString); 563 } 564 } 565 } 566 567 private Runnable mRetryFingerprintAuthentication = new Runnable() { 568 @Override 569 public void run() { 570 Log.w(TAG, "Retrying fingerprint after HW unavailable, attempt " + 571 mHardwareUnavailableRetryCount); 572 updateFingerprintListeningState(); 573 } 574 }; 575 handleFingerprintError(int msgId, String errString)576 private void handleFingerprintError(int msgId, String errString) { 577 if (msgId == FingerprintManager.FINGERPRINT_ERROR_CANCELED 578 && mFingerprintRunningState == FINGERPRINT_STATE_CANCELLING_RESTARTING) { 579 setFingerprintRunningState(FINGERPRINT_STATE_STOPPED); 580 startListeningForFingerprint(); 581 } else { 582 setFingerprintRunningState(FINGERPRINT_STATE_STOPPED); 583 } 584 585 if (msgId == FingerprintManager.FINGERPRINT_ERROR_HW_UNAVAILABLE) { 586 if (mHardwareUnavailableRetryCount < HW_UNAVAILABLE_RETRY_MAX) { 587 mHardwareUnavailableRetryCount++; 588 mHandler.removeCallbacks(mRetryFingerprintAuthentication); 589 mHandler.postDelayed(mRetryFingerprintAuthentication, HW_UNAVAILABLE_TIMEOUT); 590 } 591 } 592 593 if (msgId == FingerprintManager.FINGERPRINT_ERROR_LOCKOUT_PERMANENT) { 594 mLockPatternUtils.requireStrongAuth( 595 LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_LOCKOUT, 596 getCurrentUser()); 597 } 598 599 for (int i = 0; i < mCallbacks.size(); i++) { 600 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 601 if (cb != null) { 602 cb.onFingerprintError(msgId, errString); 603 } 604 } 605 } 606 handleFingerprintLockoutReset()607 private void handleFingerprintLockoutReset() { 608 updateFingerprintListeningState(); 609 } 610 setFingerprintRunningState(int fingerprintRunningState)611 private void setFingerprintRunningState(int fingerprintRunningState) { 612 boolean wasRunning = mFingerprintRunningState == FINGERPRINT_STATE_RUNNING; 613 boolean isRunning = fingerprintRunningState == FINGERPRINT_STATE_RUNNING; 614 mFingerprintRunningState = fingerprintRunningState; 615 616 // Clients of KeyguardUpdateMonitor don't care about the internal state about the 617 // asynchronousness of the cancel cycle. So only notify them if the actualy running state 618 // has changed. 619 if (wasRunning != isRunning) { 620 notifyFingerprintRunningStateChanged(); 621 } 622 } 623 notifyFingerprintRunningStateChanged()624 private void notifyFingerprintRunningStateChanged() { 625 for (int i = 0; i < mCallbacks.size(); i++) { 626 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 627 if (cb != null) { 628 cb.onFingerprintRunningStateChanged(isFingerprintDetectionRunning()); 629 } 630 } 631 } handleFaceUnlockStateChanged(boolean running, int userId)632 private void handleFaceUnlockStateChanged(boolean running, int userId) { 633 mUserFaceUnlockRunning.put(userId, running); 634 for (int i = 0; i < mCallbacks.size(); i++) { 635 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 636 if (cb != null) { 637 cb.onFaceUnlockStateChanged(running, userId); 638 } 639 } 640 } 641 isFaceUnlockRunning(int userId)642 public boolean isFaceUnlockRunning(int userId) { 643 return mUserFaceUnlockRunning.get(userId); 644 } 645 isFingerprintDetectionRunning()646 public boolean isFingerprintDetectionRunning() { 647 return mFingerprintRunningState == FINGERPRINT_STATE_RUNNING; 648 } 649 isTrustDisabled(int userId)650 private boolean isTrustDisabled(int userId) { 651 // Don't allow trust agent if device is secured with a SIM PIN. This is here 652 // mainly because there's no other way to prompt the user to enter their SIM PIN 653 // once they get past the keyguard screen. 654 final boolean disabledBySimPin = isSimPinSecure(); 655 return disabledBySimPin; 656 } 657 isFingerprintDisabled(int userId)658 private boolean isFingerprintDisabled(int userId) { 659 final DevicePolicyManager dpm = 660 (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); 661 return dpm != null && (dpm.getKeyguardDisabledFeatures(null, userId) 662 & DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT) != 0 663 || isSimPinSecure(); 664 } 665 getUserCanSkipBouncer(int userId)666 public boolean getUserCanSkipBouncer(int userId) { 667 return getUserHasTrust(userId) || (mUserFingerprintAuthenticated.get(userId) 668 && isUnlockingWithFingerprintAllowed()); 669 } 670 getUserHasTrust(int userId)671 public boolean getUserHasTrust(int userId) { 672 return !isTrustDisabled(userId) && mUserHasTrust.get(userId); 673 } 674 getUserTrustIsManaged(int userId)675 public boolean getUserTrustIsManaged(int userId) { 676 return mUserTrustIsManaged.get(userId) && !isTrustDisabled(userId); 677 } 678 isUnlockingWithFingerprintAllowed()679 public boolean isUnlockingWithFingerprintAllowed() { 680 return mStrongAuthTracker.isUnlockingWithFingerprintAllowed(); 681 } 682 needsSlowUnlockTransition()683 public boolean needsSlowUnlockTransition() { 684 return mNeedsSlowUnlockTransition; 685 } 686 getStrongAuthTracker()687 public StrongAuthTracker getStrongAuthTracker() { 688 return mStrongAuthTracker; 689 } 690 notifyStrongAuthStateChanged(int userId)691 private void notifyStrongAuthStateChanged(int userId) { 692 for (int i = 0; i < mCallbacks.size(); i++) { 693 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 694 if (cb != null) { 695 cb.onStrongAuthStateChanged(userId); 696 } 697 } 698 } 699 isScreenOn()700 public boolean isScreenOn() { 701 return mScreenOn; 702 } 703 704 static class DisplayClientState { 705 public int clientGeneration; 706 public boolean clearing; 707 public PendingIntent intent; 708 public int playbackState; 709 public long playbackEventTime; 710 } 711 712 private DisplayClientState mDisplayClientState = new DisplayClientState(); 713 714 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { 715 716 @Override 717 public void onReceive(Context context, Intent intent) { 718 final String action = intent.getAction(); 719 if (DEBUG) Log.d(TAG, "received broadcast " + action); 720 721 if (Intent.ACTION_TIME_TICK.equals(action) 722 || Intent.ACTION_TIME_CHANGED.equals(action) 723 || Intent.ACTION_TIMEZONE_CHANGED.equals(action)) { 724 mHandler.sendEmptyMessage(MSG_TIME_UPDATE); 725 } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { 726 final int status = intent.getIntExtra(EXTRA_STATUS, BATTERY_STATUS_UNKNOWN); 727 final int plugged = intent.getIntExtra(EXTRA_PLUGGED, 0); 728 final int level = intent.getIntExtra(EXTRA_LEVEL, 0); 729 final int health = intent.getIntExtra(EXTRA_HEALTH, BATTERY_HEALTH_UNKNOWN); 730 731 final int maxChargingMicroAmp = intent.getIntExtra(EXTRA_MAX_CHARGING_CURRENT, -1); 732 int maxChargingMicroVolt = intent.getIntExtra(EXTRA_MAX_CHARGING_VOLTAGE, -1); 733 final int maxChargingMicroWatt; 734 735 if (maxChargingMicroVolt <= 0) { 736 maxChargingMicroVolt = DEFAULT_CHARGING_VOLTAGE_MICRO_VOLT; 737 } 738 if (maxChargingMicroAmp > 0) { 739 // Calculating muW = muA * muV / (10^6 mu^2 / mu); splitting up the divisor 740 // to maintain precision equally on both factors. 741 maxChargingMicroWatt = (maxChargingMicroAmp / 1000) 742 * (maxChargingMicroVolt / 1000); 743 } else { 744 maxChargingMicroWatt = -1; 745 } 746 final Message msg = mHandler.obtainMessage( 747 MSG_BATTERY_UPDATE, new BatteryStatus(status, level, plugged, health, 748 maxChargingMicroWatt)); 749 mHandler.sendMessage(msg); 750 } else if (TelephonyIntents.ACTION_SIM_STATE_CHANGED.equals(action)) { 751 SimData args = SimData.fromIntent(intent); 752 if (DEBUG_SIM_STATES) { 753 Log.v(TAG, "action " + action 754 + " state: " + intent.getStringExtra(IccCardConstants.INTENT_KEY_ICC_STATE) 755 + " slotId: " + args.slotId + " subid: " + args.subId); 756 } 757 mHandler.obtainMessage(MSG_SIM_STATE_CHANGE, args.subId, args.slotId, args.simState) 758 .sendToTarget(); 759 } else if (AudioManager.RINGER_MODE_CHANGED_ACTION.equals(action)) { 760 mHandler.sendMessage(mHandler.obtainMessage(MSG_RINGER_MODE_CHANGED, 761 intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE, -1), 0)); 762 } else if (TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(action)) { 763 String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE); 764 mHandler.sendMessage(mHandler.obtainMessage(MSG_PHONE_STATE_CHANGED, state)); 765 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) { 766 mHandler.sendEmptyMessage(MSG_AIRPLANE_MODE_CHANGED); 767 } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) { 768 dispatchBootCompleted(); 769 } else if (TelephonyIntents.ACTION_SERVICE_STATE_CHANGED.equals(action)) { 770 ServiceState serviceState = ServiceState.newFromBundle(intent.getExtras()); 771 int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, 772 SubscriptionManager.INVALID_SUBSCRIPTION_ID); 773 if (DEBUG) { 774 Log.v(TAG, "action " + action + " serviceState=" + serviceState + " subId=" 775 + subId); 776 } 777 mHandler.sendMessage( 778 mHandler.obtainMessage(MSG_SERVICE_STATE_CHANGE, subId, 0, serviceState)); 779 } 780 } 781 }; 782 783 private final BroadcastReceiver mBroadcastAllReceiver = new BroadcastReceiver() { 784 785 @Override 786 public void onReceive(Context context, Intent intent) { 787 final String action = intent.getAction(); 788 if (AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED.equals(action)) { 789 mHandler.sendEmptyMessage(MSG_TIME_UPDATE); 790 } else if (Intent.ACTION_USER_INFO_CHANGED.equals(action)) { 791 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_INFO_CHANGED, 792 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, getSendingUserId()), 0)); 793 } else if (ACTION_FACE_UNLOCK_STARTED.equals(action)) { 794 Trace.beginSection("KeyguardUpdateMonitor.mBroadcastAllReceiver#onReceive ACTION_FACE_UNLOCK_STARTED"); 795 mHandler.sendMessage(mHandler.obtainMessage(MSG_FACE_UNLOCK_STATE_CHANGED, 1, 796 getSendingUserId())); 797 Trace.endSection(); 798 } else if (ACTION_FACE_UNLOCK_STOPPED.equals(action)) { 799 mHandler.sendMessage(mHandler.obtainMessage(MSG_FACE_UNLOCK_STATE_CHANGED, 0, 800 getSendingUserId())); 801 } else if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED 802 .equals(action)) { 803 mHandler.sendEmptyMessage(MSG_DPM_STATE_CHANGED); 804 } else if (ACTION_USER_UNLOCKED.equals(action)) { 805 mHandler.sendEmptyMessage(MSG_USER_UNLOCKED); 806 } 807 } 808 }; 809 810 private final FingerprintManager.LockoutResetCallback mLockoutResetCallback 811 = new FingerprintManager.LockoutResetCallback() { 812 @Override 813 public void onLockoutReset() { 814 handleFingerprintLockoutReset(); 815 } 816 }; 817 818 private FingerprintManager.AuthenticationCallback mAuthenticationCallback 819 = new AuthenticationCallback() { 820 821 @Override 822 public void onAuthenticationFailed() { 823 handleFingerprintAuthFailed(); 824 }; 825 826 @Override 827 public void onAuthenticationSucceeded(AuthenticationResult result) { 828 Trace.beginSection("KeyguardUpdateMonitor#onAuthenticationSucceeded"); 829 handleFingerprintAuthenticated(result.getUserId()); 830 Trace.endSection(); 831 } 832 833 @Override 834 public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { 835 handleFingerprintHelp(helpMsgId, helpString.toString()); 836 } 837 838 @Override 839 public void onAuthenticationError(int errMsgId, CharSequence errString) { 840 handleFingerprintError(errMsgId, errString.toString()); 841 } 842 843 @Override 844 public void onAuthenticationAcquired(int acquireInfo) { 845 handleFingerprintAcquired(acquireInfo); 846 } 847 }; 848 private CancellationSignal mFingerprintCancelSignal; 849 private FingerprintManager mFpm; 850 851 /** 852 * When we receive a 853 * {@link com.android.internal.telephony.TelephonyIntents#ACTION_SIM_STATE_CHANGED} broadcast, 854 * and then pass a result via our handler to {@link KeyguardUpdateMonitor#handleSimStateChange}, 855 * we need a single object to pass to the handler. This class helps decode 856 * the intent and provide a {@link SimCard.State} result. 857 */ 858 private static class SimData { 859 public State simState; 860 public int slotId; 861 public int subId; 862 SimData(State state, int slot, int id)863 SimData(State state, int slot, int id) { 864 simState = state; 865 slotId = slot; 866 subId = id; 867 } 868 fromIntent(Intent intent)869 static SimData fromIntent(Intent intent) { 870 State state; 871 if (!TelephonyIntents.ACTION_SIM_STATE_CHANGED.equals(intent.getAction())) { 872 throw new IllegalArgumentException("only handles intent ACTION_SIM_STATE_CHANGED"); 873 } 874 String stateExtra = intent.getStringExtra(IccCardConstants.INTENT_KEY_ICC_STATE); 875 int slotId = intent.getIntExtra(PhoneConstants.SLOT_KEY, 0); 876 int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, 877 SubscriptionManager.INVALID_SUBSCRIPTION_ID); 878 if (IccCardConstants.INTENT_VALUE_ICC_ABSENT.equals(stateExtra)) { 879 final String absentReason = intent 880 .getStringExtra(IccCardConstants.INTENT_KEY_LOCKED_REASON); 881 882 if (IccCardConstants.INTENT_VALUE_ABSENT_ON_PERM_DISABLED.equals( 883 absentReason)) { 884 state = IccCardConstants.State.PERM_DISABLED; 885 } else { 886 state = IccCardConstants.State.ABSENT; 887 } 888 } else if (IccCardConstants.INTENT_VALUE_ICC_READY.equals(stateExtra)) { 889 state = IccCardConstants.State.READY; 890 } else if (IccCardConstants.INTENT_VALUE_ICC_LOCKED.equals(stateExtra)) { 891 final String lockedReason = intent 892 .getStringExtra(IccCardConstants.INTENT_KEY_LOCKED_REASON); 893 if (IccCardConstants.INTENT_VALUE_LOCKED_ON_PIN.equals(lockedReason)) { 894 state = IccCardConstants.State.PIN_REQUIRED; 895 } else if (IccCardConstants.INTENT_VALUE_LOCKED_ON_PUK.equals(lockedReason)) { 896 state = IccCardConstants.State.PUK_REQUIRED; 897 } else { 898 state = IccCardConstants.State.UNKNOWN; 899 } 900 } else if (IccCardConstants.INTENT_VALUE_LOCKED_NETWORK.equals(stateExtra)) { 901 state = IccCardConstants.State.NETWORK_LOCKED; 902 } else if (IccCardConstants.INTENT_VALUE_ICC_LOADED.equals(stateExtra) 903 || IccCardConstants.INTENT_VALUE_ICC_IMSI.equals(stateExtra)) { 904 // This is required because telephony doesn't return to "READY" after 905 // these state transitions. See bug 7197471. 906 state = IccCardConstants.State.READY; 907 } else { 908 state = IccCardConstants.State.UNKNOWN; 909 } 910 return new SimData(state, slotId, subId); 911 } 912 913 @Override toString()914 public String toString() { 915 return "SimData{state=" + simState + ",slotId=" + slotId + ",subId=" + subId + "}"; 916 } 917 } 918 919 public static class BatteryStatus { 920 public static final int CHARGING_UNKNOWN = -1; 921 public static final int CHARGING_SLOWLY = 0; 922 public static final int CHARGING_REGULAR = 1; 923 public static final int CHARGING_FAST = 2; 924 925 public final int status; 926 public final int level; 927 public final int plugged; 928 public final int health; 929 public final int maxChargingWattage; BatteryStatus(int status, int level, int plugged, int health, int maxChargingWattage)930 public BatteryStatus(int status, int level, int plugged, int health, 931 int maxChargingWattage) { 932 this.status = status; 933 this.level = level; 934 this.plugged = plugged; 935 this.health = health; 936 this.maxChargingWattage = maxChargingWattage; 937 } 938 939 /** 940 * Determine whether the device is plugged in (USB, power, or wireless). 941 * @return true if the device is plugged in. 942 */ isPluggedIn()943 public boolean isPluggedIn() { 944 return plugged == BatteryManager.BATTERY_PLUGGED_AC 945 || plugged == BatteryManager.BATTERY_PLUGGED_USB 946 || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS; 947 } 948 949 /** 950 * Whether or not the device is charged. Note that some devices never return 100% for 951 * battery level, so this allows either battery level or status to determine if the 952 * battery is charged. 953 * @return true if the device is charged 954 */ isCharged()955 public boolean isCharged() { 956 return status == BATTERY_STATUS_FULL || level >= 100; 957 } 958 959 /** 960 * Whether battery is low and needs to be charged. 961 * @return true if battery is low 962 */ isBatteryLow()963 public boolean isBatteryLow() { 964 return level < LOW_BATTERY_THRESHOLD; 965 } 966 getChargingSpeed(int slowThreshold, int fastThreshold)967 public final int getChargingSpeed(int slowThreshold, int fastThreshold) { 968 return maxChargingWattage <= 0 ? CHARGING_UNKNOWN : 969 maxChargingWattage < slowThreshold ? CHARGING_SLOWLY : 970 maxChargingWattage > fastThreshold ? CHARGING_FAST : 971 CHARGING_REGULAR; 972 } 973 } 974 975 public class StrongAuthTracker extends LockPatternUtils.StrongAuthTracker { StrongAuthTracker(Context context)976 public StrongAuthTracker(Context context) { 977 super(context); 978 } 979 isUnlockingWithFingerprintAllowed()980 public boolean isUnlockingWithFingerprintAllowed() { 981 int userId = getCurrentUser(); 982 return isFingerprintAllowedForUser(userId); 983 } 984 hasUserAuthenticatedSinceBoot()985 public boolean hasUserAuthenticatedSinceBoot() { 986 int userId = getCurrentUser(); 987 return (getStrongAuthForUser(userId) 988 & STRONG_AUTH_REQUIRED_AFTER_BOOT) == 0; 989 } 990 991 @Override onStrongAuthRequiredChanged(int userId)992 public void onStrongAuthRequiredChanged(int userId) { 993 notifyStrongAuthStateChanged(userId); 994 } 995 } 996 getInstance(Context context)997 public static KeyguardUpdateMonitor getInstance(Context context) { 998 if (sInstance == null) { 999 sInstance = new KeyguardUpdateMonitor(context); 1000 } 1001 return sInstance; 1002 } 1003 handleStartedWakingUp()1004 protected void handleStartedWakingUp() { 1005 Trace.beginSection("KeyguardUpdateMonitor#handleStartedWakingUp"); 1006 updateFingerprintListeningState(); 1007 final int count = mCallbacks.size(); 1008 for (int i = 0; i < count; i++) { 1009 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1010 if (cb != null) { 1011 cb.onStartedWakingUp(); 1012 } 1013 } 1014 Trace.endSection(); 1015 } 1016 handleStartedGoingToSleep(int arg1)1017 protected void handleStartedGoingToSleep(int arg1) { 1018 clearFingerprintRecognized(); 1019 final int count = mCallbacks.size(); 1020 for (int i = 0; i < count; i++) { 1021 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1022 if (cb != null) { 1023 cb.onStartedGoingToSleep(arg1); 1024 } 1025 } 1026 mGoingToSleep = true; 1027 updateFingerprintListeningState(); 1028 } 1029 handleFinishedGoingToSleep(int arg1)1030 protected void handleFinishedGoingToSleep(int arg1) { 1031 mGoingToSleep = false; 1032 final int count = mCallbacks.size(); 1033 for (int i = 0; i < count; i++) { 1034 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1035 if (cb != null) { 1036 cb.onFinishedGoingToSleep(arg1); 1037 } 1038 } 1039 updateFingerprintListeningState(); 1040 } 1041 handleScreenTurnedOn()1042 private void handleScreenTurnedOn() { 1043 final int count = mCallbacks.size(); 1044 for (int i = 0; i < count; i++) { 1045 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1046 if (cb != null) { 1047 cb.onScreenTurnedOn(); 1048 } 1049 } 1050 } 1051 handleScreenTurnedOff()1052 private void handleScreenTurnedOff() { 1053 mHardwareUnavailableRetryCount = 0; 1054 final int count = mCallbacks.size(); 1055 for (int i = 0; i < count; i++) { 1056 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1057 if (cb != null) { 1058 cb.onScreenTurnedOff(); 1059 } 1060 } 1061 } 1062 handleDreamingStateChanged(int dreamStart)1063 private void handleDreamingStateChanged(int dreamStart) { 1064 final int count = mCallbacks.size(); 1065 mIsDreaming = dreamStart == 1; 1066 for (int i = 0; i < count; i++) { 1067 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1068 if (cb != null) { 1069 cb.onDreamingStateChanged(mIsDreaming); 1070 } 1071 } 1072 updateFingerprintListeningState(); 1073 } 1074 1075 /** 1076 * IMPORTANT: Must be called from UI thread. 1077 */ dispatchSetBackground(Bitmap bmp)1078 public void dispatchSetBackground(Bitmap bmp) { 1079 if (DEBUG) Log.d(TAG, "dispatchSetBackground"); 1080 final int count = mCallbacks.size(); 1081 for (int i = 0; i < count; i++) { 1082 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1083 if (cb != null) { 1084 cb.onSetBackground(bmp); 1085 } 1086 } 1087 } 1088 handleUserInfoChanged(int userId)1089 private void handleUserInfoChanged(int userId) { 1090 for (int i = 0; i < mCallbacks.size(); i++) { 1091 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1092 if (cb != null) { 1093 cb.onUserInfoChanged(userId); 1094 } 1095 } 1096 } 1097 handleUserUnlocked()1098 private void handleUserUnlocked() { 1099 mNeedsSlowUnlockTransition = resolveNeedsSlowUnlockTransition(); 1100 for (int i = 0; i < mCallbacks.size(); i++) { 1101 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1102 if (cb != null) { 1103 cb.onUserUnlocked(); 1104 } 1105 } 1106 } 1107 KeyguardUpdateMonitor(Context context)1108 private KeyguardUpdateMonitor(Context context) { 1109 mContext = context; 1110 mSubscriptionManager = SubscriptionManager.from(context); 1111 mDeviceProvisioned = isDeviceProvisionedInSettingsDb(); 1112 mStrongAuthTracker = new StrongAuthTracker(context); 1113 1114 // Since device can't be un-provisioned, we only need to register a content observer 1115 // to update mDeviceProvisioned when we are... 1116 if (!mDeviceProvisioned) { 1117 watchForDeviceProvisioning(); 1118 } 1119 1120 // Take a guess at initial SIM state, battery status and PLMN until we get an update 1121 mBatteryStatus = new BatteryStatus(BATTERY_STATUS_UNKNOWN, 100, 0, 0, 0); 1122 1123 // Watch for interesting updates 1124 final IntentFilter filter = new IntentFilter(); 1125 filter.addAction(Intent.ACTION_TIME_TICK); 1126 filter.addAction(Intent.ACTION_TIME_CHANGED); 1127 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 1128 filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); 1129 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED); 1130 filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED); 1131 filter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED); 1132 filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED); 1133 filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); 1134 context.registerReceiver(mBroadcastReceiver, filter); 1135 1136 final IntentFilter bootCompleteFilter = new IntentFilter(); 1137 bootCompleteFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 1138 bootCompleteFilter.addAction(Intent.ACTION_BOOT_COMPLETED); 1139 context.registerReceiver(mBroadcastReceiver, bootCompleteFilter); 1140 1141 final IntentFilter allUserFilter = new IntentFilter(); 1142 allUserFilter.addAction(Intent.ACTION_USER_INFO_CHANGED); 1143 allUserFilter.addAction(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED); 1144 allUserFilter.addAction(ACTION_FACE_UNLOCK_STARTED); 1145 allUserFilter.addAction(ACTION_FACE_UNLOCK_STOPPED); 1146 allUserFilter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED); 1147 allUserFilter.addAction(ACTION_USER_UNLOCKED); 1148 context.registerReceiverAsUser(mBroadcastAllReceiver, UserHandle.ALL, allUserFilter, 1149 null, null); 1150 1151 mSubscriptionManager.addOnSubscriptionsChangedListener(mSubscriptionListener); 1152 try { 1153 ActivityManager.getService().registerUserSwitchObserver( 1154 new UserSwitchObserver() { 1155 @Override 1156 public void onUserSwitching(int newUserId, IRemoteCallback reply) { 1157 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_SWITCHING, 1158 newUserId, 0, reply)); 1159 } 1160 @Override 1161 public void onUserSwitchComplete(int newUserId) throws RemoteException { 1162 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_SWITCH_COMPLETE, 1163 newUserId, 0)); 1164 } 1165 }, TAG); 1166 } catch (RemoteException e) { 1167 e.rethrowAsRuntimeException(); 1168 } 1169 1170 mTrustManager = (TrustManager) context.getSystemService(Context.TRUST_SERVICE); 1171 mTrustManager.registerTrustListener(this); 1172 mLockPatternUtils = new LockPatternUtils(context); 1173 mLockPatternUtils.registerStrongAuthTracker(mStrongAuthTracker); 1174 1175 mDreamManager = IDreamManager.Stub.asInterface( 1176 ServiceManager.getService(DreamService.DREAM_SERVICE)); 1177 1178 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) { 1179 mFpm = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE); 1180 } 1181 updateFingerprintListeningState(); 1182 if (mFpm != null) { 1183 mFpm.addLockoutResetCallback(mLockoutResetCallback); 1184 } 1185 1186 SystemServicesProxy.getInstance(mContext).registerTaskStackListener(mTaskStackListener); 1187 mUserManager = context.getSystemService(UserManager.class); 1188 } 1189 updateFingerprintListeningState()1190 private void updateFingerprintListeningState() { 1191 // If this message exists, we should not authenticate again until this message is 1192 // consumed by the handler 1193 if (mHandler.hasMessages(MSG_FINGERPRINT_AUTHENTICATION_CONTINUE)) { 1194 return; 1195 } 1196 mHandler.removeCallbacks(mRetryFingerprintAuthentication); 1197 boolean shouldListenForFingerprint = shouldListenForFingerprint(); 1198 if (mFingerprintRunningState == FINGERPRINT_STATE_RUNNING && !shouldListenForFingerprint) { 1199 stopListeningForFingerprint(); 1200 } else if (mFingerprintRunningState != FINGERPRINT_STATE_RUNNING 1201 && shouldListenForFingerprint) { 1202 startListeningForFingerprint(); 1203 } 1204 } 1205 shouldListenForFingerprintAssistant()1206 private boolean shouldListenForFingerprintAssistant() { 1207 return mAssistantVisible && mKeyguardOccluded 1208 && !mUserFingerprintAuthenticated.get(getCurrentUser(), false) 1209 && !mUserHasTrust.get(getCurrentUser(), false); 1210 } 1211 shouldListenForFingerprint()1212 private boolean shouldListenForFingerprint() { 1213 return (mKeyguardIsVisible || !mDeviceInteractive || 1214 (mBouncer && !mKeyguardGoingAway) || mGoingToSleep || 1215 shouldListenForFingerprintAssistant() || (mKeyguardOccluded && mIsDreaming)) 1216 && !mSwitchingUser && !isFingerprintDisabled(getCurrentUser()) 1217 && !mKeyguardGoingAway; 1218 } 1219 startListeningForFingerprint()1220 private void startListeningForFingerprint() { 1221 if (mFingerprintRunningState == FINGERPRINT_STATE_CANCELLING) { 1222 setFingerprintRunningState(FINGERPRINT_STATE_CANCELLING_RESTARTING); 1223 return; 1224 } 1225 if (DEBUG) Log.v(TAG, "startListeningForFingerprint()"); 1226 int userId = ActivityManager.getCurrentUser(); 1227 if (isUnlockWithFingerprintPossible(userId)) { 1228 if (mFingerprintCancelSignal != null) { 1229 mFingerprintCancelSignal.cancel(); 1230 } 1231 mFingerprintCancelSignal = new CancellationSignal(); 1232 mFpm.authenticate(null, mFingerprintCancelSignal, 0, mAuthenticationCallback, null, userId); 1233 setFingerprintRunningState(FINGERPRINT_STATE_RUNNING); 1234 } 1235 } 1236 isUnlockWithFingerprintPossible(int userId)1237 public boolean isUnlockWithFingerprintPossible(int userId) { 1238 return mFpm != null && mFpm.isHardwareDetected() && !isFingerprintDisabled(userId) 1239 && mFpm.getEnrolledFingerprints(userId).size() > 0; 1240 } 1241 stopListeningForFingerprint()1242 private void stopListeningForFingerprint() { 1243 if (DEBUG) Log.v(TAG, "stopListeningForFingerprint()"); 1244 if (mFingerprintRunningState == FINGERPRINT_STATE_RUNNING) { 1245 if (mFingerprintCancelSignal != null) { 1246 mFingerprintCancelSignal.cancel(); 1247 mFingerprintCancelSignal = null; 1248 } 1249 setFingerprintRunningState(FINGERPRINT_STATE_CANCELLING); 1250 } 1251 if (mFingerprintRunningState == FINGERPRINT_STATE_CANCELLING_RESTARTING) { 1252 setFingerprintRunningState(FINGERPRINT_STATE_CANCELLING); 1253 } 1254 } 1255 isDeviceProvisionedInSettingsDb()1256 private boolean isDeviceProvisionedInSettingsDb() { 1257 return Settings.Global.getInt(mContext.getContentResolver(), 1258 Settings.Global.DEVICE_PROVISIONED, 0) != 0; 1259 } 1260 watchForDeviceProvisioning()1261 private void watchForDeviceProvisioning() { 1262 mDeviceProvisionedObserver = new ContentObserver(mHandler) { 1263 @Override 1264 public void onChange(boolean selfChange) { 1265 super.onChange(selfChange); 1266 mDeviceProvisioned = isDeviceProvisionedInSettingsDb(); 1267 if (mDeviceProvisioned) { 1268 mHandler.sendEmptyMessage(MSG_DEVICE_PROVISIONED); 1269 } 1270 if (DEBUG) Log.d(TAG, "DEVICE_PROVISIONED state = " + mDeviceProvisioned); 1271 } 1272 }; 1273 1274 mContext.getContentResolver().registerContentObserver( 1275 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), 1276 false, mDeviceProvisionedObserver); 1277 1278 // prevent a race condition between where we check the flag and where we register the 1279 // observer by grabbing the value once again... 1280 boolean provisioned = isDeviceProvisionedInSettingsDb(); 1281 if (provisioned != mDeviceProvisioned) { 1282 mDeviceProvisioned = provisioned; 1283 if (mDeviceProvisioned) { 1284 mHandler.sendEmptyMessage(MSG_DEVICE_PROVISIONED); 1285 } 1286 } 1287 } 1288 1289 /** 1290 * Update the state whether Keyguard currently has a lockscreen wallpaper. 1291 * 1292 * @param hasLockscreenWallpaper Whether Keyguard has a lockscreen wallpaper. 1293 */ setHasLockscreenWallpaper(boolean hasLockscreenWallpaper)1294 public void setHasLockscreenWallpaper(boolean hasLockscreenWallpaper) { 1295 if (hasLockscreenWallpaper != mHasLockscreenWallpaper) { 1296 mHasLockscreenWallpaper = hasLockscreenWallpaper; 1297 for (int i = mCallbacks.size() - 1; i >= 0; i--) { 1298 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1299 if (cb != null) { 1300 cb.onHasLockscreenWallpaperChanged(hasLockscreenWallpaper); 1301 } 1302 } 1303 } 1304 } 1305 1306 /** 1307 * @return Whether Keyguard has a lockscreen wallpaper. 1308 */ hasLockscreenWallpaper()1309 public boolean hasLockscreenWallpaper() { 1310 return mHasLockscreenWallpaper; 1311 } 1312 1313 /** 1314 * Handle {@link #MSG_DPM_STATE_CHANGED} 1315 */ handleDevicePolicyManagerStateChanged()1316 protected void handleDevicePolicyManagerStateChanged() { 1317 updateFingerprintListeningState(); 1318 for (int i = mCallbacks.size() - 1; i >= 0; i--) { 1319 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1320 if (cb != null) { 1321 cb.onDevicePolicyManagerStateChanged(); 1322 } 1323 } 1324 } 1325 1326 /** 1327 * Handle {@link #MSG_USER_SWITCHING} 1328 */ handleUserSwitching(int userId, IRemoteCallback reply)1329 protected void handleUserSwitching(int userId, IRemoteCallback reply) { 1330 for (int i = 0; i < mCallbacks.size(); i++) { 1331 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1332 if (cb != null) { 1333 cb.onUserSwitching(userId); 1334 } 1335 } 1336 try { 1337 reply.sendResult(null); 1338 } catch (RemoteException e) { 1339 } 1340 } 1341 1342 /** 1343 * Handle {@link #MSG_USER_SWITCH_COMPLETE} 1344 */ handleUserSwitchComplete(int userId)1345 protected void handleUserSwitchComplete(int userId) { 1346 for (int i = 0; i < mCallbacks.size(); i++) { 1347 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1348 if (cb != null) { 1349 cb.onUserSwitchComplete(userId); 1350 } 1351 } 1352 } 1353 1354 /** 1355 * This is exposed since {@link Intent#ACTION_BOOT_COMPLETED} is not sticky. If 1356 * keyguard crashes sometime after boot, then it will never receive this 1357 * broadcast and hence not handle the event. This method is ultimately called by 1358 * PhoneWindowManager in this case. 1359 */ dispatchBootCompleted()1360 public void dispatchBootCompleted() { 1361 mHandler.sendEmptyMessage(MSG_BOOT_COMPLETED); 1362 } 1363 1364 /** 1365 * Handle {@link #MSG_BOOT_COMPLETED} 1366 */ handleBootCompleted()1367 protected void handleBootCompleted() { 1368 if (mBootCompleted) return; 1369 mBootCompleted = true; 1370 for (int i = 0; i < mCallbacks.size(); i++) { 1371 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1372 if (cb != null) { 1373 cb.onBootCompleted(); 1374 } 1375 } 1376 } 1377 1378 /** 1379 * We need to store this state in the KeyguardUpdateMonitor since this class will not be 1380 * destroyed. 1381 */ hasBootCompleted()1382 public boolean hasBootCompleted() { 1383 return mBootCompleted; 1384 } 1385 1386 /** 1387 * Handle {@link #MSG_DEVICE_PROVISIONED} 1388 */ handleDeviceProvisioned()1389 protected void handleDeviceProvisioned() { 1390 for (int i = 0; i < mCallbacks.size(); i++) { 1391 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1392 if (cb != null) { 1393 cb.onDeviceProvisioned(); 1394 } 1395 } 1396 if (mDeviceProvisionedObserver != null) { 1397 // We don't need the observer anymore... 1398 mContext.getContentResolver().unregisterContentObserver(mDeviceProvisionedObserver); 1399 mDeviceProvisionedObserver = null; 1400 } 1401 } 1402 1403 /** 1404 * Handle {@link #MSG_PHONE_STATE_CHANGED} 1405 */ handlePhoneStateChanged(String newState)1406 protected void handlePhoneStateChanged(String newState) { 1407 if (DEBUG) Log.d(TAG, "handlePhoneStateChanged(" + newState + ")"); 1408 if (TelephonyManager.EXTRA_STATE_IDLE.equals(newState)) { 1409 mPhoneState = TelephonyManager.CALL_STATE_IDLE; 1410 } else if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(newState)) { 1411 mPhoneState = TelephonyManager.CALL_STATE_OFFHOOK; 1412 } else if (TelephonyManager.EXTRA_STATE_RINGING.equals(newState)) { 1413 mPhoneState = TelephonyManager.CALL_STATE_RINGING; 1414 } 1415 for (int i = 0; i < mCallbacks.size(); i++) { 1416 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1417 if (cb != null) { 1418 cb.onPhoneStateChanged(mPhoneState); 1419 } 1420 } 1421 } 1422 1423 /** 1424 * Handle {@link #MSG_RINGER_MODE_CHANGED} 1425 */ handleRingerModeChange(int mode)1426 protected void handleRingerModeChange(int mode) { 1427 if (DEBUG) Log.d(TAG, "handleRingerModeChange(" + mode + ")"); 1428 mRingMode = mode; 1429 for (int i = 0; i < mCallbacks.size(); i++) { 1430 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1431 if (cb != null) { 1432 cb.onRingerModeChanged(mode); 1433 } 1434 } 1435 } 1436 1437 /** 1438 * Handle {@link #MSG_TIME_UPDATE} 1439 */ handleTimeUpdate()1440 private void handleTimeUpdate() { 1441 if (DEBUG) Log.d(TAG, "handleTimeUpdate"); 1442 for (int i = 0; i < mCallbacks.size(); i++) { 1443 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1444 if (cb != null) { 1445 cb.onTimeChanged(); 1446 } 1447 } 1448 } 1449 1450 /** 1451 * Handle {@link #MSG_BATTERY_UPDATE} 1452 */ handleBatteryUpdate(BatteryStatus status)1453 private void handleBatteryUpdate(BatteryStatus status) { 1454 if (DEBUG) Log.d(TAG, "handleBatteryUpdate"); 1455 final boolean batteryUpdateInteresting = isBatteryUpdateInteresting(mBatteryStatus, status); 1456 mBatteryStatus = status; 1457 if (batteryUpdateInteresting) { 1458 for (int i = 0; i < mCallbacks.size(); i++) { 1459 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1460 if (cb != null) { 1461 cb.onRefreshBatteryInfo(status); 1462 } 1463 } 1464 } 1465 } 1466 1467 /** 1468 * Handle {@link #MSG_SIM_STATE_CHANGE} 1469 */ handleSimStateChange(int subId, int slotId, State state)1470 private void handleSimStateChange(int subId, int slotId, State state) { 1471 1472 if (DEBUG_SIM_STATES) { 1473 Log.d(TAG, "handleSimStateChange(subId=" + subId + ", slotId=" 1474 + slotId + ", state=" + state +")"); 1475 } 1476 1477 if (!SubscriptionManager.isValidSubscriptionId(subId)) { 1478 Log.w(TAG, "invalid subId in handleSimStateChange()"); 1479 return; 1480 } 1481 1482 SimData data = mSimDatas.get(subId); 1483 final boolean changed; 1484 if (data == null) { 1485 data = new SimData(state, slotId, subId); 1486 mSimDatas.put(subId, data); 1487 changed = true; // no data yet; force update 1488 } else { 1489 changed = (data.simState != state || data.subId != subId || data.slotId != slotId); 1490 data.simState = state; 1491 data.subId = subId; 1492 data.slotId = slotId; 1493 } 1494 if (changed && state != State.UNKNOWN) { 1495 for (int i = 0; i < mCallbacks.size(); i++) { 1496 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1497 if (cb != null) { 1498 cb.onSimStateChanged(subId, slotId, state); 1499 } 1500 } 1501 } 1502 } 1503 1504 /** 1505 * Handle {@link #MSG_SERVICE_STATE_CHANGE} 1506 */ handleServiceStateChange(int subId, ServiceState serviceState)1507 private void handleServiceStateChange(int subId, ServiceState serviceState) { 1508 if (DEBUG) { 1509 Log.d(TAG, 1510 "handleServiceStateChange(subId=" + subId + ", serviceState=" + serviceState); 1511 } 1512 1513 if (!SubscriptionManager.isValidSubscriptionId(subId)) { 1514 Log.w(TAG, "invalid subId in handleServiceStateChange()"); 1515 return; 1516 } 1517 1518 mServiceStates.put(subId, serviceState); 1519 1520 for (int j = 0; j < mCallbacks.size(); j++) { 1521 KeyguardUpdateMonitorCallback cb = mCallbacks.get(j).get(); 1522 if (cb != null) { 1523 cb.onRefreshCarrierInfo(); 1524 } 1525 } 1526 } 1527 1528 /** 1529 * Notifies that the visibility state of Keyguard has changed. 1530 * 1531 * <p>Needs to be called from the main thread. 1532 */ onKeyguardVisibilityChanged(boolean showing)1533 public void onKeyguardVisibilityChanged(boolean showing) { 1534 if (DEBUG) Log.d(TAG, "onKeyguardVisibilityChanged(" + showing + ")"); 1535 mKeyguardIsVisible = showing; 1536 for (int i = 0; i < mCallbacks.size(); i++) { 1537 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1538 if (cb != null) { 1539 cb.onKeyguardVisibilityChangedRaw(showing); 1540 } 1541 } 1542 updateFingerprintListeningState(); 1543 } 1544 1545 /** 1546 * Handle {@link #MSG_KEYGUARD_RESET} 1547 */ handleKeyguardReset()1548 private void handleKeyguardReset() { 1549 if (DEBUG) Log.d(TAG, "handleKeyguardReset"); 1550 updateFingerprintListeningState(); 1551 mNeedsSlowUnlockTransition = resolveNeedsSlowUnlockTransition(); 1552 } 1553 resolveNeedsSlowUnlockTransition()1554 private boolean resolveNeedsSlowUnlockTransition() { 1555 if (mUserManager.isUserUnlocked(getCurrentUser())) { 1556 return false; 1557 } 1558 Intent homeIntent = new Intent(Intent.ACTION_MAIN) 1559 .addCategory(Intent.CATEGORY_HOME); 1560 ResolveInfo resolveInfo = mContext.getPackageManager().resolveActivity(homeIntent, 1561 0 /* flags */); 1562 return FALLBACK_HOME_COMPONENT.equals(resolveInfo.getComponentInfo().getComponentName()); 1563 } 1564 1565 /** 1566 * Handle {@link #MSG_KEYGUARD_BOUNCER_CHANGED} 1567 * @see #sendKeyguardBouncerChanged(boolean) 1568 */ handleKeyguardBouncerChanged(int bouncer)1569 private void handleKeyguardBouncerChanged(int bouncer) { 1570 if (DEBUG) Log.d(TAG, "handleKeyguardBouncerChanged(" + bouncer + ")"); 1571 boolean isBouncer = (bouncer == 1); 1572 mBouncer = isBouncer; 1573 for (int i = 0; i < mCallbacks.size(); i++) { 1574 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1575 if (cb != null) { 1576 cb.onKeyguardBouncerChanged(isBouncer); 1577 } 1578 } 1579 updateFingerprintListeningState(); 1580 } 1581 1582 /** 1583 * Handle {@link #MSG_REPORT_EMERGENCY_CALL_ACTION} 1584 */ handleReportEmergencyCallAction()1585 private void handleReportEmergencyCallAction() { 1586 for (int i = 0; i < mCallbacks.size(); i++) { 1587 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); 1588 if (cb != null) { 1589 cb.onEmergencyCallAction(); 1590 } 1591 } 1592 } 1593 isBatteryUpdateInteresting(BatteryStatus old, BatteryStatus current)1594 private static boolean isBatteryUpdateInteresting(BatteryStatus old, BatteryStatus current) { 1595 final boolean nowPluggedIn = current.isPluggedIn(); 1596 final boolean wasPluggedIn = old.isPluggedIn(); 1597 final boolean stateChangedWhilePluggedIn = 1598 wasPluggedIn == true && nowPluggedIn == true 1599 && (old.status != current.status); 1600 1601 // change in plug state is always interesting 1602 if (wasPluggedIn != nowPluggedIn || stateChangedWhilePluggedIn) { 1603 return true; 1604 } 1605 1606 // change in battery level while plugged in 1607 if (nowPluggedIn && old.level != current.level) { 1608 return true; 1609 } 1610 1611 // change where battery needs charging 1612 if (!nowPluggedIn && current.isBatteryLow() && current.level != old.level) { 1613 return true; 1614 } 1615 1616 // change in charging current while plugged in 1617 if (nowPluggedIn && current.maxChargingWattage != old.maxChargingWattage) { 1618 return true; 1619 } 1620 1621 return false; 1622 } 1623 1624 /** 1625 * Remove the given observer's callback. 1626 * 1627 * @param callback The callback to remove 1628 */ removeCallback(KeyguardUpdateMonitorCallback callback)1629 public void removeCallback(KeyguardUpdateMonitorCallback callback) { 1630 if (DEBUG) Log.v(TAG, "*** unregister callback for " + callback); 1631 for (int i = mCallbacks.size() - 1; i >= 0; i--) { 1632 if (mCallbacks.get(i).get() == callback) { 1633 mCallbacks.remove(i); 1634 } 1635 } 1636 } 1637 1638 /** 1639 * Register to receive notifications about general keyguard information 1640 * (see {@link InfoCallback}. 1641 * @param callback The callback to register 1642 */ registerCallback(KeyguardUpdateMonitorCallback callback)1643 public void registerCallback(KeyguardUpdateMonitorCallback callback) { 1644 if (DEBUG) Log.v(TAG, "*** register callback for " + callback); 1645 // Prevent adding duplicate callbacks 1646 for (int i = 0; i < mCallbacks.size(); i++) { 1647 if (mCallbacks.get(i).get() == callback) { 1648 if (DEBUG) Log.e(TAG, "Object tried to add another callback", 1649 new Exception("Called by")); 1650 return; 1651 } 1652 } 1653 mCallbacks.add(new WeakReference<KeyguardUpdateMonitorCallback>(callback)); 1654 removeCallback(null); // remove unused references 1655 sendUpdates(callback); 1656 } 1657 isSwitchingUser()1658 public boolean isSwitchingUser() { 1659 return mSwitchingUser; 1660 } 1661 setSwitchingUser(boolean switching)1662 public void setSwitchingUser(boolean switching) { 1663 mSwitchingUser = switching; 1664 updateFingerprintListeningState(); 1665 } 1666 sendUpdates(KeyguardUpdateMonitorCallback callback)1667 private void sendUpdates(KeyguardUpdateMonitorCallback callback) { 1668 // Notify listener of the current state 1669 callback.onRefreshBatteryInfo(mBatteryStatus); 1670 callback.onTimeChanged(); 1671 callback.onRingerModeChanged(mRingMode); 1672 callback.onPhoneStateChanged(mPhoneState); 1673 callback.onRefreshCarrierInfo(); 1674 callback.onClockVisibilityChanged(); 1675 for (Entry<Integer, SimData> data : mSimDatas.entrySet()) { 1676 final SimData state = data.getValue(); 1677 callback.onSimStateChanged(state.subId, state.slotId, state.simState); 1678 } 1679 } 1680 sendKeyguardReset()1681 public void sendKeyguardReset() { 1682 mHandler.obtainMessage(MSG_KEYGUARD_RESET).sendToTarget(); 1683 } 1684 1685 /** 1686 * @see #handleKeyguardBouncerChanged(int) 1687 */ sendKeyguardBouncerChanged(boolean showingBouncer)1688 public void sendKeyguardBouncerChanged(boolean showingBouncer) { 1689 if (DEBUG) Log.d(TAG, "sendKeyguardBouncerChanged(" + showingBouncer + ")"); 1690 Message message = mHandler.obtainMessage(MSG_KEYGUARD_BOUNCER_CHANGED); 1691 message.arg1 = showingBouncer ? 1 : 0; 1692 message.sendToTarget(); 1693 } 1694 1695 /** 1696 * Report that the user successfully entered the SIM PIN or PUK/SIM PIN so we 1697 * have the information earlier than waiting for the intent 1698 * broadcast from the telephony code. 1699 * 1700 * NOTE: Because handleSimStateChange() invokes callbacks immediately without going 1701 * through mHandler, this *must* be called from the UI thread. 1702 */ reportSimUnlocked(int subId)1703 public void reportSimUnlocked(int subId) { 1704 if (DEBUG_SIM_STATES) Log.v(TAG, "reportSimUnlocked(subId=" + subId + ")"); 1705 int slotId = SubscriptionManager.getSlotIndex(subId); 1706 handleSimStateChange(subId, slotId, State.READY); 1707 } 1708 1709 /** 1710 * Report that the emergency call button has been pressed and the emergency dialer is 1711 * about to be displayed. 1712 * 1713 * @param bypassHandler runs immediately. 1714 * 1715 * NOTE: Must be called from UI thread if bypassHandler == true. 1716 */ reportEmergencyCallAction(boolean bypassHandler)1717 public void reportEmergencyCallAction(boolean bypassHandler) { 1718 if (!bypassHandler) { 1719 mHandler.obtainMessage(MSG_REPORT_EMERGENCY_CALL_ACTION).sendToTarget(); 1720 } else { 1721 handleReportEmergencyCallAction(); 1722 } 1723 } 1724 1725 /** 1726 * @return Whether the device is provisioned (whether they have gone through 1727 * the setup wizard) 1728 */ isDeviceProvisioned()1729 public boolean isDeviceProvisioned() { 1730 return mDeviceProvisioned; 1731 } 1732 clearFailedUnlockAttempts()1733 public void clearFailedUnlockAttempts() { 1734 mFailedAttempts.delete(sCurrentUser); 1735 } 1736 getFailedUnlockAttempts(int userId)1737 public int getFailedUnlockAttempts(int userId) { 1738 return mFailedAttempts.get(userId, 0); 1739 } 1740 reportFailedStrongAuthUnlockAttempt(int userId)1741 public void reportFailedStrongAuthUnlockAttempt(int userId) { 1742 mFailedAttempts.put(userId, getFailedUnlockAttempts(userId) + 1); 1743 } 1744 clearFingerprintRecognized()1745 public void clearFingerprintRecognized() { 1746 mUserFingerprintAuthenticated.clear(); 1747 mTrustManager.clearAllFingerprints(); 1748 } 1749 isSimPinVoiceSecure()1750 public boolean isSimPinVoiceSecure() { 1751 // TODO: only count SIMs that handle voice 1752 return isSimPinSecure(); 1753 } 1754 isSimPinSecure()1755 public boolean isSimPinSecure() { 1756 // True if any SIM is pin secure 1757 for (SubscriptionInfo info : getSubscriptionInfo(false /* forceReload */)) { 1758 if (isSimPinSecure(getSimState(info.getSubscriptionId()))) return true; 1759 } 1760 return false; 1761 } 1762 getSimState(int subId)1763 public State getSimState(int subId) { 1764 if (mSimDatas.containsKey(subId)) { 1765 return mSimDatas.get(subId).simState; 1766 } else { 1767 return State.UNKNOWN; 1768 } 1769 } 1770 1771 private final TaskStackListener mTaskStackListener = new TaskStackListener() { 1772 @Override 1773 public void onTaskStackChangedBackground() { 1774 try { 1775 ActivityManager.StackInfo info = ActivityManager.getService().getStackInfo( 1776 ActivityManager.StackId.ASSISTANT_STACK_ID); 1777 if (info == null) { 1778 return; 1779 } 1780 mHandler.sendMessage(mHandler.obtainMessage(MSG_ASSISTANT_STACK_CHANGED, 1781 info.visible)); 1782 } catch (RemoteException e) { 1783 Log.e(TAG, "unable to check task stack", e); 1784 } 1785 } 1786 }; 1787 1788 /** 1789 * @return true if and only if the state has changed for the specified {@code slotId} 1790 */ refreshSimState(int subId, int slotId)1791 private boolean refreshSimState(int subId, int slotId) { 1792 1793 // This is awful. It exists because there are two APIs for getting the SIM status 1794 // that don't return the complete set of values and have different types. In Keyguard we 1795 // need IccCardConstants, but TelephonyManager would only give us 1796 // TelephonyManager.SIM_STATE*, so we retrieve it manually. 1797 final TelephonyManager tele = TelephonyManager.from(mContext); 1798 int simState = tele.getSimState(slotId); 1799 State state; 1800 try { 1801 state = State.intToState(simState); 1802 } catch(IllegalArgumentException ex) { 1803 Log.w(TAG, "Unknown sim state: " + simState); 1804 state = State.UNKNOWN; 1805 } 1806 SimData data = mSimDatas.get(subId); 1807 final boolean changed; 1808 if (data == null) { 1809 data = new SimData(state, slotId, subId); 1810 mSimDatas.put(subId, data); 1811 changed = true; // no data yet; force update 1812 } else { 1813 changed = data.simState != state; 1814 data.simState = state; 1815 } 1816 return changed; 1817 } 1818 isSimPinSecure(IccCardConstants.State state)1819 public static boolean isSimPinSecure(IccCardConstants.State state) { 1820 final IccCardConstants.State simState = state; 1821 return (simState == IccCardConstants.State.PIN_REQUIRED 1822 || simState == IccCardConstants.State.PUK_REQUIRED 1823 || simState == IccCardConstants.State.PERM_DISABLED); 1824 } 1825 getCachedDisplayClientState()1826 public DisplayClientState getCachedDisplayClientState() { 1827 return mDisplayClientState; 1828 } 1829 1830 // TODO: use these callbacks elsewhere in place of the existing notifyScreen*() 1831 // (KeyguardViewMediator, KeyguardHostView) dispatchStartedWakingUp()1832 public void dispatchStartedWakingUp() { 1833 synchronized (this) { 1834 mDeviceInteractive = true; 1835 } 1836 mHandler.sendEmptyMessage(MSG_STARTED_WAKING_UP); 1837 } 1838 dispatchStartedGoingToSleep(int why)1839 public void dispatchStartedGoingToSleep(int why) { 1840 mHandler.sendMessage(mHandler.obtainMessage(MSG_STARTED_GOING_TO_SLEEP, why, 0)); 1841 } 1842 dispatchFinishedGoingToSleep(int why)1843 public void dispatchFinishedGoingToSleep(int why) { 1844 synchronized(this) { 1845 mDeviceInteractive = false; 1846 } 1847 mHandler.sendMessage(mHandler.obtainMessage(MSG_FINISHED_GOING_TO_SLEEP, why, 0)); 1848 } 1849 dispatchScreenTurnedOn()1850 public void dispatchScreenTurnedOn() { 1851 synchronized (this) { 1852 mScreenOn = true; 1853 } 1854 mHandler.sendEmptyMessage(MSG_SCREEN_TURNED_ON); 1855 } 1856 dispatchScreenTurnedOff()1857 public void dispatchScreenTurnedOff() { 1858 synchronized(this) { 1859 mScreenOn = false; 1860 } 1861 mHandler.sendEmptyMessage(MSG_SCREEN_TURNED_OFF); 1862 } 1863 dispatchDreamingStarted()1864 public void dispatchDreamingStarted() { 1865 mHandler.sendMessage(mHandler.obtainMessage(MSG_DREAMING_STATE_CHANGED, 1, 0)); 1866 } 1867 dispatchDreamingStopped()1868 public void dispatchDreamingStopped() { 1869 mHandler.sendMessage(mHandler.obtainMessage(MSG_DREAMING_STATE_CHANGED, 0, 0)); 1870 } 1871 isDeviceInteractive()1872 public boolean isDeviceInteractive() { 1873 return mDeviceInteractive; 1874 } 1875 isGoingToSleep()1876 public boolean isGoingToSleep() { 1877 return mGoingToSleep; 1878 } 1879 1880 /** 1881 * Find the next SubscriptionId for a SIM in the given state, favoring lower slot numbers first. 1882 * @param state 1883 * @return subid or {@link SubscriptionManager#INVALID_SUBSCRIPTION_ID} if none found 1884 */ getNextSubIdForState(State state)1885 public int getNextSubIdForState(State state) { 1886 List<SubscriptionInfo> list = getSubscriptionInfo(false /* forceReload */); 1887 int resultId = SubscriptionManager.INVALID_SUBSCRIPTION_ID; 1888 int bestSlotId = Integer.MAX_VALUE; // Favor lowest slot first 1889 for (int i = 0; i < list.size(); i++) { 1890 final SubscriptionInfo info = list.get(i); 1891 final int id = info.getSubscriptionId(); 1892 int slotId = SubscriptionManager.getSlotIndex(id); 1893 if (state == getSimState(id) && bestSlotId > slotId ) { 1894 resultId = id; 1895 bestSlotId = slotId; 1896 } 1897 } 1898 return resultId; 1899 } 1900 getSubscriptionInfoForSubId(int subId)1901 public SubscriptionInfo getSubscriptionInfoForSubId(int subId) { 1902 List<SubscriptionInfo> list = getSubscriptionInfo(false /* forceReload */); 1903 for (int i = 0; i < list.size(); i++) { 1904 SubscriptionInfo info = list.get(i); 1905 if (subId == info.getSubscriptionId()) return info; 1906 } 1907 return null; // not found 1908 } 1909 dump(FileDescriptor fd, PrintWriter pw, String[] args)1910 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1911 pw.println("KeyguardUpdateMonitor state:"); 1912 pw.println(" SIM States:"); 1913 for (SimData data : mSimDatas.values()) { 1914 pw.println(" " + data.toString()); 1915 } 1916 pw.println(" Subs:"); 1917 if (mSubscriptionInfo != null) { 1918 for (int i = 0; i < mSubscriptionInfo.size(); i++) { 1919 pw.println(" " + mSubscriptionInfo.get(i)); 1920 } 1921 } 1922 pw.println(" Service states:"); 1923 for (int subId : mServiceStates.keySet()) { 1924 pw.println(" " + subId + "=" + mServiceStates.get(subId)); 1925 } 1926 if (mFpm != null && mFpm.isHardwareDetected()) { 1927 final int userId = ActivityManager.getCurrentUser(); 1928 final int strongAuthFlags = mStrongAuthTracker.getStrongAuthForUser(userId); 1929 pw.println(" Fingerprint state (user=" + userId + ")"); 1930 pw.println(" allowed=" + isUnlockingWithFingerprintAllowed()); 1931 pw.println(" auth'd=" + mUserFingerprintAuthenticated.get(userId)); 1932 pw.println(" authSinceBoot=" 1933 + getStrongAuthTracker().hasUserAuthenticatedSinceBoot()); 1934 pw.println(" disabled(DPM)=" + isFingerprintDisabled(userId)); 1935 pw.println(" possible=" + isUnlockWithFingerprintPossible(userId)); 1936 pw.println(" strongAuthFlags=" + Integer.toHexString(strongAuthFlags)); 1937 pw.println(" trustManaged=" + getUserTrustIsManaged(userId)); 1938 } 1939 } 1940 } 1941