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.app.WindowConfiguration.ACTIVITY_TYPE_ASSISTANT;
20 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
21 import static android.content.Intent.ACTION_USER_UNLOCKED;
22 import static android.os.BatteryManager.BATTERY_HEALTH_UNKNOWN;
23 import static android.os.BatteryManager.BATTERY_STATUS_FULL;
24 import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN;
25 import static android.os.BatteryManager.EXTRA_HEALTH;
26 import static android.os.BatteryManager.EXTRA_LEVEL;
27 import static android.os.BatteryManager.EXTRA_MAX_CHARGING_CURRENT;
28 import static android.os.BatteryManager.EXTRA_MAX_CHARGING_VOLTAGE;
29 import static android.os.BatteryManager.EXTRA_PLUGGED;
30 import static android.os.BatteryManager.EXTRA_STATUS;
31 import static android.telephony.PhoneStateListener.LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE;
32 
33 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_BOOT;
34 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
35 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_LOCKOUT;
36 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_TIMEOUT;
37 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN;
38 
39 import android.annotation.AnyThread;
40 import android.annotation.MainThread;
41 import android.app.ActivityManager;
42 import android.app.ActivityTaskManager;
43 import android.app.AlarmManager;
44 import android.app.Instrumentation;
45 import android.app.PendingIntent;
46 import android.app.UserSwitchObserver;
47 import android.app.admin.DevicePolicyManager;
48 import android.app.trust.TrustManager;
49 import android.content.BroadcastReceiver;
50 import android.content.ComponentName;
51 import android.content.Context;
52 import android.content.Intent;
53 import android.content.IntentFilter;
54 import android.content.pm.IPackageManager;
55 import android.content.pm.PackageManager;
56 import android.content.pm.ResolveInfo;
57 import android.database.ContentObserver;
58 import android.hardware.biometrics.BiometricManager;
59 import android.hardware.biometrics.BiometricSourceType;
60 import android.hardware.biometrics.IBiometricEnabledOnKeyguardCallback;
61 import android.hardware.face.FaceManager;
62 import android.hardware.fingerprint.FingerprintManager;
63 import android.hardware.fingerprint.FingerprintManager.AuthenticationCallback;
64 import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
65 import android.media.AudioManager;
66 import android.os.BatteryManager;
67 import android.os.CancellationSignal;
68 import android.os.Handler;
69 import android.os.IRemoteCallback;
70 import android.os.Looper;
71 import android.os.Message;
72 import android.os.RemoteException;
73 import android.os.ServiceManager;
74 import android.os.Trace;
75 import android.os.UserHandle;
76 import android.os.UserManager;
77 import android.provider.Settings;
78 import android.service.dreams.DreamService;
79 import android.service.dreams.IDreamManager;
80 import android.telephony.CarrierConfigManager;
81 import android.telephony.PhoneStateListener;
82 import android.telephony.ServiceState;
83 import android.telephony.SubscriptionInfo;
84 import android.telephony.SubscriptionManager;
85 import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener;
86 import android.telephony.TelephonyManager;
87 import android.util.Log;
88 import android.util.SparseBooleanArray;
89 
90 import com.android.internal.annotations.VisibleForTesting;
91 import com.android.internal.telephony.IccCardConstants;
92 import com.android.internal.telephony.IccCardConstants.State;
93 import com.android.internal.telephony.TelephonyIntents;
94 import com.android.internal.util.Preconditions;
95 import com.android.internal.widget.LockPatternUtils;
96 import com.android.settingslib.WirelessUtils;
97 import com.android.systemui.R;
98 import com.android.systemui.shared.system.ActivityManagerWrapper;
99 import com.android.systemui.shared.system.TaskStackChangeListener;
100 import com.android.systemui.statusbar.phone.KeyguardBypassController;
101 
102 import com.google.android.collect.Lists;
103 
104 import java.io.FileDescriptor;
105 import java.io.PrintWriter;
106 import java.lang.ref.WeakReference;
107 import java.util.ArrayList;
108 import java.util.HashMap;
109 import java.util.List;
110 import java.util.Map.Entry;
111 import java.util.TimeZone;
112 import java.util.function.Consumer;
113 
114 /**
115  * Watches for updates that may be interesting to the keyguard, and provides
116  * the up to date information as well as a registration for callbacks that care
117  * to be updated.
118  */
119 public class KeyguardUpdateMonitor implements TrustManager.TrustListener {
120 
121     private static final String TAG = "KeyguardUpdateMonitor";
122     private static final boolean DEBUG = KeyguardConstants.DEBUG;
123     private static final boolean DEBUG_SIM_STATES = KeyguardConstants.DEBUG_SIM_STATES;
124     private static final boolean DEBUG_FACE = true;
125     private static final int LOW_BATTERY_THRESHOLD = 20;
126 
127     private static final String ACTION_FACE_UNLOCK_STARTED
128             = "com.android.facelock.FACE_UNLOCK_STARTED";
129     private static final String ACTION_FACE_UNLOCK_STOPPED
130             = "com.android.facelock.FACE_UNLOCK_STOPPED";
131 
132     // Callback messages
133     private static final int MSG_TIME_UPDATE = 301;
134     private static final int MSG_BATTERY_UPDATE = 302;
135     private static final int MSG_SIM_STATE_CHANGE = 304;
136     private static final int MSG_RINGER_MODE_CHANGED = 305;
137     private static final int MSG_PHONE_STATE_CHANGED = 306;
138     private static final int MSG_DEVICE_PROVISIONED = 308;
139     private static final int MSG_DPM_STATE_CHANGED = 309;
140     private static final int MSG_USER_SWITCHING = 310;
141     private static final int MSG_KEYGUARD_RESET = 312;
142     private static final int MSG_BOOT_COMPLETED = 313;
143     private static final int MSG_USER_SWITCH_COMPLETE = 314;
144     private static final int MSG_USER_INFO_CHANGED = 317;
145     private static final int MSG_REPORT_EMERGENCY_CALL_ACTION = 318;
146     private static final int MSG_STARTED_WAKING_UP = 319;
147     private static final int MSG_FINISHED_GOING_TO_SLEEP = 320;
148     private static final int MSG_STARTED_GOING_TO_SLEEP = 321;
149     private static final int MSG_KEYGUARD_BOUNCER_CHANGED = 322;
150     private static final int MSG_FACE_UNLOCK_STATE_CHANGED = 327;
151     private static final int MSG_SIM_SUBSCRIPTION_INFO_CHANGED = 328;
152     private static final int MSG_AIRPLANE_MODE_CHANGED = 329;
153     private static final int MSG_SERVICE_STATE_CHANGE = 330;
154     private static final int MSG_SCREEN_TURNED_ON = 331;
155     private static final int MSG_SCREEN_TURNED_OFF = 332;
156     private static final int MSG_DREAMING_STATE_CHANGED = 333;
157     private static final int MSG_USER_UNLOCKED = 334;
158     private static final int MSG_ASSISTANT_STACK_CHANGED = 335;
159     private static final int MSG_BIOMETRIC_AUTHENTICATION_CONTINUE = 336;
160     private static final int MSG_DEVICE_POLICY_MANAGER_STATE_CHANGED = 337;
161     private static final int MSG_TELEPHONY_CAPABLE = 338;
162     private static final int MSG_TIMEZONE_UPDATE = 339;
163 
164     /** Biometric authentication state: Not listening. */
165     private static final int BIOMETRIC_STATE_STOPPED = 0;
166 
167     /** Biometric authentication state: Listening. */
168     private static final int BIOMETRIC_STATE_RUNNING = 1;
169 
170     /**
171      * Biometric authentication: Cancelling and waiting for the relevant biometric service to
172      * send us the confirmation that cancellation has happened.
173      */
174     private static final int BIOMETRIC_STATE_CANCELLING = 2;
175 
176     /**
177      * Biometric state: During cancelling we got another request to start listening, so when we
178      * receive the cancellation done signal, we should start listening again.
179      */
180     private static final int BIOMETRIC_STATE_CANCELLING_RESTARTING = 3;
181 
182     private static final int BIOMETRIC_HELP_FINGERPRINT_NOT_RECOGNIZED = -1;
183     public static final int BIOMETRIC_HELP_FACE_NOT_RECOGNIZED = -2;
184 
185     private static final int DEFAULT_CHARGING_VOLTAGE_MICRO_VOLT = 5000000;
186 
187     private static final ComponentName FALLBACK_HOME_COMPONENT = new ComponentName(
188             "com.android.settings", "com.android.settings.FallbackHome");
189 
190 
191     /**
192      * If true, the system is in the half-boot-to-decryption-screen state.
193      * Prudently disable lockscreen.
194      */
195     public static final boolean CORE_APPS_ONLY;
196 
197     static {
198         try {
199             CORE_APPS_ONLY = IPackageManager.Stub.asInterface(
200                     ServiceManager.getService("package")).isOnlyCoreApps();
201         } catch (RemoteException e) {
202             throw e.rethrowFromSystemServer();
203         }
204     }
205 
206     private static KeyguardUpdateMonitor sInstance;
207 
208     private final Context mContext;
209     private final boolean mIsPrimaryUser;
210     HashMap<Integer, SimData> mSimDatas = new HashMap<Integer, SimData>();
211     HashMap<Integer, ServiceState> mServiceStates = new HashMap<Integer, ServiceState>();
212 
213     private int mRingMode;
214     private int mPhoneState;
215     private boolean mKeyguardIsVisible;
216     private boolean mKeyguardGoingAway;
217     private boolean mGoingToSleep;
218     private boolean mBouncer;
219     private boolean mAuthInterruptActive;
220     private boolean mBootCompleted;
221     private boolean mNeedsSlowUnlockTransition;
222     private boolean mHasLockscreenWallpaper;
223     private boolean mAssistantVisible;
224     private boolean mKeyguardOccluded;
225     private boolean mSecureCameraLaunched;
226     @VisibleForTesting
227     protected boolean mTelephonyCapable;
228 
229     // Device provisioning state
230     private boolean mDeviceProvisioned;
231 
232     // Battery status
233     private BatteryStatus mBatteryStatus;
234 
235     @VisibleForTesting
236     protected StrongAuthTracker mStrongAuthTracker;
237 
238     private final ArrayList<WeakReference<KeyguardUpdateMonitorCallback>>
239             mCallbacks = Lists.newArrayList();
240     private ContentObserver mDeviceProvisionedObserver;
241 
242     private boolean mSwitchingUser;
243 
244     private boolean mDeviceInteractive;
245     private boolean mScreenOn;
246     private SubscriptionManager mSubscriptionManager;
247     private List<SubscriptionInfo> mSubscriptionInfo;
248     private TrustManager mTrustManager;
249     private UserManager mUserManager;
250     private KeyguardBypassController mKeyguardBypassController;
251     private int mFingerprintRunningState = BIOMETRIC_STATE_STOPPED;
252     private int mFaceRunningState = BIOMETRIC_STATE_STOPPED;
253     private LockPatternUtils mLockPatternUtils;
254     private final IDreamManager mDreamManager;
255     private boolean mIsDreaming;
256     private final DevicePolicyManager mDevicePolicyManager;
257     private boolean mLogoutEnabled;
258     // If the user long pressed the lock icon, disabling face auth for the current session.
259     private boolean mLockIconPressed;
260     private int mActiveMobileDataSubscription = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
261 
262     /**
263      * Short delay before restarting biometric authentication after a successful try
264      * This should be slightly longer than the time between on<biometric>Authenticated
265      * (e.g. onFingerprintAuthenticated) and setKeyguardGoingAway(true).
266      */
267     private static final int BIOMETRIC_CONTINUE_DELAY_MS = 500;
268 
269     // If the HAL dies or is unable to authenticate, keyguard should retry after a short delay
270     private int mHardwareFingerprintUnavailableRetryCount = 0;
271     private int mHardwareFaceUnavailableRetryCount = 0;
272     private static final int HAL_ERROR_RETRY_TIMEOUT = 500; // ms
273     private static final int HAL_ERROR_RETRY_MAX = 10;
274 
275     private final Handler mHandler = new Handler(Looper.getMainLooper()) {
276         @Override
277         public void handleMessage(Message msg) {
278             switch (msg.what) {
279                 case MSG_TIME_UPDATE:
280                     handleTimeUpdate();
281                     break;
282                 case MSG_TIMEZONE_UPDATE:
283                     handleTimeZoneUpdate((String) msg.obj);
284                     break;
285                 case MSG_BATTERY_UPDATE:
286                     handleBatteryUpdate((BatteryStatus) msg.obj);
287                     break;
288                 case MSG_SIM_STATE_CHANGE:
289                     handleSimStateChange(msg.arg1, msg.arg2, (State) msg.obj);
290                     break;
291                 case MSG_RINGER_MODE_CHANGED:
292                     handleRingerModeChange(msg.arg1);
293                     break;
294                 case MSG_PHONE_STATE_CHANGED:
295                     handlePhoneStateChanged((String) msg.obj);
296                     break;
297                 case MSG_DEVICE_PROVISIONED:
298                     handleDeviceProvisioned();
299                     break;
300                 case MSG_DPM_STATE_CHANGED:
301                     handleDevicePolicyManagerStateChanged();
302                     break;
303                 case MSG_USER_SWITCHING:
304                     handleUserSwitching(msg.arg1, (IRemoteCallback) msg.obj);
305                     break;
306                 case MSG_USER_SWITCH_COMPLETE:
307                     handleUserSwitchComplete(msg.arg1);
308                     break;
309                 case MSG_KEYGUARD_RESET:
310                     handleKeyguardReset();
311                     break;
312                 case MSG_KEYGUARD_BOUNCER_CHANGED:
313                     handleKeyguardBouncerChanged(msg.arg1);
314                     break;
315                 case MSG_BOOT_COMPLETED:
316                     handleBootCompleted();
317                     break;
318                 case MSG_USER_INFO_CHANGED:
319                     handleUserInfoChanged(msg.arg1);
320                     break;
321                 case MSG_REPORT_EMERGENCY_CALL_ACTION:
322                     handleReportEmergencyCallAction();
323                     break;
324                 case MSG_STARTED_GOING_TO_SLEEP:
325                     handleStartedGoingToSleep(msg.arg1);
326                     break;
327                 case MSG_FINISHED_GOING_TO_SLEEP:
328                     handleFinishedGoingToSleep(msg.arg1);
329                     break;
330                 case MSG_STARTED_WAKING_UP:
331                     Trace.beginSection("KeyguardUpdateMonitor#handler MSG_STARTED_WAKING_UP");
332                     handleStartedWakingUp();
333                     Trace.endSection();
334                     break;
335                 case MSG_FACE_UNLOCK_STATE_CHANGED:
336                     Trace.beginSection("KeyguardUpdateMonitor#handler MSG_FACE_UNLOCK_STATE_CHANGED");
337                     handleFaceUnlockStateChanged(msg.arg1 != 0, msg.arg2);
338                     Trace.endSection();
339                     break;
340                 case MSG_SIM_SUBSCRIPTION_INFO_CHANGED:
341                     handleSimSubscriptionInfoChanged();
342                     break;
343                 case MSG_AIRPLANE_MODE_CHANGED:
344                     handleAirplaneModeChanged();
345                     break;
346                 case MSG_SERVICE_STATE_CHANGE:
347                     handleServiceStateChange(msg.arg1, (ServiceState) msg.obj);
348                     break;
349                 case MSG_SCREEN_TURNED_ON:
350                     handleScreenTurnedOn();
351                     break;
352                 case MSG_SCREEN_TURNED_OFF:
353                     Trace.beginSection("KeyguardUpdateMonitor#handler MSG_SCREEN_TURNED_ON");
354                     handleScreenTurnedOff();
355                     Trace.endSection();
356                     break;
357                 case MSG_DREAMING_STATE_CHANGED:
358                     handleDreamingStateChanged(msg.arg1);
359                     break;
360                 case MSG_USER_UNLOCKED:
361                     handleUserUnlocked();
362                     break;
363                 case MSG_ASSISTANT_STACK_CHANGED:
364                     setAssistantVisible((boolean) msg.obj);
365                     break;
366                 case MSG_BIOMETRIC_AUTHENTICATION_CONTINUE:
367                     updateBiometricListeningState();
368                     break;
369                 case MSG_DEVICE_POLICY_MANAGER_STATE_CHANGED:
370                     updateLogoutEnabled();
371                     break;
372                 case MSG_TELEPHONY_CAPABLE:
373                     updateTelephonyCapable((boolean) msg.obj);
374                     break;
375                 default:
376                     super.handleMessage(msg);
377                     break;
378             }
379         }
380     };
381 
382     private SparseBooleanArray mFaceSettingEnabledForUser = new SparseBooleanArray();
383     private BiometricManager mBiometricManager;
384     private IBiometricEnabledOnKeyguardCallback mBiometricEnabledCallback =
385             new IBiometricEnabledOnKeyguardCallback.Stub() {
386         @Override
387         public void onChanged(BiometricSourceType type, boolean enabled, int userId)
388                 throws RemoteException {
389             if (type == BiometricSourceType.FACE) {
390                 mFaceSettingEnabledForUser.put(userId, enabled);
391                 updateFaceListeningState();
392             }
393         }
394     };
395 
396     @VisibleForTesting
397     public PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
398         @Override
399         public void onActiveDataSubscriptionIdChanged(int subId) {
400             mActiveMobileDataSubscription = subId;
401             mHandler.sendEmptyMessage(MSG_SIM_SUBSCRIPTION_INFO_CHANGED);
402         }
403     };
404 
405     private OnSubscriptionsChangedListener mSubscriptionListener =
406             new OnSubscriptionsChangedListener() {
407         @Override
408         public void onSubscriptionsChanged() {
409             mHandler.sendEmptyMessage(MSG_SIM_SUBSCRIPTION_INFO_CHANGED);
410         }
411     };
412 
413     private SparseBooleanArray mUserHasTrust = new SparseBooleanArray();
414     private SparseBooleanArray mUserTrustIsManaged = new SparseBooleanArray();
415     private SparseBooleanArray mUserFingerprintAuthenticated = new SparseBooleanArray();
416     private SparseBooleanArray mUserFaceAuthenticated = new SparseBooleanArray();
417     private SparseBooleanArray mUserFaceUnlockRunning = new SparseBooleanArray();
418 
419     private static int sCurrentUser;
420     private Runnable mUpdateBiometricListeningState = this::updateBiometricListeningState;
421     private static boolean sDisableHandlerCheckForTesting;
422 
setCurrentUser(int currentUser)423     public synchronized static void setCurrentUser(int currentUser) {
424         sCurrentUser = currentUser;
425     }
426 
getCurrentUser()427     public synchronized static int getCurrentUser() {
428         return sCurrentUser;
429     }
430 
431     @Override
onTrustChanged(boolean enabled, int userId, int flags)432     public void onTrustChanged(boolean enabled, int userId, int flags) {
433         checkIsHandlerThread();
434         mUserHasTrust.put(userId, enabled);
435         for (int i = 0; i < mCallbacks.size(); i++) {
436             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
437             if (cb != null) {
438                 cb.onTrustChanged(userId);
439                 if (enabled && flags != 0) {
440                     cb.onTrustGrantedWithFlags(flags, userId);
441                 }
442             }
443         }
444     }
445 
446     @Override
onTrustError(CharSequence message)447     public void onTrustError(CharSequence message) {
448         dispatchErrorMessage(message);
449     }
450 
handleSimSubscriptionInfoChanged()451     private void handleSimSubscriptionInfoChanged() {
452         if (DEBUG_SIM_STATES) {
453             Log.v(TAG, "onSubscriptionInfoChanged()");
454             List<SubscriptionInfo> sil = mSubscriptionManager.getActiveSubscriptionInfoList(false);
455             if (sil != null) {
456                 for (SubscriptionInfo subInfo : sil) {
457                     Log.v(TAG, "SubInfo:" + subInfo);
458                 }
459             } else {
460                 Log.v(TAG, "onSubscriptionInfoChanged: list is null");
461             }
462         }
463         List<SubscriptionInfo> subscriptionInfos = getSubscriptionInfo(true /* forceReload */);
464 
465         // Hack level over 9000: Because the subscription id is not yet valid when we see the
466         // first update in handleSimStateChange, we need to force refresh all all SIM states
467         // so the subscription id for them is consistent.
468         ArrayList<SubscriptionInfo> changedSubscriptions = new ArrayList<>();
469         for (int i = 0; i < subscriptionInfos.size(); i++) {
470             SubscriptionInfo info = subscriptionInfos.get(i);
471             boolean changed = refreshSimState(info.getSubscriptionId(), info.getSimSlotIndex());
472             if (changed) {
473                 changedSubscriptions.add(info);
474             }
475         }
476         for (int i = 0; i < changedSubscriptions.size(); i++) {
477             SimData data = mSimDatas.get(changedSubscriptions.get(i).getSubscriptionId());
478             for (int j = 0; j < mCallbacks.size(); j++) {
479                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(j).get();
480                 if (cb != null) {
481                     cb.onSimStateChanged(data.subId, data.slotId, data.simState);
482                 }
483             }
484         }
485         for (int j = 0; j < mCallbacks.size(); j++) {
486             KeyguardUpdateMonitorCallback cb = mCallbacks.get(j).get();
487             if (cb != null) {
488                 cb.onRefreshCarrierInfo();
489             }
490         }
491     }
492 
handleAirplaneModeChanged()493     private void handleAirplaneModeChanged() {
494         for (int j = 0; j < mCallbacks.size(); j++) {
495             KeyguardUpdateMonitorCallback cb = mCallbacks.get(j).get();
496             if (cb != null) {
497                 cb.onRefreshCarrierInfo();
498             }
499         }
500     }
501 
502     /**
503      * @return List of SubscriptionInfo records, maybe empty but never null.
504      */
getSubscriptionInfo(boolean forceReload)505     public List<SubscriptionInfo> getSubscriptionInfo(boolean forceReload) {
506         List<SubscriptionInfo> sil = mSubscriptionInfo;
507         if (sil == null || forceReload) {
508             sil = mSubscriptionManager.getActiveSubscriptionInfoList(false);
509         }
510         if (sil == null) {
511             // getActiveSubscriptionInfoList was null callers expect an empty list.
512             mSubscriptionInfo = new ArrayList<SubscriptionInfo>();
513         } else {
514             mSubscriptionInfo = sil;
515         }
516         return new ArrayList<>(mSubscriptionInfo);
517     }
518 
519     /**
520      * This method returns filtered list of SubscriptionInfo from {@link #getSubscriptionInfo}.
521      * above. Maybe empty but never null.
522      *
523      * In DSDS mode if both subscriptions are grouped and one is opportunistic, we filter out one
524      * of them based on carrier config. e.g. In this case we should only show one carrier name
525      * on the status bar and quick settings.
526      */
getFilteredSubscriptionInfo(boolean forceReload)527     public List<SubscriptionInfo> getFilteredSubscriptionInfo(boolean forceReload) {
528         List<SubscriptionInfo> subscriptions = getSubscriptionInfo(false);
529         if (subscriptions.size() == 2) {
530             SubscriptionInfo info1 = subscriptions.get(0);
531             SubscriptionInfo info2 = subscriptions.get(1);
532             if (info1.getGroupUuid() != null && info1.getGroupUuid().equals(info2.getGroupUuid())) {
533                 // If both subscriptions are primary, show both.
534                 if (!info1.isOpportunistic() && !info2.isOpportunistic()) return subscriptions;
535 
536                 // If carrier required, always show signal bar of primary subscription.
537                 // Otherwise, show whichever subscription is currently active for Internet.
538                 boolean alwaysShowPrimary = CarrierConfigManager.getDefaultConfig()
539                         .getBoolean(CarrierConfigManager
540                         .KEY_ALWAYS_SHOW_PRIMARY_SIGNAL_BAR_IN_OPPORTUNISTIC_NETWORK_BOOLEAN);
541                 if (alwaysShowPrimary) {
542                     subscriptions.remove(info1.isOpportunistic() ? info1 : info2);
543                 } else {
544                     subscriptions.remove(info1.getSubscriptionId() == mActiveMobileDataSubscription
545                             ? info2 : info1);
546                 }
547 
548             }
549         }
550 
551         return subscriptions;
552     }
553 
554     @Override
onTrustManagedChanged(boolean managed, int userId)555     public void onTrustManagedChanged(boolean managed, int userId) {
556         checkIsHandlerThread();
557         mUserTrustIsManaged.put(userId, managed);
558 
559         for (int i = 0; i < mCallbacks.size(); i++) {
560             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
561             if (cb != null) {
562                 cb.onTrustManagedChanged(userId);
563             }
564         }
565     }
566 
567     /**
568      * Updates KeyguardUpdateMonitor's internal state to know if keyguard is goingAway
569      * @param goingAway
570      */
setKeyguardGoingAway(boolean goingAway)571     public void setKeyguardGoingAway(boolean goingAway) {
572         mKeyguardGoingAway = goingAway;
573         updateFingerprintListeningState();
574     }
575 
576     /**
577      * Updates KeyguardUpdateMonitor's internal state to know if keyguard is occluded
578      * @param occluded
579      */
setKeyguardOccluded(boolean occluded)580     public void setKeyguardOccluded(boolean occluded) {
581         mKeyguardOccluded = occluded;
582         updateBiometricListeningState();
583     }
584 
585     /**
586      * Invoked when the secure camera is launched.
587      */
onCameraLaunched()588     public void onCameraLaunched() {
589         mSecureCameraLaunched = true;
590         updateBiometricListeningState();
591     }
592 
593     /**
594      * @return a cached version of DreamManager.isDreaming()
595      */
isDreaming()596     public boolean isDreaming() {
597         return mIsDreaming;
598     }
599 
600     /**
601      * If the device is dreaming, awakens the device
602      */
awakenFromDream()603     public void awakenFromDream() {
604         if (mIsDreaming && mDreamManager != null) {
605             try {
606                 mDreamManager.awaken();
607             } catch (RemoteException e) {
608                 Log.e(TAG, "Unable to awaken from dream");
609             }
610         }
611     }
612 
613     @VisibleForTesting
onFingerprintAuthenticated(int userId)614     protected void onFingerprintAuthenticated(int userId) {
615         Trace.beginSection("KeyGuardUpdateMonitor#onFingerPrintAuthenticated");
616         mUserFingerprintAuthenticated.put(userId, true);
617         // Update/refresh trust state only if user can skip bouncer
618         if (getUserCanSkipBouncer(userId)) {
619             mTrustManager.unlockedByBiometricForUser(userId, BiometricSourceType.FINGERPRINT);
620         }
621         // Don't send cancel if authentication succeeds
622         mFingerprintCancelSignal = null;
623         for (int i = 0; i < mCallbacks.size(); i++) {
624             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
625             if (cb != null) {
626                 cb.onBiometricAuthenticated(userId, BiometricSourceType.FINGERPRINT);
627             }
628         }
629 
630         mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE),
631                 BIOMETRIC_CONTINUE_DELAY_MS);
632 
633         // Only authenticate fingerprint once when assistant is visible
634         mAssistantVisible = false;
635 
636         Trace.endSection();
637     }
638 
handleFingerprintAuthFailed()639     private void handleFingerprintAuthFailed() {
640         for (int i = 0; i < mCallbacks.size(); i++) {
641             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
642             if (cb != null) {
643                 cb.onBiometricAuthFailed(BiometricSourceType.FINGERPRINT);
644             }
645         }
646         handleFingerprintHelp(BIOMETRIC_HELP_FINGERPRINT_NOT_RECOGNIZED,
647                 mContext.getString(R.string.kg_fingerprint_not_recognized));
648     }
649 
handleFingerprintAcquired(int acquireInfo)650     private void handleFingerprintAcquired(int acquireInfo) {
651         if (acquireInfo != FingerprintManager.FINGERPRINT_ACQUIRED_GOOD) {
652             return;
653         }
654         for (int i = 0; i < mCallbacks.size(); i++) {
655             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
656             if (cb != null) {
657                 cb.onBiometricAcquired(BiometricSourceType.FINGERPRINT);
658             }
659         }
660     }
661 
handleFingerprintAuthenticated(int authUserId)662     private void handleFingerprintAuthenticated(int authUserId) {
663         Trace.beginSection("KeyGuardUpdateMonitor#handlerFingerPrintAuthenticated");
664         try {
665             final int userId;
666             try {
667                 userId = ActivityManager.getService().getCurrentUser().id;
668             } catch (RemoteException e) {
669                 Log.e(TAG, "Failed to get current user id: ", e);
670                 return;
671             }
672             if (userId != authUserId) {
673                 Log.d(TAG, "Fingerprint authenticated for wrong user: " + authUserId);
674                 return;
675             }
676             if (isFingerprintDisabled(userId)) {
677                 Log.d(TAG, "Fingerprint disabled by DPM for userId: " + userId);
678                 return;
679             }
680             onFingerprintAuthenticated(userId);
681         } finally {
682             setFingerprintRunningState(BIOMETRIC_STATE_STOPPED);
683         }
684         Trace.endSection();
685     }
686 
handleFingerprintHelp(int msgId, String helpString)687     private void handleFingerprintHelp(int msgId, String helpString) {
688         for (int i = 0; i < mCallbacks.size(); i++) {
689             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
690             if (cb != null) {
691                 cb.onBiometricHelp(msgId, helpString, BiometricSourceType.FINGERPRINT);
692             }
693         }
694     }
695 
696     private Runnable mRetryFingerprintAuthentication = new Runnable() {
697         @Override
698         public void run() {
699             Log.w(TAG, "Retrying fingerprint after HW unavailable, attempt " +
700                     mHardwareFingerprintUnavailableRetryCount);
701             updateFingerprintListeningState();
702         }
703     };
704 
handleFingerprintError(int msgId, String errString)705     private void handleFingerprintError(int msgId, String errString) {
706         if (msgId == FingerprintManager.FINGERPRINT_ERROR_CANCELED
707                 && mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) {
708             setFingerprintRunningState(BIOMETRIC_STATE_STOPPED);
709             updateFingerprintListeningState();
710         } else {
711             setFingerprintRunningState(BIOMETRIC_STATE_STOPPED);
712         }
713 
714         if (msgId == FingerprintManager.FINGERPRINT_ERROR_HW_UNAVAILABLE) {
715             if (mHardwareFingerprintUnavailableRetryCount < HAL_ERROR_RETRY_MAX) {
716                 mHardwareFingerprintUnavailableRetryCount++;
717                 mHandler.removeCallbacks(mRetryFingerprintAuthentication);
718                 mHandler.postDelayed(mRetryFingerprintAuthentication, HAL_ERROR_RETRY_TIMEOUT);
719             }
720         }
721 
722         if (msgId == FingerprintManager.FINGERPRINT_ERROR_LOCKOUT_PERMANENT) {
723             mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_LOCKOUT,
724                     getCurrentUser());
725         }
726 
727         for (int i = 0; i < mCallbacks.size(); i++) {
728             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
729             if (cb != null) {
730                 cb.onBiometricError(msgId, errString, BiometricSourceType.FINGERPRINT);
731             }
732         }
733     }
734 
handleFingerprintLockoutReset()735     private void handleFingerprintLockoutReset() {
736         updateFingerprintListeningState();
737     }
738 
setFingerprintRunningState(int fingerprintRunningState)739     private void setFingerprintRunningState(int fingerprintRunningState) {
740         boolean wasRunning = mFingerprintRunningState == BIOMETRIC_STATE_RUNNING;
741         boolean isRunning = fingerprintRunningState == BIOMETRIC_STATE_RUNNING;
742         mFingerprintRunningState = fingerprintRunningState;
743         Log.d(TAG, "fingerprintRunningState: " + mFingerprintRunningState);
744         // Clients of KeyguardUpdateMonitor don't care about the internal state about the
745         // asynchronousness of the cancel cycle. So only notify them if the actually running state
746         // has changed.
747         if (wasRunning != isRunning) {
748             notifyFingerprintRunningStateChanged();
749         }
750     }
751 
notifyFingerprintRunningStateChanged()752     private void notifyFingerprintRunningStateChanged() {
753         checkIsHandlerThread();
754         for (int i = 0; i < mCallbacks.size(); i++) {
755             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
756             if (cb != null) {
757                 cb.onBiometricRunningStateChanged(isFingerprintDetectionRunning(),
758                         BiometricSourceType.FINGERPRINT);
759             }
760         }
761     }
762 
763     @VisibleForTesting
onFaceAuthenticated(int userId)764     protected void onFaceAuthenticated(int userId) {
765         Trace.beginSection("KeyGuardUpdateMonitor#onFaceAuthenticated");
766         mUserFaceAuthenticated.put(userId, true);
767         // Update/refresh trust state only if user can skip bouncer
768         if (getUserCanSkipBouncer(userId)) {
769             mTrustManager.unlockedByBiometricForUser(userId, BiometricSourceType.FACE);
770         }
771         // Don't send cancel if authentication succeeds
772         mFaceCancelSignal = null;
773         for (int i = 0; i < mCallbacks.size(); i++) {
774             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
775             if (cb != null) {
776                 cb.onBiometricAuthenticated(userId,
777                         BiometricSourceType.FACE);
778             }
779         }
780 
781         mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE),
782                 BIOMETRIC_CONTINUE_DELAY_MS);
783 
784         // Only authenticate face once when assistant is visible
785         mAssistantVisible = false;
786 
787         Trace.endSection();
788     }
789 
handleFaceAuthFailed()790     private void handleFaceAuthFailed() {
791         setFaceRunningState(BIOMETRIC_STATE_STOPPED);
792         for (int i = 0; i < mCallbacks.size(); i++) {
793             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
794             if (cb != null) {
795                 cb.onBiometricAuthFailed(BiometricSourceType.FACE);
796             }
797         }
798         handleFaceHelp(BIOMETRIC_HELP_FACE_NOT_RECOGNIZED,
799                 mContext.getString(R.string.kg_face_not_recognized));
800     }
801 
handleFaceAcquired(int acquireInfo)802     private void handleFaceAcquired(int acquireInfo) {
803         if (acquireInfo != FaceManager.FACE_ACQUIRED_GOOD) {
804             return;
805         }
806         if (DEBUG_FACE) Log.d(TAG, "Face acquired");
807         for (int i = 0; i < mCallbacks.size(); i++) {
808             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
809             if (cb != null) {
810                 cb.onBiometricAcquired(BiometricSourceType.FACE);
811             }
812         }
813     }
814 
handleFaceAuthenticated(int authUserId)815     private void handleFaceAuthenticated(int authUserId) {
816         Trace.beginSection("KeyGuardUpdateMonitor#handlerFaceAuthenticated");
817         try {
818             if (mGoingToSleep) {
819                 Log.d(TAG, "Aborted successful auth because device is going to sleep.");
820                 return;
821             }
822             final int userId;
823             try {
824                 userId = ActivityManager.getService().getCurrentUser().id;
825             } catch (RemoteException e) {
826                 Log.e(TAG, "Failed to get current user id: ", e);
827                 return;
828             }
829             if (userId != authUserId) {
830                 Log.d(TAG, "Face authenticated for wrong user: " + authUserId);
831                 return;
832             }
833             if (isFaceDisabled(userId)) {
834                 Log.d(TAG, "Face authentication disabled by DPM for userId: " + userId);
835                 return;
836             }
837             if (DEBUG_FACE) Log.d(TAG, "Face auth succeeded for user " + userId);
838             onFaceAuthenticated(userId);
839         } finally {
840             setFaceRunningState(BIOMETRIC_STATE_STOPPED);
841         }
842         Trace.endSection();
843     }
844 
handleFaceHelp(int msgId, String helpString)845     private void handleFaceHelp(int msgId, String helpString) {
846         if (DEBUG_FACE) Log.d(TAG, "Face help received: " + helpString);
847         for (int i = 0; i < mCallbacks.size(); i++) {
848             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
849             if (cb != null) {
850                 cb.onBiometricHelp(msgId, helpString, BiometricSourceType.FACE);
851             }
852         }
853     }
854 
855     private Runnable mRetryFaceAuthentication = new Runnable() {
856         @Override
857         public void run() {
858             Log.w(TAG, "Retrying face after HW unavailable, attempt " +
859                     mHardwareFaceUnavailableRetryCount);
860             updateFaceListeningState();
861         }
862     };
863 
handleFaceError(int msgId, String errString)864     private void handleFaceError(int msgId, String errString) {
865         if (DEBUG_FACE) Log.d(TAG, "Face error received: " + errString);
866         if (msgId == FaceManager.FACE_ERROR_CANCELED
867                 && mFaceRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) {
868             setFaceRunningState(BIOMETRIC_STATE_STOPPED);
869             updateFaceListeningState();
870         } else {
871             setFaceRunningState(BIOMETRIC_STATE_STOPPED);
872         }
873 
874         if (msgId == FaceManager.FACE_ERROR_HW_UNAVAILABLE
875                 || msgId == FaceManager.FACE_ERROR_UNABLE_TO_PROCESS) {
876             if (mHardwareFaceUnavailableRetryCount < HAL_ERROR_RETRY_MAX) {
877                 mHardwareFaceUnavailableRetryCount++;
878                 mHandler.removeCallbacks(mRetryFaceAuthentication);
879                 mHandler.postDelayed(mRetryFaceAuthentication, HAL_ERROR_RETRY_TIMEOUT);
880             }
881         }
882 
883         if (msgId == FaceManager.FACE_ERROR_LOCKOUT_PERMANENT) {
884             mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_LOCKOUT,
885                     getCurrentUser());
886         }
887 
888         for (int i = 0; i < mCallbacks.size(); i++) {
889             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
890             if (cb != null) {
891                 cb.onBiometricError(msgId, errString,
892                         BiometricSourceType.FACE);
893             }
894         }
895     }
896 
handleFaceLockoutReset()897     private void handleFaceLockoutReset() {
898         updateFaceListeningState();
899     }
900 
setFaceRunningState(int faceRunningState)901     private void setFaceRunningState(int faceRunningState) {
902         boolean wasRunning = mFaceRunningState == BIOMETRIC_STATE_RUNNING;
903         boolean isRunning = faceRunningState == BIOMETRIC_STATE_RUNNING;
904         mFaceRunningState = faceRunningState;
905         Log.d(TAG, "faceRunningState: " + mFaceRunningState);
906         // Clients of KeyguardUpdateMonitor don't care about the internal state or about the
907         // asynchronousness of the cancel cycle. So only notify them if the actually running state
908         // has changed.
909         if (wasRunning != isRunning) {
910             notifyFaceRunningStateChanged();
911         }
912     }
913 
notifyFaceRunningStateChanged()914     private void notifyFaceRunningStateChanged() {
915         for (int i = 0; i < mCallbacks.size(); i++) {
916             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
917             if (cb != null) {
918                 cb.onBiometricRunningStateChanged(isFaceDetectionRunning(),
919                         BiometricSourceType.FACE);
920             }
921         }
922     }
923 
handleFaceUnlockStateChanged(boolean running, int userId)924     private void handleFaceUnlockStateChanged(boolean running, int userId) {
925         checkIsHandlerThread();
926         mUserFaceUnlockRunning.put(userId, running);
927         for (int i = 0; i < mCallbacks.size(); i++) {
928             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
929             if (cb != null) {
930                 cb.onFaceUnlockStateChanged(running, userId);
931             }
932         }
933     }
934 
isFaceUnlockRunning(int userId)935     public boolean isFaceUnlockRunning(int userId) {
936         return mUserFaceUnlockRunning.get(userId);
937     }
938 
isFingerprintDetectionRunning()939     public boolean isFingerprintDetectionRunning() {
940         return mFingerprintRunningState == BIOMETRIC_STATE_RUNNING;
941     }
942 
isFaceDetectionRunning()943     public boolean isFaceDetectionRunning() {
944         return mFaceRunningState == BIOMETRIC_STATE_RUNNING;
945     }
946 
isTrustDisabled(int userId)947     private boolean isTrustDisabled(int userId) {
948         // Don't allow trust agent if device is secured with a SIM PIN. This is here
949         // mainly because there's no other way to prompt the user to enter their SIM PIN
950         // once they get past the keyguard screen.
951         final boolean disabledBySimPin = isSimPinSecure();
952         return disabledBySimPin;
953     }
954 
isFingerprintDisabled(int userId)955     private boolean isFingerprintDisabled(int userId) {
956         final DevicePolicyManager dpm =
957                 (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
958         return dpm != null && (dpm.getKeyguardDisabledFeatures(null, userId)
959                     & DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT) != 0
960                 || isSimPinSecure();
961     }
962 
isFaceDisabled(int userId)963     private boolean isFaceDisabled(int userId) {
964         final DevicePolicyManager dpm =
965                 (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
966         return dpm != null && (dpm.getKeyguardDisabledFeatures(null, userId)
967                 & DevicePolicyManager.KEYGUARD_DISABLE_FACE) != 0
968                 || isSimPinSecure();
969     }
970 
971 
getUserCanSkipBouncer(int userId)972     public boolean getUserCanSkipBouncer(int userId) {
973         return getUserHasTrust(userId) || getUserUnlockedWithBiometric(userId);
974     }
975 
getUserHasTrust(int userId)976     public boolean getUserHasTrust(int userId) {
977         return !isTrustDisabled(userId) && mUserHasTrust.get(userId);
978     }
979 
980     /**
981      * Returns whether the user is unlocked with biometrics.
982      */
getUserUnlockedWithBiometric(int userId)983     public boolean getUserUnlockedWithBiometric(int userId) {
984         boolean fingerprintOrFace = mUserFingerprintAuthenticated.get(userId)
985                 || mUserFaceAuthenticated.get(userId);
986         return fingerprintOrFace && isUnlockingWithBiometricAllowed();
987     }
988 
getUserTrustIsManaged(int userId)989     public boolean getUserTrustIsManaged(int userId) {
990         return mUserTrustIsManaged.get(userId) && !isTrustDisabled(userId);
991     }
992 
isUnlockingWithBiometricAllowed()993     public boolean isUnlockingWithBiometricAllowed() {
994         return mStrongAuthTracker.isUnlockingWithBiometricAllowed();
995     }
996 
isUserInLockdown(int userId)997     public boolean isUserInLockdown(int userId) {
998         return containsFlag(mStrongAuthTracker.getStrongAuthForUser(userId),
999                 STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN);
1000     }
1001 
userNeedsStrongAuth()1002     public boolean userNeedsStrongAuth() {
1003         return mStrongAuthTracker.getStrongAuthForUser(getCurrentUser())
1004                 != LockPatternUtils.StrongAuthTracker.STRONG_AUTH_NOT_REQUIRED;
1005     }
1006 
containsFlag(int haystack, int needle)1007     private boolean containsFlag(int haystack, int needle) {
1008         return (haystack & needle) != 0;
1009     }
1010 
needsSlowUnlockTransition()1011     public boolean needsSlowUnlockTransition() {
1012         return mNeedsSlowUnlockTransition;
1013     }
1014 
getStrongAuthTracker()1015     public StrongAuthTracker getStrongAuthTracker() {
1016         return mStrongAuthTracker;
1017     }
1018 
notifyStrongAuthStateChanged(int userId)1019     private void notifyStrongAuthStateChanged(int userId) {
1020         checkIsHandlerThread();
1021         for (int i = 0; i < mCallbacks.size(); i++) {
1022             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1023             if (cb != null) {
1024                 cb.onStrongAuthStateChanged(userId);
1025             }
1026         }
1027     }
1028 
isScreenOn()1029     public boolean isScreenOn() {
1030         return mScreenOn;
1031     }
1032 
dispatchErrorMessage(CharSequence message)1033     private void dispatchErrorMessage(CharSequence message) {
1034         for (int i = 0; i < mCallbacks.size(); i++) {
1035             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1036             if (cb != null) {
1037                 cb.onTrustAgentErrorMessage(message);
1038             }
1039         }
1040     }
1041 
1042     @VisibleForTesting
setAssistantVisible(boolean assistantVisible)1043     void setAssistantVisible(boolean assistantVisible) {
1044         mAssistantVisible = assistantVisible;
1045         updateBiometricListeningState();
1046     }
1047 
1048     static class DisplayClientState {
1049         public int clientGeneration;
1050         public boolean clearing;
1051         public PendingIntent intent;
1052         public int playbackState;
1053         public long playbackEventTime;
1054     }
1055 
1056     private DisplayClientState mDisplayClientState = new DisplayClientState();
1057 
1058     @VisibleForTesting
1059     protected final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1060 
1061         @Override
1062         public void onReceive(Context context, Intent intent) {
1063             final String action = intent.getAction();
1064             if (DEBUG) Log.d(TAG, "received broadcast " + action);
1065 
1066             if (Intent.ACTION_TIME_TICK.equals(action)
1067                     || Intent.ACTION_TIME_CHANGED.equals(action)) {
1068                 mHandler.sendEmptyMessage(MSG_TIME_UPDATE);
1069             } else if (Intent.ACTION_TIMEZONE_CHANGED.equals(action)) {
1070                 final Message msg = mHandler.obtainMessage(
1071                         MSG_TIMEZONE_UPDATE, intent.getStringExtra("time-zone"));
1072                 mHandler.sendMessage(msg);
1073             } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
1074                 final int status = intent.getIntExtra(EXTRA_STATUS, BATTERY_STATUS_UNKNOWN);
1075                 final int plugged = intent.getIntExtra(EXTRA_PLUGGED, 0);
1076                 final int level = intent.getIntExtra(EXTRA_LEVEL, 0);
1077                 final int health = intent.getIntExtra(EXTRA_HEALTH, BATTERY_HEALTH_UNKNOWN);
1078 
1079                 final int maxChargingMicroAmp = intent.getIntExtra(EXTRA_MAX_CHARGING_CURRENT, -1);
1080                 int maxChargingMicroVolt = intent.getIntExtra(EXTRA_MAX_CHARGING_VOLTAGE, -1);
1081                 final int maxChargingMicroWatt;
1082 
1083                 if (maxChargingMicroVolt <= 0) {
1084                     maxChargingMicroVolt = DEFAULT_CHARGING_VOLTAGE_MICRO_VOLT;
1085                 }
1086                 if (maxChargingMicroAmp > 0) {
1087                     // Calculating muW = muA * muV / (10^6 mu^2 / mu); splitting up the divisor
1088                     // to maintain precision equally on both factors.
1089                     maxChargingMicroWatt = (maxChargingMicroAmp / 1000)
1090                             * (maxChargingMicroVolt / 1000);
1091                 } else {
1092                     maxChargingMicroWatt = -1;
1093                 }
1094                 final Message msg = mHandler.obtainMessage(
1095                         MSG_BATTERY_UPDATE, new BatteryStatus(status, level, plugged, health,
1096                                 maxChargingMicroWatt));
1097                 mHandler.sendMessage(msg);
1098             } else if (TelephonyIntents.ACTION_SIM_STATE_CHANGED.equals(action)) {
1099                 SimData args = SimData.fromIntent(intent);
1100                 // ACTION_SIM_STATE_CHANGED is rebroadcast after unlocking the device to
1101                 // keep compatibility with apps that aren't direct boot aware.
1102                 // SysUI should just ignore this broadcast because it was already received
1103                 // and processed previously.
1104                 if (intent.getBooleanExtra(Intent.EXTRA_REBROADCAST_ON_UNLOCK, false)) {
1105                     // Guarantee mTelephonyCapable state after SysUI crash and restart
1106                     if (args.simState == State.ABSENT) {
1107                         mHandler.obtainMessage(MSG_TELEPHONY_CAPABLE, true).sendToTarget();
1108                     }
1109                     return;
1110                 }
1111                 if (DEBUG_SIM_STATES) {
1112                     Log.v(TAG, "action " + action
1113                         + " state: " + intent.getStringExtra(IccCardConstants.INTENT_KEY_ICC_STATE)
1114                         + " slotId: " + args.slotId + " subid: " + args.subId);
1115                 }
1116                 mHandler.obtainMessage(MSG_SIM_STATE_CHANGE, args.subId, args.slotId, args.simState)
1117                         .sendToTarget();
1118             } else if (AudioManager.RINGER_MODE_CHANGED_ACTION.equals(action)) {
1119                 mHandler.sendMessage(mHandler.obtainMessage(MSG_RINGER_MODE_CHANGED,
1120                         intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE, -1), 0));
1121             } else if (TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(action)) {
1122                 String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
1123                 mHandler.sendMessage(mHandler.obtainMessage(MSG_PHONE_STATE_CHANGED, state));
1124             } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
1125                 mHandler.sendEmptyMessage(MSG_AIRPLANE_MODE_CHANGED);
1126             } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
1127                 dispatchBootCompleted();
1128             } else if (TelephonyIntents.ACTION_SERVICE_STATE_CHANGED.equals(action)) {
1129                 ServiceState serviceState = ServiceState.newFromBundle(intent.getExtras());
1130                 int subId = intent.getIntExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX,
1131                         SubscriptionManager.INVALID_SUBSCRIPTION_ID);
1132                 if (DEBUG) {
1133                     Log.v(TAG, "action " + action + " serviceState=" + serviceState + " subId="
1134                             + subId);
1135                 }
1136                 mHandler.sendMessage(
1137                         mHandler.obtainMessage(MSG_SERVICE_STATE_CHANGE, subId, 0, serviceState));
1138             } else if (TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED.equals(action)) {
1139                 mHandler.sendEmptyMessage(MSG_SIM_SUBSCRIPTION_INFO_CHANGED);
1140             } else if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED.equals(
1141                     action)) {
1142                 mHandler.sendEmptyMessage(MSG_DEVICE_POLICY_MANAGER_STATE_CHANGED);
1143             }
1144         }
1145     };
1146 
1147     @VisibleForTesting
1148     protected final BroadcastReceiver mBroadcastAllReceiver = new BroadcastReceiver() {
1149 
1150         @Override
1151         public void onReceive(Context context, Intent intent) {
1152             final String action = intent.getAction();
1153             if (AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED.equals(action)) {
1154                 mHandler.sendEmptyMessage(MSG_TIME_UPDATE);
1155             } else if (Intent.ACTION_USER_INFO_CHANGED.equals(action)) {
1156                 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_INFO_CHANGED,
1157                         intent.getIntExtra(Intent.EXTRA_USER_HANDLE, getSendingUserId()), 0));
1158             } else if (ACTION_FACE_UNLOCK_STARTED.equals(action)) {
1159                 Trace.beginSection("KeyguardUpdateMonitor.mBroadcastAllReceiver#onReceive ACTION_FACE_UNLOCK_STARTED");
1160                 mHandler.sendMessage(mHandler.obtainMessage(MSG_FACE_UNLOCK_STATE_CHANGED, 1,
1161                         getSendingUserId()));
1162                 Trace.endSection();
1163             } else if (ACTION_FACE_UNLOCK_STOPPED.equals(action)) {
1164                 mHandler.sendMessage(mHandler.obtainMessage(MSG_FACE_UNLOCK_STATE_CHANGED, 0,
1165                         getSendingUserId()));
1166             } else if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
1167                     .equals(action)) {
1168                 mHandler.sendEmptyMessage(MSG_DPM_STATE_CHANGED);
1169             } else if (ACTION_USER_UNLOCKED.equals(action)) {
1170                 mHandler.sendEmptyMessage(MSG_USER_UNLOCKED);
1171             }
1172         }
1173     };
1174 
1175     private final FingerprintManager.LockoutResetCallback mFingerprintLockoutResetCallback
1176             = new FingerprintManager.LockoutResetCallback() {
1177         @Override
1178         public void onLockoutReset() {
1179             handleFingerprintLockoutReset();
1180         }
1181     };
1182 
1183     private final FaceManager.LockoutResetCallback mFaceLockoutResetCallback
1184             = new FaceManager.LockoutResetCallback() {
1185         @Override
1186         public void onLockoutReset() {
1187             handleFaceLockoutReset();
1188         }
1189     };
1190 
1191     private FingerprintManager.AuthenticationCallback mFingerprintAuthenticationCallback
1192             = new AuthenticationCallback() {
1193 
1194         @Override
1195         public void onAuthenticationFailed() {
1196             handleFingerprintAuthFailed();
1197         }
1198 
1199         @Override
1200         public void onAuthenticationSucceeded(AuthenticationResult result) {
1201             Trace.beginSection("KeyguardUpdateMonitor#onAuthenticationSucceeded");
1202             handleFingerprintAuthenticated(result.getUserId());
1203             Trace.endSection();
1204         }
1205 
1206         @Override
1207         public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
1208             handleFingerprintHelp(helpMsgId, helpString.toString());
1209         }
1210 
1211         @Override
1212         public void onAuthenticationError(int errMsgId, CharSequence errString) {
1213             handleFingerprintError(errMsgId, errString.toString());
1214         }
1215 
1216         @Override
1217         public void onAuthenticationAcquired(int acquireInfo) {
1218             handleFingerprintAcquired(acquireInfo);
1219         }
1220     };
1221 
1222     @VisibleForTesting
1223     FaceManager.AuthenticationCallback mFaceAuthenticationCallback
1224             = new FaceManager.AuthenticationCallback() {
1225 
1226         @Override
1227         public void onAuthenticationFailed() {
1228             handleFaceAuthFailed();
1229         }
1230 
1231         @Override
1232         public void onAuthenticationSucceeded(FaceManager.AuthenticationResult result) {
1233             Trace.beginSection("KeyguardUpdateMonitor#onAuthenticationSucceeded");
1234             handleFaceAuthenticated(result.getUserId());
1235             Trace.endSection();
1236         }
1237 
1238         @Override
1239         public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
1240             handleFaceHelp(helpMsgId, helpString.toString());
1241         }
1242 
1243         @Override
1244         public void onAuthenticationError(int errMsgId, CharSequence errString) {
1245             handleFaceError(errMsgId, errString.toString());
1246         }
1247 
1248         @Override
1249         public void onAuthenticationAcquired(int acquireInfo) {
1250             handleFaceAcquired(acquireInfo);
1251         }
1252     };
1253 
1254     private CancellationSignal mFingerprintCancelSignal;
1255     private CancellationSignal mFaceCancelSignal;
1256     private FingerprintManager mFpm;
1257     private FaceManager mFaceManager;
1258 
1259     /**
1260      * When we receive a
1261      * {@link com.android.internal.telephony.TelephonyIntents#ACTION_SIM_STATE_CHANGED} broadcast,
1262      * and then pass a result via our handler to {@link KeyguardUpdateMonitor#handleSimStateChange},
1263      * we need a single object to pass to the handler.  This class helps decode
1264      * the intent and provide a {@link SimCard.State} result.
1265      */
1266     private static class SimData {
1267         public State simState;
1268         public int slotId;
1269         public int subId;
1270 
SimData(State state, int slot, int id)1271         SimData(State state, int slot, int id) {
1272             simState = state;
1273             slotId = slot;
1274             subId = id;
1275         }
1276 
fromIntent(Intent intent)1277         static SimData fromIntent(Intent intent) {
1278             State state;
1279             if (!TelephonyIntents.ACTION_SIM_STATE_CHANGED.equals(intent.getAction())) {
1280                 throw new IllegalArgumentException("only handles intent ACTION_SIM_STATE_CHANGED");
1281             }
1282             String stateExtra = intent.getStringExtra(Intent.EXTRA_SIM_STATE);
1283             int slotId = intent.getIntExtra(SubscriptionManager.EXTRA_SLOT_INDEX, 0);
1284             int subId = intent.getIntExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX,
1285                     SubscriptionManager.INVALID_SUBSCRIPTION_ID);
1286             if (IccCardConstants.INTENT_VALUE_ICC_ABSENT.equals(stateExtra)) {
1287                 final String absentReason = intent
1288                     .getStringExtra(IccCardConstants.INTENT_KEY_LOCKED_REASON);
1289 
1290                 if (IccCardConstants.INTENT_VALUE_ABSENT_ON_PERM_DISABLED.equals(
1291                         absentReason)) {
1292                     state = IccCardConstants.State.PERM_DISABLED;
1293                 } else {
1294                     state = IccCardConstants.State.ABSENT;
1295                 }
1296             } else if (IccCardConstants.INTENT_VALUE_ICC_READY.equals(stateExtra)) {
1297                 state = IccCardConstants.State.READY;
1298             } else if (IccCardConstants.INTENT_VALUE_ICC_LOCKED.equals(stateExtra)) {
1299                 final String lockedReason = intent
1300                         .getStringExtra(IccCardConstants.INTENT_KEY_LOCKED_REASON);
1301                 if (IccCardConstants.INTENT_VALUE_LOCKED_ON_PIN.equals(lockedReason)) {
1302                     state = IccCardConstants.State.PIN_REQUIRED;
1303                 } else if (IccCardConstants.INTENT_VALUE_LOCKED_ON_PUK.equals(lockedReason)) {
1304                     state = IccCardConstants.State.PUK_REQUIRED;
1305                 } else {
1306                     state = IccCardConstants.State.UNKNOWN;
1307                 }
1308             } else if (IccCardConstants.INTENT_VALUE_LOCKED_NETWORK.equals(stateExtra)) {
1309                 state = IccCardConstants.State.NETWORK_LOCKED;
1310             } else if (IccCardConstants.INTENT_VALUE_ICC_CARD_IO_ERROR.equals(stateExtra)) {
1311                 state = IccCardConstants.State.CARD_IO_ERROR;
1312             } else if (IccCardConstants.INTENT_VALUE_ICC_LOADED.equals(stateExtra)
1313                         || IccCardConstants.INTENT_VALUE_ICC_IMSI.equals(stateExtra)) {
1314                 // This is required because telephony doesn't return to "READY" after
1315                 // these state transitions. See bug 7197471.
1316                 state = IccCardConstants.State.READY;
1317             } else {
1318                 state = IccCardConstants.State.UNKNOWN;
1319             }
1320             return new SimData(state, slotId, subId);
1321         }
1322 
1323         @Override
toString()1324         public String toString() {
1325             return "SimData{state=" + simState + ",slotId=" + slotId + ",subId=" + subId + "}";
1326         }
1327     }
1328 
1329     public static class BatteryStatus {
1330         public static final int CHARGING_UNKNOWN = -1;
1331         public static final int CHARGING_SLOWLY = 0;
1332         public static final int CHARGING_REGULAR = 1;
1333         public static final int CHARGING_FAST = 2;
1334 
1335         public final int status;
1336         public final int level;
1337         public final int plugged;
1338         public final int health;
1339         public final int maxChargingWattage;
BatteryStatus(int status, int level, int plugged, int health, int maxChargingWattage)1340         public BatteryStatus(int status, int level, int plugged, int health,
1341                 int maxChargingWattage) {
1342             this.status = status;
1343             this.level = level;
1344             this.plugged = plugged;
1345             this.health = health;
1346             this.maxChargingWattage = maxChargingWattage;
1347         }
1348 
1349         /**
1350          * Determine whether the device is plugged in (USB, power, or wireless).
1351          * @return true if the device is plugged in.
1352          */
isPluggedIn()1353         public boolean isPluggedIn() {
1354             return plugged == BatteryManager.BATTERY_PLUGGED_AC
1355                     || plugged == BatteryManager.BATTERY_PLUGGED_USB
1356                     || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS;
1357         }
1358 
1359         /**
1360          * Determine whether the device is plugged in (USB, power).
1361          * @return true if the device is plugged in wired (as opposed to wireless)
1362          */
isPluggedInWired()1363         public boolean isPluggedInWired() {
1364             return plugged == BatteryManager.BATTERY_PLUGGED_AC
1365                     || plugged == BatteryManager.BATTERY_PLUGGED_USB;
1366         }
1367 
1368         /**
1369          * Whether or not the device is charged. Note that some devices never return 100% for
1370          * battery level, so this allows either battery level or status to determine if the
1371          * battery is charged.
1372          * @return true if the device is charged
1373          */
isCharged()1374         public boolean isCharged() {
1375             return status == BATTERY_STATUS_FULL || level >= 100;
1376         }
1377 
1378         /**
1379          * Whether battery is low and needs to be charged.
1380          * @return true if battery is low
1381          */
isBatteryLow()1382         public boolean isBatteryLow() {
1383             return level < LOW_BATTERY_THRESHOLD;
1384         }
1385 
getChargingSpeed(int slowThreshold, int fastThreshold)1386         public final int getChargingSpeed(int slowThreshold, int fastThreshold) {
1387             return maxChargingWattage <= 0 ? CHARGING_UNKNOWN :
1388                     maxChargingWattage < slowThreshold ? CHARGING_SLOWLY :
1389                     maxChargingWattage > fastThreshold ? CHARGING_FAST :
1390                     CHARGING_REGULAR;
1391         }
1392 
1393         @Override
toString()1394         public String toString() {
1395             return "BatteryStatus{status=" + status + ",level=" + level + ",plugged=" + plugged
1396                     + ",health=" + health + ",maxChargingWattage=" + maxChargingWattage + "}";
1397         }
1398     }
1399 
1400     public static class StrongAuthTracker extends LockPatternUtils.StrongAuthTracker {
1401         private final Consumer<Integer> mStrongAuthRequiredChangedCallback;
1402 
StrongAuthTracker(Context context, Consumer<Integer> strongAuthRequiredChangedCallback)1403         public StrongAuthTracker(Context context,
1404                 Consumer<Integer> strongAuthRequiredChangedCallback) {
1405             super(context);
1406             mStrongAuthRequiredChangedCallback = strongAuthRequiredChangedCallback;
1407         }
1408 
isUnlockingWithBiometricAllowed()1409         public boolean isUnlockingWithBiometricAllowed() {
1410             int userId = getCurrentUser();
1411             return isBiometricAllowedForUser(userId);
1412         }
1413 
hasUserAuthenticatedSinceBoot()1414         public boolean hasUserAuthenticatedSinceBoot() {
1415             int userId = getCurrentUser();
1416             return (getStrongAuthForUser(userId)
1417                     & STRONG_AUTH_REQUIRED_AFTER_BOOT) == 0;
1418         }
1419 
1420         @Override
onStrongAuthRequiredChanged(int userId)1421         public void onStrongAuthRequiredChanged(int userId) {
1422             mStrongAuthRequiredChangedCallback.accept(userId);
1423         }
1424     }
1425 
getInstance(Context context)1426     public static KeyguardUpdateMonitor getInstance(Context context) {
1427         if (sInstance == null) {
1428             sInstance = new KeyguardUpdateMonitor(context);
1429         }
1430         return sInstance;
1431     }
1432 
handleStartedWakingUp()1433     protected void handleStartedWakingUp() {
1434         Trace.beginSection("KeyguardUpdateMonitor#handleStartedWakingUp");
1435         updateBiometricListeningState();
1436         final int count = mCallbacks.size();
1437         for (int i = 0; i < count; i++) {
1438             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1439             if (cb != null) {
1440                 cb.onStartedWakingUp();
1441             }
1442         }
1443         Trace.endSection();
1444     }
1445 
handleStartedGoingToSleep(int arg1)1446     protected void handleStartedGoingToSleep(int arg1) {
1447         mLockIconPressed = false;
1448         clearBiometricRecognized();
1449         final int count = mCallbacks.size();
1450         for (int i = 0; i < count; i++) {
1451             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1452             if (cb != null) {
1453                 cb.onStartedGoingToSleep(arg1);
1454             }
1455         }
1456         mGoingToSleep = true;
1457         updateBiometricListeningState();
1458     }
1459 
handleFinishedGoingToSleep(int arg1)1460     protected void handleFinishedGoingToSleep(int arg1) {
1461         mGoingToSleep = false;
1462         final int count = mCallbacks.size();
1463         for (int i = 0; i < count; i++) {
1464             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1465             if (cb != null) {
1466                 cb.onFinishedGoingToSleep(arg1);
1467             }
1468         }
1469         updateBiometricListeningState();
1470     }
1471 
handleScreenTurnedOn()1472     private void handleScreenTurnedOn() {
1473         final int count = mCallbacks.size();
1474         for (int i = 0; i < count; i++) {
1475             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1476             if (cb != null) {
1477                 cb.onScreenTurnedOn();
1478             }
1479         }
1480     }
1481 
handleScreenTurnedOff()1482     private void handleScreenTurnedOff() {
1483         mHardwareFingerprintUnavailableRetryCount = 0;
1484         mHardwareFaceUnavailableRetryCount = 0;
1485         final int count = mCallbacks.size();
1486         for (int i = 0; i < count; i++) {
1487             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1488             if (cb != null) {
1489                 cb.onScreenTurnedOff();
1490             }
1491         }
1492     }
1493 
handleDreamingStateChanged(int dreamStart)1494     private void handleDreamingStateChanged(int dreamStart) {
1495         final int count = mCallbacks.size();
1496         mIsDreaming = dreamStart == 1;
1497         for (int i = 0; i < count; i++) {
1498             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1499             if (cb != null) {
1500                 cb.onDreamingStateChanged(mIsDreaming);
1501             }
1502         }
1503         updateBiometricListeningState();
1504     }
1505 
handleUserInfoChanged(int userId)1506     private void handleUserInfoChanged(int userId) {
1507         for (int i = 0; i < mCallbacks.size(); i++) {
1508             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1509             if (cb != null) {
1510                 cb.onUserInfoChanged(userId);
1511             }
1512         }
1513     }
1514 
handleUserUnlocked()1515     private void handleUserUnlocked() {
1516         mNeedsSlowUnlockTransition = resolveNeedsSlowUnlockTransition();
1517         for (int i = 0; i < mCallbacks.size(); i++) {
1518             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1519             if (cb != null) {
1520                 cb.onUserUnlocked();
1521             }
1522         }
1523     }
1524 
1525     @VisibleForTesting
KeyguardUpdateMonitor(Context context)1526     protected KeyguardUpdateMonitor(Context context) {
1527         mContext = context;
1528         mSubscriptionManager = SubscriptionManager.from(context);
1529         mDeviceProvisioned = isDeviceProvisionedInSettingsDb();
1530         mStrongAuthTracker = new StrongAuthTracker(context, this::notifyStrongAuthStateChanged);
1531 
1532         // Since device can't be un-provisioned, we only need to register a content observer
1533         // to update mDeviceProvisioned when we are...
1534         if (!mDeviceProvisioned) {
1535             watchForDeviceProvisioning();
1536         }
1537 
1538         // Take a guess at initial SIM state, battery status and PLMN until we get an update
1539         mBatteryStatus = new BatteryStatus(BATTERY_STATUS_UNKNOWN, 100, 0, 0, 0);
1540 
1541         // Watch for interesting updates
1542         final IntentFilter filter = new IntentFilter();
1543         filter.addAction(Intent.ACTION_TIME_TICK);
1544         filter.addAction(Intent.ACTION_TIME_CHANGED);
1545         filter.addAction(Intent.ACTION_BATTERY_CHANGED);
1546         filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
1547         filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
1548         filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
1549         filter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
1550         filter.addAction(TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED);
1551         filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
1552         filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
1553         filter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
1554         context.registerReceiver(mBroadcastReceiver, filter, null, mHandler);
1555 
1556         final IntentFilter bootCompleteFilter = new IntentFilter();
1557         bootCompleteFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1558         bootCompleteFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
1559         context.registerReceiver(mBroadcastReceiver, bootCompleteFilter, null, mHandler);
1560 
1561         final IntentFilter allUserFilter = new IntentFilter();
1562         allUserFilter.addAction(Intent.ACTION_USER_INFO_CHANGED);
1563         allUserFilter.addAction(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
1564         allUserFilter.addAction(ACTION_FACE_UNLOCK_STARTED);
1565         allUserFilter.addAction(ACTION_FACE_UNLOCK_STOPPED);
1566         allUserFilter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
1567         allUserFilter.addAction(ACTION_USER_UNLOCKED);
1568         context.registerReceiverAsUser(mBroadcastAllReceiver, UserHandle.ALL, allUserFilter,
1569                 null, mHandler);
1570 
1571         mSubscriptionManager.addOnSubscriptionsChangedListener(mSubscriptionListener);
1572         try {
1573             ActivityManager.getService().registerUserSwitchObserver(
1574                     new UserSwitchObserver() {
1575                         @Override
1576                         public void onUserSwitching(int newUserId, IRemoteCallback reply) {
1577                             mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_SWITCHING,
1578                                     newUserId, 0, reply));
1579                         }
1580                         @Override
1581                         public void onUserSwitchComplete(int newUserId) throws RemoteException {
1582                             mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_SWITCH_COMPLETE,
1583                                     newUserId, 0));
1584                         }
1585                     }, TAG);
1586         } catch (RemoteException e) {
1587             e.rethrowAsRuntimeException();
1588         }
1589 
1590         mTrustManager = (TrustManager) context.getSystemService(Context.TRUST_SERVICE);
1591         mTrustManager.registerTrustListener(this);
1592         mLockPatternUtils = new LockPatternUtils(context);
1593         mLockPatternUtils.registerStrongAuthTracker(mStrongAuthTracker);
1594 
1595         mDreamManager = IDreamManager.Stub.asInterface(
1596                 ServiceManager.getService(DreamService.DREAM_SERVICE));
1597 
1598         if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
1599             mFpm = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
1600         }
1601         if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) {
1602             mFaceManager = (FaceManager) context.getSystemService(Context.FACE_SERVICE);
1603         }
1604 
1605         if (mFpm != null || mFaceManager != null) {
1606             mBiometricManager = context.getSystemService(BiometricManager.class);
1607             mBiometricManager.registerEnabledOnKeyguardCallback(mBiometricEnabledCallback);
1608         }
1609 
1610         updateBiometricListeningState();
1611         if (mFpm != null) {
1612             mFpm.addLockoutResetCallback(mFingerprintLockoutResetCallback);
1613         }
1614         if (mFaceManager != null) {
1615             mFaceManager.addLockoutResetCallback(mFaceLockoutResetCallback);
1616         }
1617 
1618         ActivityManagerWrapper.getInstance().registerTaskStackListener(mTaskStackListener);
1619         mUserManager = context.getSystemService(UserManager.class);
1620         mIsPrimaryUser = mUserManager.isPrimaryUser();
1621         mDevicePolicyManager = context.getSystemService(DevicePolicyManager.class);
1622         mLogoutEnabled = mDevicePolicyManager.isLogoutEnabled();
1623         updateAirplaneModeState();
1624 
1625         TelephonyManager telephony =
1626                 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
1627         if (telephony != null) {
1628             telephony.listen(mPhoneStateListener, LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE);
1629         }
1630     }
1631 
updateAirplaneModeState()1632     private void updateAirplaneModeState() {
1633         // ACTION_AIRPLANE_MODE_CHANGED do not broadcast if device set AirplaneMode ON and boot
1634         if (!WirelessUtils.isAirplaneModeOn(mContext)
1635                 || mHandler.hasMessages(MSG_AIRPLANE_MODE_CHANGED)) {
1636             return;
1637         }
1638         mHandler.sendEmptyMessage(MSG_AIRPLANE_MODE_CHANGED);
1639     }
1640 
updateBiometricListeningState()1641     private void updateBiometricListeningState() {
1642         updateFingerprintListeningState();
1643         updateFaceListeningState();
1644     }
1645 
updateFingerprintListeningState()1646     private void updateFingerprintListeningState() {
1647         // If this message exists, we should not authenticate again until this message is
1648         // consumed by the handler
1649         if (mHandler.hasMessages(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE)) {
1650             return;
1651         }
1652         mHandler.removeCallbacks(mRetryFingerprintAuthentication);
1653         boolean shouldListenForFingerprint = shouldListenForFingerprint();
1654         boolean runningOrRestarting = mFingerprintRunningState == BIOMETRIC_STATE_RUNNING
1655                 || mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING;
1656         if (runningOrRestarting && !shouldListenForFingerprint) {
1657             stopListeningForFingerprint();
1658         } else if (!runningOrRestarting && shouldListenForFingerprint) {
1659             startListeningForFingerprint();
1660         }
1661     }
1662 
1663     /**
1664      * Called whenever passive authentication is requested or aborted by a sensor.
1665      * @param active If the interrupt started or ended.
1666      */
onAuthInterruptDetected(boolean active)1667     public void onAuthInterruptDetected(boolean active) {
1668         if (DEBUG) Log.d(TAG, "onAuthInterruptDetected(" + active + ")");
1669         if (mAuthInterruptActive == active) {
1670             return;
1671         }
1672         mAuthInterruptActive = active;
1673         updateFaceListeningState();
1674     }
1675 
1676     /**
1677      * Requests face authentication if we're on a state where it's allowed.
1678      * This will re-trigger auth in case it fails.
1679      */
requestFaceAuth()1680     public void requestFaceAuth() {
1681         if (DEBUG) Log.d(TAG, "requestFaceAuth()");
1682         updateFaceListeningState();
1683     }
1684 
1685     /**
1686      * In case face auth is running, cancel it.
1687      */
cancelFaceAuth()1688     public void cancelFaceAuth() {
1689         stopListeningForFace();
1690     }
1691 
updateFaceListeningState()1692     private void updateFaceListeningState() {
1693         // If this message exists, we should not authenticate again until this message is
1694         // consumed by the handler
1695         if (mHandler.hasMessages(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE)) {
1696             return;
1697         }
1698         mHandler.removeCallbacks(mRetryFaceAuthentication);
1699         boolean shouldListenForFace = shouldListenForFace();
1700         if (mFaceRunningState == BIOMETRIC_STATE_RUNNING && !shouldListenForFace) {
1701             stopListeningForFace();
1702         } else if (mFaceRunningState != BIOMETRIC_STATE_RUNNING
1703                 && shouldListenForFace) {
1704             startListeningForFace();
1705         }
1706     }
1707 
shouldListenForFingerprintAssistant()1708     private boolean shouldListenForFingerprintAssistant() {
1709         return mAssistantVisible && mKeyguardOccluded
1710                 && !mUserFingerprintAuthenticated.get(getCurrentUser(), false)
1711                 && !mUserHasTrust.get(getCurrentUser(), false);
1712     }
1713 
shouldListenForFaceAssistant()1714     private boolean shouldListenForFaceAssistant() {
1715         return mAssistantVisible && mKeyguardOccluded
1716                 && !mUserFaceAuthenticated.get(getCurrentUser(), false)
1717                 && !mUserHasTrust.get(getCurrentUser(), false);
1718     }
1719 
shouldListenForFingerprint()1720     private boolean shouldListenForFingerprint() {
1721         // Only listen if this KeyguardUpdateMonitor belongs to the primary user. There is an
1722         // instance of KeyguardUpdateMonitor for each user but KeyguardUpdateMonitor is user-aware.
1723         final boolean shouldListen = (mKeyguardIsVisible || !mDeviceInteractive ||
1724                 (mBouncer && !mKeyguardGoingAway) || mGoingToSleep ||
1725                 shouldListenForFingerprintAssistant() || (mKeyguardOccluded && mIsDreaming))
1726                 && !mSwitchingUser && !isFingerprintDisabled(getCurrentUser())
1727                 && (!mKeyguardGoingAway || !mDeviceInteractive) && mIsPrimaryUser;
1728         return shouldListen;
1729     }
1730 
1731     /**
1732      * If face auth is allows to scan on this exact moment.
1733      */
shouldListenForFace()1734     public boolean shouldListenForFace() {
1735         final boolean awakeKeyguard = mKeyguardIsVisible && mDeviceInteractive && !mGoingToSleep;
1736         final int user = getCurrentUser();
1737         final int strongAuth = mStrongAuthTracker.getStrongAuthForUser(user);
1738         final boolean isLockOutOrLockDown =
1739                 containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_LOCKOUT)
1740                         || containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW)
1741                         || containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN);
1742         final boolean isEncryptedOrTimedOut =
1743                 containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_BOOT)
1744                         || containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_TIMEOUT);
1745 
1746         boolean canBypass = mKeyguardBypassController != null
1747                 && mKeyguardBypassController.canBypass();
1748         // There's no reason to ask the HAL for authentication when the user can dismiss the
1749         // bouncer, unless we're bypassing and need to auto-dismiss the lock screen even when
1750         // TrustAgents or biometrics are keeping the device unlocked.
1751         boolean becauseCannotSkipBouncer = !getUserCanSkipBouncer(user) || canBypass;
1752 
1753         // Scan even when encrypted or timeout to show a preemptive bouncer when bypassing.
1754         // Lockout/lockdown modes shouldn't scan, since they are more explicit.
1755         boolean strongAuthAllowsScanning = (!isEncryptedOrTimedOut || canBypass && !mBouncer)
1756                 && !isLockOutOrLockDown;
1757 
1758         // Only listen if this KeyguardUpdateMonitor belongs to the primary user. There is an
1759         // instance of KeyguardUpdateMonitor for each user but KeyguardUpdateMonitor is user-aware.
1760         return (mBouncer || mAuthInterruptActive || awakeKeyguard || shouldListenForFaceAssistant())
1761                 && !mSwitchingUser && !isFaceDisabled(user) && becauseCannotSkipBouncer
1762                 && !mKeyguardGoingAway && mFaceSettingEnabledForUser.get(user) && !mLockIconPressed
1763                 && strongAuthAllowsScanning && mIsPrimaryUser
1764                 && !mSecureCameraLaunched;
1765     }
1766 
1767     /**
1768      * Whenever the lock icon is long pressed, disabling trust agents.
1769      * This means that we cannot auth passively (face) until the user presses power.
1770      */
onLockIconPressed()1771     public void onLockIconPressed() {
1772         mLockIconPressed = true;
1773         mUserFaceAuthenticated.put(getCurrentUser(), false);
1774         updateFaceListeningState();
1775     }
1776 
startListeningForFingerprint()1777     private void startListeningForFingerprint() {
1778         if (mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING) {
1779             setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING_RESTARTING);
1780             return;
1781         }
1782         if (mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) {
1783             // Waiting for restart via handleFingerprintError().
1784             return;
1785         }
1786         if (DEBUG) Log.v(TAG, "startListeningForFingerprint()");
1787         int userId = getCurrentUser();
1788         if (isUnlockWithFingerprintPossible(userId)) {
1789             if (mFingerprintCancelSignal != null) {
1790                 mFingerprintCancelSignal.cancel();
1791             }
1792             mFingerprintCancelSignal = new CancellationSignal();
1793             mFpm.authenticate(null, mFingerprintCancelSignal, 0, mFingerprintAuthenticationCallback,
1794                     null, userId);
1795             setFingerprintRunningState(BIOMETRIC_STATE_RUNNING);
1796         }
1797     }
1798 
startListeningForFace()1799     private void startListeningForFace() {
1800         if (mFaceRunningState == BIOMETRIC_STATE_CANCELLING) {
1801             setFaceRunningState(BIOMETRIC_STATE_CANCELLING_RESTARTING);
1802             return;
1803         }
1804         if (DEBUG) Log.v(TAG, "startListeningForFace()");
1805         int userId = getCurrentUser();
1806         if (isUnlockWithFacePossible(userId)) {
1807             if (mFaceCancelSignal != null) {
1808                 mFaceCancelSignal.cancel();
1809             }
1810             mFaceCancelSignal = new CancellationSignal();
1811             mFaceManager.authenticate(null, mFaceCancelSignal, 0,
1812                     mFaceAuthenticationCallback, null, userId);
1813             setFaceRunningState(BIOMETRIC_STATE_RUNNING);
1814         }
1815     }
1816 
1817     /**
1818      * If biometrics hardware is available, not disabled, and user has enrolled templates.
1819      * This does NOT check if the device is encrypted or in lockdown.
1820      *
1821      * @param userId User that's trying to unlock.
1822      * @return {@code true} if possible.
1823      */
isUnlockingWithBiometricsPossible(int userId)1824     public boolean isUnlockingWithBiometricsPossible(int userId) {
1825         return isUnlockWithFacePossible(userId) || isUnlockWithFingerprintPossible(userId);
1826     }
1827 
isUnlockWithFingerprintPossible(int userId)1828     private boolean isUnlockWithFingerprintPossible(int userId) {
1829         return mFpm != null && mFpm.isHardwareDetected() && !isFingerprintDisabled(userId)
1830                 && mFpm.getEnrolledFingerprints(userId).size() > 0;
1831     }
1832 
isUnlockWithFacePossible(int userId)1833     private boolean isUnlockWithFacePossible(int userId) {
1834         return isFaceAuthEnabledForUser(userId) && !isFaceDisabled(userId);
1835     }
1836 
1837     /**
1838      * If face hardware is available, user has enrolled and enabled auth via setting.
1839      */
isFaceAuthEnabledForUser(int userId)1840     public boolean isFaceAuthEnabledForUser(int userId) {
1841         return mFaceManager != null && mFaceManager.isHardwareDetected()
1842                 && mFaceManager.hasEnrolledTemplates(userId)
1843                 && mFaceSettingEnabledForUser.get(userId);
1844     }
1845 
stopListeningForFingerprint()1846     private void stopListeningForFingerprint() {
1847         if (DEBUG) Log.v(TAG, "stopListeningForFingerprint()");
1848         if (mFingerprintRunningState == BIOMETRIC_STATE_RUNNING) {
1849             if (mFingerprintCancelSignal != null) {
1850                 mFingerprintCancelSignal.cancel();
1851                 mFingerprintCancelSignal = null;
1852             }
1853             setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING);
1854         }
1855         if (mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) {
1856             setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING);
1857         }
1858     }
1859 
stopListeningForFace()1860     private void stopListeningForFace() {
1861         if (DEBUG) Log.v(TAG, "stopListeningForFace()");
1862         if (mFaceRunningState == BIOMETRIC_STATE_RUNNING) {
1863             if (mFaceCancelSignal != null) {
1864                 mFaceCancelSignal.cancel();
1865                 mFaceCancelSignal = null;
1866             }
1867             setFaceRunningState(BIOMETRIC_STATE_CANCELLING);
1868         }
1869         if (mFaceRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) {
1870             setFaceRunningState(BIOMETRIC_STATE_CANCELLING);
1871         }
1872     }
1873 
isDeviceProvisionedInSettingsDb()1874     private boolean isDeviceProvisionedInSettingsDb() {
1875         return Settings.Global.getInt(mContext.getContentResolver(),
1876                 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
1877     }
1878 
watchForDeviceProvisioning()1879     private void watchForDeviceProvisioning() {
1880         mDeviceProvisionedObserver = new ContentObserver(mHandler) {
1881             @Override
1882             public void onChange(boolean selfChange) {
1883                 super.onChange(selfChange);
1884                 mDeviceProvisioned = isDeviceProvisionedInSettingsDb();
1885                 if (mDeviceProvisioned) {
1886                     mHandler.sendEmptyMessage(MSG_DEVICE_PROVISIONED);
1887                 }
1888                 if (DEBUG) Log.d(TAG, "DEVICE_PROVISIONED state = " + mDeviceProvisioned);
1889             }
1890         };
1891 
1892         mContext.getContentResolver().registerContentObserver(
1893                 Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED),
1894                 false, mDeviceProvisionedObserver);
1895 
1896         // prevent a race condition between where we check the flag and where we register the
1897         // observer by grabbing the value once again...
1898         boolean provisioned = isDeviceProvisionedInSettingsDb();
1899         if (provisioned != mDeviceProvisioned) {
1900             mDeviceProvisioned = provisioned;
1901             if (mDeviceProvisioned) {
1902                 mHandler.sendEmptyMessage(MSG_DEVICE_PROVISIONED);
1903             }
1904         }
1905     }
1906 
1907     /**
1908      * Update the state whether Keyguard currently has a lockscreen wallpaper.
1909      *
1910      * @param hasLockscreenWallpaper Whether Keyguard has a lockscreen wallpaper.
1911      */
setHasLockscreenWallpaper(boolean hasLockscreenWallpaper)1912     public void setHasLockscreenWallpaper(boolean hasLockscreenWallpaper) {
1913         checkIsHandlerThread();
1914         if (hasLockscreenWallpaper != mHasLockscreenWallpaper) {
1915             mHasLockscreenWallpaper = hasLockscreenWallpaper;
1916             for (int i = mCallbacks.size() - 1; i >= 0; i--) {
1917                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1918                 if (cb != null) {
1919                     cb.onHasLockscreenWallpaperChanged(hasLockscreenWallpaper);
1920                 }
1921             }
1922         }
1923     }
1924 
1925     /**
1926      * @return Whether Keyguard has a lockscreen wallpaper.
1927      */
hasLockscreenWallpaper()1928     public boolean hasLockscreenWallpaper() {
1929         return mHasLockscreenWallpaper;
1930     }
1931 
1932     /**
1933      * Handle {@link #MSG_DPM_STATE_CHANGED}
1934      */
handleDevicePolicyManagerStateChanged()1935     private void handleDevicePolicyManagerStateChanged() {
1936         updateFingerprintListeningState();
1937         for (int i = mCallbacks.size() - 1; i >= 0; i--) {
1938             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1939             if (cb != null) {
1940                 cb.onDevicePolicyManagerStateChanged();
1941             }
1942         }
1943     }
1944 
1945     /**
1946      * Handle {@link #MSG_USER_SWITCHING}
1947      */
handleUserSwitching(int userId, IRemoteCallback reply)1948     private void handleUserSwitching(int userId, IRemoteCallback reply) {
1949         for (int i = 0; i < mCallbacks.size(); i++) {
1950             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1951             if (cb != null) {
1952                 cb.onUserSwitching(userId);
1953             }
1954         }
1955         try {
1956             reply.sendResult(null);
1957         } catch (RemoteException e) {
1958         }
1959     }
1960 
1961     /**
1962      * Handle {@link #MSG_USER_SWITCH_COMPLETE}
1963      */
handleUserSwitchComplete(int userId)1964     private void handleUserSwitchComplete(int userId) {
1965         for (int i = 0; i < mCallbacks.size(); i++) {
1966             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1967             if (cb != null) {
1968                 cb.onUserSwitchComplete(userId);
1969             }
1970         }
1971     }
1972 
1973     /**
1974      * This is exposed since {@link Intent#ACTION_BOOT_COMPLETED} is not sticky. If
1975      * keyguard crashes sometime after boot, then it will never receive this
1976      * broadcast and hence not handle the event. This method is ultimately called by
1977      * PhoneWindowManager in this case.
1978      */
dispatchBootCompleted()1979     public void dispatchBootCompleted() {
1980         mHandler.sendEmptyMessage(MSG_BOOT_COMPLETED);
1981     }
1982 
1983     /**
1984      * Handle {@link #MSG_BOOT_COMPLETED}
1985      */
handleBootCompleted()1986     private void handleBootCompleted() {
1987         if (mBootCompleted) return;
1988         mBootCompleted = true;
1989         for (int i = 0; i < mCallbacks.size(); i++) {
1990             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
1991             if (cb != null) {
1992                 cb.onBootCompleted();
1993             }
1994         }
1995     }
1996 
1997     /**
1998      * We need to store this state in the KeyguardUpdateMonitor since this class will not be
1999      * destroyed.
2000      */
hasBootCompleted()2001     public boolean hasBootCompleted() {
2002         return mBootCompleted;
2003     }
2004 
2005     /**
2006      * Handle {@link #MSG_DEVICE_PROVISIONED}
2007      */
handleDeviceProvisioned()2008     private void handleDeviceProvisioned() {
2009         for (int i = 0; i < mCallbacks.size(); i++) {
2010             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2011             if (cb != null) {
2012                 cb.onDeviceProvisioned();
2013             }
2014         }
2015         if (mDeviceProvisionedObserver != null) {
2016             // We don't need the observer anymore...
2017             mContext.getContentResolver().unregisterContentObserver(mDeviceProvisionedObserver);
2018             mDeviceProvisionedObserver = null;
2019         }
2020     }
2021 
2022     /**
2023      * Handle {@link #MSG_PHONE_STATE_CHANGED}
2024      */
handlePhoneStateChanged(String newState)2025     private void handlePhoneStateChanged(String newState) {
2026         if (DEBUG) Log.d(TAG, "handlePhoneStateChanged(" + newState + ")");
2027         if (TelephonyManager.EXTRA_STATE_IDLE.equals(newState)) {
2028             mPhoneState = TelephonyManager.CALL_STATE_IDLE;
2029         } else if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(newState)) {
2030             mPhoneState = TelephonyManager.CALL_STATE_OFFHOOK;
2031         } else if (TelephonyManager.EXTRA_STATE_RINGING.equals(newState)) {
2032             mPhoneState = TelephonyManager.CALL_STATE_RINGING;
2033         }
2034         for (int i = 0; i < mCallbacks.size(); i++) {
2035             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2036             if (cb != null) {
2037                 cb.onPhoneStateChanged(mPhoneState);
2038             }
2039         }
2040     }
2041 
2042     /**
2043      * Handle {@link #MSG_RINGER_MODE_CHANGED}
2044      */
handleRingerModeChange(int mode)2045     private void handleRingerModeChange(int mode) {
2046         if (DEBUG) Log.d(TAG, "handleRingerModeChange(" + mode + ")");
2047         mRingMode = mode;
2048         for (int i = 0; i < mCallbacks.size(); i++) {
2049             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2050             if (cb != null) {
2051                 cb.onRingerModeChanged(mode);
2052             }
2053         }
2054     }
2055 
2056     /**
2057      * Handle {@link #MSG_TIME_UPDATE}
2058      */
handleTimeUpdate()2059     private void handleTimeUpdate() {
2060         if (DEBUG) Log.d(TAG, "handleTimeUpdate");
2061         for (int i = 0; i < mCallbacks.size(); i++) {
2062             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2063             if (cb != null) {
2064                 cb.onTimeChanged();
2065             }
2066         }
2067     }
2068 
2069     /**
2070      * Handle (@line #MSG_TIMEZONE_UPDATE}
2071      */
handleTimeZoneUpdate(String timeZone)2072     private void handleTimeZoneUpdate(String timeZone) {
2073         if (DEBUG) Log.d(TAG, "handleTimeZoneUpdate");
2074         for (int i = 0; i < mCallbacks.size(); i++) {
2075             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2076             if (cb != null) {
2077                 cb.onTimeZoneChanged(TimeZone.getTimeZone(timeZone));
2078                 // Also notify callbacks about time change to remain compatible.
2079                 cb.onTimeChanged();
2080             }
2081         }
2082     }
2083 
2084     /**
2085      * Handle {@link #MSG_BATTERY_UPDATE}
2086      */
handleBatteryUpdate(BatteryStatus status)2087     private void handleBatteryUpdate(BatteryStatus status) {
2088         if (DEBUG) Log.d(TAG, "handleBatteryUpdate");
2089         final boolean batteryUpdateInteresting = isBatteryUpdateInteresting(mBatteryStatus, status);
2090         mBatteryStatus = status;
2091         if (batteryUpdateInteresting) {
2092             for (int i = 0; i < mCallbacks.size(); i++) {
2093                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2094                 if (cb != null) {
2095                     cb.onRefreshBatteryInfo(status);
2096                 }
2097             }
2098         }
2099     }
2100 
2101     /**
2102      * Handle Telephony status during Boot for CarrierText display policy
2103      */
2104     @VisibleForTesting
updateTelephonyCapable(boolean capable)2105     void updateTelephonyCapable(boolean capable){
2106         if (capable == mTelephonyCapable) {
2107             return;
2108         }
2109         mTelephonyCapable = capable;
2110         for (WeakReference<KeyguardUpdateMonitorCallback> ref : mCallbacks) {
2111             KeyguardUpdateMonitorCallback cb = ref.get();
2112             if (cb != null) {
2113                 cb.onTelephonyCapable(mTelephonyCapable);
2114             }
2115         }
2116     }
2117 
2118     /**
2119      * Handle {@link #MSG_SIM_STATE_CHANGE}
2120      */
2121     @VisibleForTesting
handleSimStateChange(int subId, int slotId, State state)2122     void handleSimStateChange(int subId, int slotId, State state) {
2123         checkIsHandlerThread();
2124         if (DEBUG_SIM_STATES) {
2125             Log.d(TAG, "handleSimStateChange(subId=" + subId + ", slotId="
2126                     + slotId + ", state=" + state +")");
2127         }
2128 
2129         boolean becameAbsent = false;
2130         if (!SubscriptionManager.isValidSubscriptionId(subId)) {
2131             Log.w(TAG, "invalid subId in handleSimStateChange()");
2132             /* Only handle No SIM(ABSENT) and Card Error(CARD_IO_ERROR) due to
2133              * handleServiceStateChange() handle other case */
2134             if (state == State.ABSENT) {
2135                 updateTelephonyCapable(true);
2136                 // Even though the subscription is not valid anymore, we need to notify that the
2137                 // SIM card was removed so we can update the UI.
2138                 becameAbsent = true;
2139                 for (SimData data : mSimDatas.values()) {
2140                     // Set the SIM state of all SimData associated with that slot to ABSENT se we
2141                     // do not move back into PIN/PUK locked and not detect the change below.
2142                     if (data.slotId == slotId) {
2143                         data.simState = State.ABSENT;
2144                     }
2145                 }
2146             } else if (state == State.CARD_IO_ERROR) {
2147                 updateTelephonyCapable(true);
2148             } else {
2149                 return;
2150             }
2151         }
2152 
2153         SimData data = mSimDatas.get(subId);
2154         final boolean changed;
2155         if (data == null) {
2156             data = new SimData(state, slotId, subId);
2157             mSimDatas.put(subId, data);
2158             changed = true; // no data yet; force update
2159         } else {
2160             changed = (data.simState != state || data.subId != subId || data.slotId != slotId);
2161             data.simState = state;
2162             data.subId = subId;
2163             data.slotId = slotId;
2164         }
2165         if ((changed || becameAbsent) && state != State.UNKNOWN) {
2166             for (int i = 0; i < mCallbacks.size(); i++) {
2167                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2168                 if (cb != null) {
2169                     cb.onSimStateChanged(subId, slotId, state);
2170                 }
2171             }
2172         }
2173     }
2174 
2175     /**
2176      * Handle {@link #MSG_SERVICE_STATE_CHANGE}
2177      */
2178     @VisibleForTesting
handleServiceStateChange(int subId, ServiceState serviceState)2179     void handleServiceStateChange(int subId, ServiceState serviceState) {
2180         if (DEBUG) {
2181             Log.d(TAG,
2182                     "handleServiceStateChange(subId=" + subId + ", serviceState=" + serviceState);
2183         }
2184 
2185         if (!SubscriptionManager.isValidSubscriptionId(subId)) {
2186             Log.w(TAG, "invalid subId in handleServiceStateChange()");
2187             return;
2188         } else {
2189             updateTelephonyCapable(true);
2190         }
2191 
2192         mServiceStates.put(subId, serviceState);
2193 
2194         for (int j = 0; j < mCallbacks.size(); j++) {
2195             KeyguardUpdateMonitorCallback cb = mCallbacks.get(j).get();
2196             if (cb != null) {
2197                 cb.onRefreshCarrierInfo();
2198             }
2199         }
2200     }
2201 
isKeyguardVisible()2202     public boolean isKeyguardVisible() {
2203         return mKeyguardIsVisible;
2204     }
2205 
2206     /**
2207      * Notifies that the visibility state of Keyguard has changed.
2208      *
2209      * <p>Needs to be called from the main thread.
2210      */
onKeyguardVisibilityChanged(boolean showing)2211     public void onKeyguardVisibilityChanged(boolean showing) {
2212         checkIsHandlerThread();
2213         Log.d(TAG, "onKeyguardVisibilityChanged(" + showing + ")");
2214         mKeyguardIsVisible = showing;
2215 
2216         if (showing) {
2217             mSecureCameraLaunched = false;
2218         }
2219 
2220         for (int i = 0; i < mCallbacks.size(); i++) {
2221             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2222             if (cb != null) {
2223                 cb.onKeyguardVisibilityChangedRaw(showing);
2224             }
2225         }
2226         updateBiometricListeningState();
2227     }
2228 
2229     /**
2230      * Handle {@link #MSG_KEYGUARD_RESET}
2231      */
handleKeyguardReset()2232     private void handleKeyguardReset() {
2233         if (DEBUG) Log.d(TAG, "handleKeyguardReset");
2234         updateBiometricListeningState();
2235         mNeedsSlowUnlockTransition = resolveNeedsSlowUnlockTransition();
2236     }
2237 
resolveNeedsSlowUnlockTransition()2238     private boolean resolveNeedsSlowUnlockTransition() {
2239         if (mUserManager.isUserUnlocked(getCurrentUser())) {
2240             return false;
2241         }
2242         Intent homeIntent = new Intent(Intent.ACTION_MAIN)
2243                 .addCategory(Intent.CATEGORY_HOME);
2244         ResolveInfo resolveInfo = mContext.getPackageManager().resolveActivity(homeIntent,
2245                 0 /* flags */);
2246         return FALLBACK_HOME_COMPONENT.equals(resolveInfo.getComponentInfo().getComponentName());
2247     }
2248 
2249     /**
2250      * Handle {@link #MSG_KEYGUARD_BOUNCER_CHANGED}
2251      * @see #sendKeyguardBouncerChanged(boolean)
2252      */
handleKeyguardBouncerChanged(int bouncer)2253     private void handleKeyguardBouncerChanged(int bouncer) {
2254         if (DEBUG) Log.d(TAG, "handleKeyguardBouncerChanged(" + bouncer + ")");
2255         boolean isBouncer = (bouncer == 1);
2256         mBouncer = isBouncer;
2257 
2258         if (isBouncer) {
2259             // If the bouncer is shown, always clear this flag. This can happen in the following
2260             // situations: 1) Default camera with SHOW_WHEN_LOCKED is not chosen yet. 2) Secure
2261             // camera requests dismiss keyguard (tapping on photos for example). When these happen,
2262             // face auth should resume.
2263             mSecureCameraLaunched = false;
2264         }
2265 
2266         for (int i = 0; i < mCallbacks.size(); i++) {
2267             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2268             if (cb != null) {
2269                 cb.onKeyguardBouncerChanged(isBouncer);
2270             }
2271         }
2272         updateBiometricListeningState();
2273     }
2274 
2275     /**
2276      * Handle {@link #MSG_REPORT_EMERGENCY_CALL_ACTION}
2277      */
handleReportEmergencyCallAction()2278     private void handleReportEmergencyCallAction() {
2279         for (int i = 0; i < mCallbacks.size(); i++) {
2280             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2281             if (cb != null) {
2282                 cb.onEmergencyCallAction();
2283             }
2284         }
2285     }
2286 
isBatteryUpdateInteresting(BatteryStatus old, BatteryStatus current)2287     private boolean isBatteryUpdateInteresting(BatteryStatus old, BatteryStatus current) {
2288         final boolean nowPluggedIn = current.isPluggedIn();
2289         final boolean wasPluggedIn = old.isPluggedIn();
2290         final boolean stateChangedWhilePluggedIn = wasPluggedIn && nowPluggedIn
2291             && (old.status != current.status);
2292 
2293         // change in plug state is always interesting
2294         if (wasPluggedIn != nowPluggedIn || stateChangedWhilePluggedIn) {
2295             return true;
2296         }
2297 
2298         // change in battery level
2299         if (old.level != current.level) {
2300             return true;
2301         }
2302 
2303         // change in charging current while plugged in
2304         if (nowPluggedIn && current.maxChargingWattage != old.maxChargingWattage) {
2305             return true;
2306         }
2307 
2308         return false;
2309     }
2310 
2311     /**
2312      * Remove the given observer's callback.
2313      *
2314      * @param callback The callback to remove
2315      */
removeCallback(KeyguardUpdateMonitorCallback callback)2316     public void removeCallback(KeyguardUpdateMonitorCallback callback) {
2317         checkIsHandlerThread();
2318         if (DEBUG) Log.v(TAG, "*** unregister callback for " + callback);
2319         for (int i = mCallbacks.size() - 1; i >= 0; i--) {
2320             if (mCallbacks.get(i).get() == callback) {
2321                 mCallbacks.remove(i);
2322             }
2323         }
2324     }
2325 
2326     /**
2327      * Register to receive notifications about general keyguard information
2328      * (see {@link InfoCallback}.
2329      * @param callback The callback to register
2330      */
registerCallback(KeyguardUpdateMonitorCallback callback)2331     public void registerCallback(KeyguardUpdateMonitorCallback callback) {
2332         checkIsHandlerThread();
2333         if (DEBUG) Log.v(TAG, "*** register callback for " + callback);
2334         // Prevent adding duplicate callbacks
2335         for (int i = 0; i < mCallbacks.size(); i++) {
2336             if (mCallbacks.get(i).get() == callback) {
2337                 if (DEBUG) Log.e(TAG, "Object tried to add another callback",
2338                         new Exception("Called by"));
2339                 return;
2340             }
2341         }
2342         mCallbacks.add(new WeakReference<KeyguardUpdateMonitorCallback>(callback));
2343         removeCallback(null); // remove unused references
2344         sendUpdates(callback);
2345     }
2346 
setKeyguardBypassController(KeyguardBypassController keyguardBypassController)2347     public void setKeyguardBypassController(KeyguardBypassController keyguardBypassController) {
2348         mKeyguardBypassController = keyguardBypassController;
2349     }
2350 
isSwitchingUser()2351     public boolean isSwitchingUser() {
2352         return mSwitchingUser;
2353     }
2354 
2355     @AnyThread
setSwitchingUser(boolean switching)2356     public void setSwitchingUser(boolean switching) {
2357         mSwitchingUser = switching;
2358         // Since this comes in on a binder thread, we need to post if first
2359         mHandler.post(mUpdateBiometricListeningState);
2360     }
2361 
sendUpdates(KeyguardUpdateMonitorCallback callback)2362     private void sendUpdates(KeyguardUpdateMonitorCallback callback) {
2363         // Notify listener of the current state
2364         callback.onRefreshBatteryInfo(mBatteryStatus);
2365         callback.onTimeChanged();
2366         callback.onRingerModeChanged(mRingMode);
2367         callback.onPhoneStateChanged(mPhoneState);
2368         callback.onRefreshCarrierInfo();
2369         callback.onClockVisibilityChanged();
2370         callback.onKeyguardVisibilityChangedRaw(mKeyguardIsVisible);
2371         callback.onTelephonyCapable(mTelephonyCapable);
2372         for (Entry<Integer, SimData> data : mSimDatas.entrySet()) {
2373             final SimData state = data.getValue();
2374             callback.onSimStateChanged(state.subId, state.slotId, state.simState);
2375         }
2376     }
2377 
sendKeyguardReset()2378     public void sendKeyguardReset() {
2379         mHandler.obtainMessage(MSG_KEYGUARD_RESET).sendToTarget();
2380     }
2381 
2382     /**
2383      * @see #handleKeyguardBouncerChanged(int)
2384      */
sendKeyguardBouncerChanged(boolean showingBouncer)2385     public void sendKeyguardBouncerChanged(boolean showingBouncer) {
2386         if (DEBUG) Log.d(TAG, "sendKeyguardBouncerChanged(" + showingBouncer + ")");
2387         Message message = mHandler.obtainMessage(MSG_KEYGUARD_BOUNCER_CHANGED);
2388         message.arg1 = showingBouncer ? 1 : 0;
2389         message.sendToTarget();
2390     }
2391 
2392     /**
2393      * Report that the user successfully entered the SIM PIN or PUK/SIM PIN so we
2394      * have the information earlier than waiting for the intent
2395      * broadcast from the telephony code.
2396      *
2397      * NOTE: Because handleSimStateChange() invokes callbacks immediately without going
2398      * through mHandler, this *must* be called from the UI thread.
2399      */
2400     @MainThread
reportSimUnlocked(int subId)2401     public void reportSimUnlocked(int subId) {
2402         if (DEBUG_SIM_STATES) Log.v(TAG, "reportSimUnlocked(subId=" + subId + ")");
2403         int slotId = SubscriptionManager.getSlotIndex(subId);
2404         handleSimStateChange(subId, slotId, State.READY);
2405     }
2406 
2407     /**
2408      * Report that the emergency call button has been pressed and the emergency dialer is
2409      * about to be displayed.
2410      *
2411      * @param bypassHandler runs immediately.
2412      *
2413      * NOTE: Must be called from UI thread if bypassHandler == true.
2414      */
reportEmergencyCallAction(boolean bypassHandler)2415     public void reportEmergencyCallAction(boolean bypassHandler) {
2416         if (!bypassHandler) {
2417             mHandler.obtainMessage(MSG_REPORT_EMERGENCY_CALL_ACTION).sendToTarget();
2418         } else {
2419             checkIsHandlerThread();
2420             handleReportEmergencyCallAction();
2421         }
2422     }
2423 
2424     /**
2425      * @return Whether the device is provisioned (whether they have gone through
2426      *   the setup wizard)
2427      */
isDeviceProvisioned()2428     public boolean isDeviceProvisioned() {
2429         return mDeviceProvisioned;
2430     }
2431 
getServiceState(int subId)2432     public ServiceState getServiceState(int subId) {
2433         return mServiceStates.get(subId);
2434     }
2435 
clearBiometricRecognized()2436     public void clearBiometricRecognized() {
2437         mUserFingerprintAuthenticated.clear();
2438         mUserFaceAuthenticated.clear();
2439         mTrustManager.clearAllBiometricRecognized(BiometricSourceType.FINGERPRINT);
2440         mTrustManager.clearAllBiometricRecognized(BiometricSourceType.FACE);
2441 
2442         for (int i = 0; i < mCallbacks.size(); i++) {
2443             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2444             if (cb != null) {
2445                 cb.onBiometricsCleared();
2446             }
2447         }
2448     }
2449 
isSimPinVoiceSecure()2450     public boolean isSimPinVoiceSecure() {
2451         // TODO: only count SIMs that handle voice
2452         return isSimPinSecure();
2453     }
2454 
2455     /**
2456      * If any SIM cards are currently secure.
2457      * @see #isSimPinSecure(State)
2458      */
isSimPinSecure()2459     public boolean isSimPinSecure() {
2460         // True if any SIM is pin secure
2461         for (SubscriptionInfo info : getSubscriptionInfo(false /* forceReload */)) {
2462             if (isSimPinSecure(getSimState(info.getSubscriptionId()))) return true;
2463         }
2464         return false;
2465     }
2466 
getSimState(int subId)2467     public State getSimState(int subId) {
2468         if (mSimDatas.containsKey(subId)) {
2469             return mSimDatas.get(subId).simState;
2470         } else {
2471             return State.UNKNOWN;
2472         }
2473     }
2474 
2475     private final TaskStackChangeListener
2476             mTaskStackListener = new TaskStackChangeListener() {
2477         @Override
2478         public void onTaskStackChangedBackground() {
2479             try {
2480                 ActivityManager.StackInfo info = ActivityTaskManager.getService().getStackInfo(
2481                         WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_ASSISTANT);
2482                 if (info == null) {
2483                     return;
2484                 }
2485                 mHandler.sendMessage(mHandler.obtainMessage(MSG_ASSISTANT_STACK_CHANGED,
2486                         info.visible));
2487             } catch (RemoteException e) {
2488                 Log.e(TAG, "unable to check task stack", e);
2489             }
2490         }
2491     };
2492 
2493     /**
2494      * @return true if and only if the state has changed for the specified {@code slotId}
2495      */
refreshSimState(int subId, int slotId)2496     private boolean refreshSimState(int subId, int slotId) {
2497 
2498         // This is awful. It exists because there are two APIs for getting the SIM status
2499         // that don't return the complete set of values and have different types. In Keyguard we
2500         // need IccCardConstants, but TelephonyManager would only give us
2501         // TelephonyManager.SIM_STATE*, so we retrieve it manually.
2502         final TelephonyManager tele = TelephonyManager.from(mContext);
2503         int simState =  tele.getSimState(slotId);
2504         State state;
2505         try {
2506             state = State.intToState(simState);
2507         } catch(IllegalArgumentException ex) {
2508             Log.w(TAG, "Unknown sim state: " + simState);
2509             state = State.UNKNOWN;
2510         }
2511         SimData data = mSimDatas.get(subId);
2512         final boolean changed;
2513         if (data == null) {
2514             data = new SimData(state, slotId, subId);
2515             mSimDatas.put(subId, data);
2516             changed = true; // no data yet; force update
2517         } else {
2518             changed = data.simState != state;
2519             data.simState = state;
2520         }
2521         return changed;
2522     }
2523 
2524     /**
2525      * If the {@code state} is currently requiring a SIM PIN, PUK, or is disabled.
2526      */
isSimPinSecure(IccCardConstants.State state)2527     public static boolean isSimPinSecure(IccCardConstants.State state) {
2528         return (state == IccCardConstants.State.PIN_REQUIRED
2529                 || state == IccCardConstants.State.PUK_REQUIRED
2530                 || state == IccCardConstants.State.PERM_DISABLED);
2531     }
2532 
getCachedDisplayClientState()2533     public DisplayClientState getCachedDisplayClientState() {
2534         return mDisplayClientState;
2535     }
2536 
2537     // TODO: use these callbacks elsewhere in place of the existing notifyScreen*()
2538     // (KeyguardViewMediator, KeyguardHostView)
dispatchStartedWakingUp()2539     public void dispatchStartedWakingUp() {
2540         synchronized (this) {
2541             mDeviceInteractive = true;
2542         }
2543         mHandler.sendEmptyMessage(MSG_STARTED_WAKING_UP);
2544     }
2545 
dispatchStartedGoingToSleep(int why)2546     public void dispatchStartedGoingToSleep(int why) {
2547         mHandler.sendMessage(mHandler.obtainMessage(MSG_STARTED_GOING_TO_SLEEP, why, 0));
2548     }
2549 
dispatchFinishedGoingToSleep(int why)2550     public void dispatchFinishedGoingToSleep(int why) {
2551         synchronized(this) {
2552             mDeviceInteractive = false;
2553         }
2554         mHandler.sendMessage(mHandler.obtainMessage(MSG_FINISHED_GOING_TO_SLEEP, why, 0));
2555     }
2556 
dispatchScreenTurnedOn()2557     public void dispatchScreenTurnedOn() {
2558         synchronized (this) {
2559             mScreenOn = true;
2560         }
2561         mHandler.sendEmptyMessage(MSG_SCREEN_TURNED_ON);
2562     }
2563 
dispatchScreenTurnedOff()2564     public void dispatchScreenTurnedOff() {
2565         synchronized(this) {
2566             mScreenOn = false;
2567         }
2568         mHandler.sendEmptyMessage(MSG_SCREEN_TURNED_OFF);
2569     }
2570 
dispatchDreamingStarted()2571     public void dispatchDreamingStarted() {
2572         mHandler.sendMessage(mHandler.obtainMessage(MSG_DREAMING_STATE_CHANGED, 1, 0));
2573     }
2574 
dispatchDreamingStopped()2575     public void dispatchDreamingStopped() {
2576         mHandler.sendMessage(mHandler.obtainMessage(MSG_DREAMING_STATE_CHANGED, 0, 0));
2577     }
2578 
isDeviceInteractive()2579     public boolean isDeviceInteractive() {
2580         return mDeviceInteractive;
2581     }
2582 
isGoingToSleep()2583     public boolean isGoingToSleep() {
2584         return mGoingToSleep;
2585     }
2586 
2587     /**
2588      * Find the next SubscriptionId for a SIM in the given state, favoring lower slot numbers first.
2589      * @param state
2590      * @return subid or {@link SubscriptionManager#INVALID_SUBSCRIPTION_ID} if none found
2591      */
getNextSubIdForState(State state)2592     public int getNextSubIdForState(State state) {
2593         List<SubscriptionInfo> list = getSubscriptionInfo(false /* forceReload */);
2594         int resultId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
2595         int bestSlotId = Integer.MAX_VALUE; // Favor lowest slot first
2596         for (int i = 0; i < list.size(); i++) {
2597             final SubscriptionInfo info = list.get(i);
2598             final int id = info.getSubscriptionId();
2599             int slotId = SubscriptionManager.getSlotIndex(id);
2600             if (state == getSimState(id) && bestSlotId > slotId ) {
2601                 resultId = id;
2602                 bestSlotId = slotId;
2603             }
2604         }
2605         return resultId;
2606     }
2607 
getSubscriptionInfoForSubId(int subId)2608     public SubscriptionInfo getSubscriptionInfoForSubId(int subId) {
2609         List<SubscriptionInfo> list = getSubscriptionInfo(false /* forceReload */);
2610         for (int i = 0; i < list.size(); i++) {
2611             SubscriptionInfo info = list.get(i);
2612             if (subId == info.getSubscriptionId()) return info;
2613         }
2614         return null; // not found
2615     }
2616 
2617     /**
2618      * @return a cached version of DevicePolicyManager.isLogoutEnabled()
2619      */
isLogoutEnabled()2620     public boolean isLogoutEnabled() {
2621         return mLogoutEnabled;
2622     }
2623 
updateLogoutEnabled()2624     private void updateLogoutEnabled() {
2625         checkIsHandlerThread();
2626         boolean logoutEnabled = mDevicePolicyManager.isLogoutEnabled();
2627         if (mLogoutEnabled != logoutEnabled) {
2628             mLogoutEnabled = logoutEnabled;
2629             for (int i = 0; i < mCallbacks.size(); i++) {
2630                 KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
2631                 if (cb != null) {
2632                     cb.onLogoutEnabledChanged();
2633                 }
2634             }
2635         }
2636     }
2637 
checkIsHandlerThread()2638     private void checkIsHandlerThread() {
2639         if (sDisableHandlerCheckForTesting) {
2640             return;
2641         }
2642         if (!mHandler.getLooper().isCurrentThread()) {
2643             Log.wtf(TAG, "must call on mHandler's thread "
2644                     + mHandler.getLooper().getThread() + ", not " + Thread.currentThread());
2645         }
2646     }
2647 
2648     /**
2649      * Turn off the handler check for testing.
2650      *
2651      * This is necessary because currently tests are not too careful about which thread they call
2652      * into this class on.
2653      *
2654      * Note that this must be called before scheduling any work involving KeyguardUpdateMonitor
2655      * instances.
2656      *
2657      * TODO: fix the tests and remove this.
2658      */
2659     @VisibleForTesting
disableHandlerCheckForTesting(Instrumentation instrumentation)2660     public static void disableHandlerCheckForTesting(Instrumentation instrumentation) {
2661         Preconditions.checkNotNull(instrumentation, "Must only call this method in tests!");
2662         // Don't need synchronization here *if* the callers follow the contract and call this only
2663         // before scheduling work for KeyguardUpdateMonitor on other threads, because the scheduling
2664         // of that work forces a happens-before relationship.
2665         sDisableHandlerCheckForTesting = true;
2666     }
2667 
dump(FileDescriptor fd, PrintWriter pw, String[] args)2668     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2669         pw.println("KeyguardUpdateMonitor state:");
2670         pw.println("  SIM States:");
2671         for (SimData data : mSimDatas.values()) {
2672             pw.println("    " + data.toString());
2673         }
2674         pw.println("  Subs:");
2675         if (mSubscriptionInfo != null) {
2676             for (int i = 0; i < mSubscriptionInfo.size(); i++) {
2677                 pw.println("    " + mSubscriptionInfo.get(i));
2678             }
2679         }
2680         pw.println("  Current active data subId=" + mActiveMobileDataSubscription);
2681         pw.println("  Service states:");
2682         for (int subId : mServiceStates.keySet()) {
2683             pw.println("    " + subId + "=" + mServiceStates.get(subId));
2684         }
2685         if (mFpm != null && mFpm.isHardwareDetected()) {
2686             final int userId = ActivityManager.getCurrentUser();
2687             final int strongAuthFlags = mStrongAuthTracker.getStrongAuthForUser(userId);
2688             pw.println("  Fingerprint state (user=" + userId + ")");
2689             pw.println("    allowed=" + isUnlockingWithBiometricAllowed());
2690             pw.println("    auth'd=" + mUserFingerprintAuthenticated.get(userId));
2691             pw.println("    authSinceBoot="
2692                     + getStrongAuthTracker().hasUserAuthenticatedSinceBoot());
2693             pw.println("    disabled(DPM)=" + isFingerprintDisabled(userId));
2694             pw.println("    possible=" + isUnlockWithFingerprintPossible(userId));
2695             pw.println("    listening: actual=" + mFingerprintRunningState
2696                     + " expected=" + (shouldListenForFingerprint() ? 1 : 0));
2697             pw.println("    strongAuthFlags=" + Integer.toHexString(strongAuthFlags));
2698             pw.println("    trustManaged=" + getUserTrustIsManaged(userId));
2699         }
2700         if (mFaceManager != null && mFaceManager.isHardwareDetected()) {
2701             final int userId = ActivityManager.getCurrentUser();
2702             final int strongAuthFlags = mStrongAuthTracker.getStrongAuthForUser(userId);
2703             pw.println("  Face authentication state (user=" + userId + ")");
2704             pw.println("    allowed=" + isUnlockingWithBiometricAllowed());
2705             pw.println("    auth'd=" + mUserFaceAuthenticated.get(userId));
2706             pw.println("    authSinceBoot="
2707                     + getStrongAuthTracker().hasUserAuthenticatedSinceBoot());
2708             pw.println("    disabled(DPM)=" + isFaceDisabled(userId));
2709             pw.println("    possible=" + isUnlockWithFacePossible(userId));
2710             pw.println("    strongAuthFlags=" + Integer.toHexString(strongAuthFlags));
2711             pw.println("    trustManaged=" + getUserTrustIsManaged(userId));
2712             pw.println("    enabledByUser=" + mFaceSettingEnabledForUser.get(userId));
2713             pw.println("    mSecureCameraLaunched=" + mSecureCameraLaunched);
2714         }
2715     }
2716 }
2717