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