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