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