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