aboutsummaryrefslogtreecommitdiff
path: root/src/java/com/android/internal/telephony/emergency/EmergencyStateTracker.java
blob: 0692f7d3bd06f393d24f0b55ad0a6a904944f781 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.internal.telephony.emergency;

import static android.telephony.CarrierConfigManager.ImsEmergency.KEY_EMERGENCY_CALLBACK_MODE_SUPPORTED_BOOL;

import static com.android.internal.telephony.emergency.EmergencyConstants.MODE_EMERGENCY_CALLBACK;
import static com.android.internal.telephony.emergency.EmergencyConstants.MODE_EMERGENCY_NONE;
import static com.android.internal.telephony.emergency.EmergencyConstants.MODE_EMERGENCY_WWAN;

import android.annotation.IntDef;
import android.annotation.NonNull;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PersistableBundle;
import android.os.PowerManager;
import android.os.UserHandle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.sysprop.TelephonyProperties;
import android.telephony.AccessNetworkConstants;
import android.telephony.Annotation.DisconnectCauses;
import android.telephony.CarrierConfigManager;
import android.telephony.DisconnectCause;
import android.telephony.EmergencyRegResult;
import android.telephony.NetworkRegistrationInfo;
import android.telephony.PreciseDataConnectionState;
import android.telephony.ServiceState;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyCallback;
import android.telephony.TelephonyManager;
import android.telephony.data.ApnSetting;
import android.util.ArraySet;

import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.telephony.Call;
import com.android.internal.telephony.GsmCdmaPhone;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.PhoneFactory;
import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.telephony.data.PhoneSwitcher;
import com.android.internal.telephony.satellite.SatelliteController;
import com.android.telephony.Rlog;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Consumer;

/**
 * Tracks the emergency call state and notifies listeners of changes to the emergency mode.
 */
public class EmergencyStateTracker {

    private static final String TAG = "EmergencyStateTracker";

    /**
     * Timeout before we continue with the emergency call without waiting for DDS switch response
     * from the modem.
     */
    private static final int DEFAULT_DATA_SWITCH_TIMEOUT_MS = 1000;
    /** Default value for if Emergency Callback Mode is supported. */
    private static final boolean DEFAULT_EMERGENCY_CALLBACK_MODE_SUPPORTED = true;
    /** Default Emergency Callback Mode exit timeout value. */
    private static final long DEFAULT_ECM_EXIT_TIMEOUT_MS = 300000;
    private static final int DEFAULT_EPDN_DISCONNECTION_TIMEOUT_MS = 500;

    /** The emergency types used when setting the emergency mode on modem. */
    @Retention(RetentionPolicy.SOURCE)
    @IntDef(prefix = "EMERGENCY_TYPE_",
            value = {
                    EMERGENCY_TYPE_CALL,
                    EMERGENCY_TYPE_SMS})
    public @interface EmergencyType {}

    /** Indicates the emergency type is call. */
    public static final int EMERGENCY_TYPE_CALL = 1;
    /** Indicates the emergency type is SMS. */
    public static final int EMERGENCY_TYPE_SMS = 2;

    private static final String KEY_NO_SIM_ECBM_SUPPORT = "no_sim_ecbm_support";

    private static EmergencyStateTracker INSTANCE = null;

    private final Context mContext;
    private final CarrierConfigManager mConfigManager;
    private final Handler mHandler;
    private final boolean mIsSuplDdsSwitchRequiredForEmergencyCall;
    private final PowerManager.WakeLock mWakeLock;
    private RadioOnHelper mRadioOnHelper;
    @EmergencyConstants.EmergencyMode
    private int mEmergencyMode = MODE_EMERGENCY_NONE;
    private boolean mWasEmergencyModeSetOnModem;
    private EmergencyRegResult mLastEmergencyRegResult;
    private boolean mIsEmergencyModeInProgress;
    private boolean mIsEmergencyCallStartedDuringEmergencySms;

    /** For emergency calls */
    private final long mEcmExitTimeoutMs;
    // A runnable which is used to automatically exit from Ecm after a period of time.
    private final Runnable mExitEcmRunnable = this::exitEmergencyCallbackMode;
    // Tracks emergency calls by callId that have reached {@link Call.State#ACTIVE}.
    private final Set<String> mActiveEmergencyCalls = new ArraySet<>();
    private Phone mPhoneToExit;
    private int mPdnDisconnectionTimeoutMs = DEFAULT_EPDN_DISCONNECTION_TIMEOUT_MS;
    private final Object mLock = new Object();
    private Phone mPhone;
    // Tracks ongoing emergency callId to handle a second emergency call
    private String mOngoingCallId;
    // Domain of the active emergency call. Assuming here that there will only be one domain active.
    private int mEmergencyCallDomain = NetworkRegistrationInfo.DOMAIN_UNKNOWN;
    private CompletableFuture<Integer> mCallEmergencyModeFuture;
    private boolean mIsInEmergencyCall;
    private boolean mIsInEcm;
    private boolean mIsTestEmergencyNumber;
    private Runnable mOnEcmExitCompleteRunnable;
    private int mOngoingCallProperties;

    /** For emergency SMS */
    private final Set<String> mOngoingEmergencySmsIds = new ArraySet<>();
    private Phone mSmsPhone;
    private CompletableFuture<Integer> mSmsEmergencyModeFuture;
    private boolean mIsTestEmergencyNumberForSms;

    private final android.util.ArrayMap<Integer, Boolean> mNoSimEcbmSupported =
            new android.util.ArrayMap<>();
    private final CarrierConfigManager.CarrierConfigChangeListener mCarrierConfigChangeListener =
            (slotIndex, subId, carrierId, specificCarrierId) -> onCarrierConfigurationChanged(
                    slotIndex, subId);

    /**
     * Listens for Emergency Callback Mode state change intents
     */
    private final BroadcastReceiver mEcmExitReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(
                    TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {

                boolean isInEcm = intent.getBooleanExtra(
                        TelephonyManager.EXTRA_PHONE_IN_ECM_STATE, false);
                Rlog.d(TAG, "Received ACTION_EMERGENCY_CALLBACK_MODE_CHANGED isInEcm = " + isInEcm);

                // If we exit ECM mode, notify all connections.
                if (!isInEcm) {
                    exitEmergencyCallbackMode();
                }
            }
        }
    };

    /**
     * TelephonyCallback used to monitor whether ePDN on cellular network is disconnected or not.
     */
    private final class PreciseDataConnectionStateListener extends TelephonyCallback implements
            TelephonyCallback.PreciseDataConnectionStateListener {
        @Override
        public void onPreciseDataConnectionStateChanged(
                @NonNull PreciseDataConnectionState dataConnectionState) {
            ApnSetting apnSetting = dataConnectionState.getApnSetting();
            if ((apnSetting == null)
                    || ((apnSetting.getApnTypeBitmask() | ApnSetting.TYPE_EMERGENCY) == 0)
                    || (dataConnectionState.getTransportType()
                            != AccessNetworkConstants.TRANSPORT_TYPE_WWAN)) {
                return;
            }
            int state = dataConnectionState.getState();
            Rlog.d(TAG, "onPreciseDataConnectionStateChanged ePDN state=" + state);
            if (state == TelephonyManager.DATA_DISCONNECTED) exitEmergencyModeIfDelayed();
        }
    }

    private PreciseDataConnectionStateListener mDataConnectionStateListener;

    /** PhoneFactory Dependencies for testing. */
    @VisibleForTesting
    public interface PhoneFactoryProxy {
        Phone[] getPhones();
    }

    private PhoneFactoryProxy mPhoneFactoryProxy = PhoneFactory::getPhones;

    /** PhoneSwitcher dependencies for testing. */
    @VisibleForTesting
    public interface PhoneSwitcherProxy {

        PhoneSwitcher getPhoneSwitcher();
    }

    private PhoneSwitcherProxy mPhoneSwitcherProxy = PhoneSwitcher::getInstance;

    /**
     * TelephonyManager dependencies for testing.
     */
    @VisibleForTesting
    public interface TelephonyManagerProxy {
        int getPhoneCount();
        void registerTelephonyCallback(int subId, Executor executor, TelephonyCallback callback);
        void unregisterTelephonyCallback(TelephonyCallback callback);
    }

    private final TelephonyManagerProxy mTelephonyManagerProxy;

    private static class TelephonyManagerProxyImpl implements TelephonyManagerProxy {
        private final TelephonyManager mTelephonyManager;

        TelephonyManagerProxyImpl(Context context) {
            mTelephonyManager = new TelephonyManager(context);
        }

        @Override
        public int getPhoneCount() {
            return mTelephonyManager.getActiveModemCount();
        }

        @Override
        public void registerTelephonyCallback(int subId,
                Executor executor, TelephonyCallback callback) {
            TelephonyManager tm = mTelephonyManager.createForSubscriptionId(subId);
            tm.registerTelephonyCallback(executor, callback);
        }

        @Override
        public void unregisterTelephonyCallback(TelephonyCallback callback) {
            mTelephonyManager.unregisterTelephonyCallback(callback);
        }
    }

    /**
     * Return the handler for testing.
     */
    @VisibleForTesting
    public Handler getHandler() {
        return mHandler;
    }

    @VisibleForTesting
    public static final int MSG_SET_EMERGENCY_MODE = 1;
    @VisibleForTesting
    public static final int MSG_EXIT_EMERGENCY_MODE = 2;
    @VisibleForTesting
    public static final int MSG_SET_EMERGENCY_MODE_DONE = 3;
    @VisibleForTesting
    public static final int MSG_EXIT_EMERGENCY_MODE_DONE = 4;
    @VisibleForTesting
    public static final int MSG_SET_EMERGENCY_CALLBACK_MODE_DONE = 5;

    private class MyHandler extends Handler {

        MyHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SET_EMERGENCY_MODE_DONE: {
                    AsyncResult ar = (AsyncResult) msg.obj;
                    Integer emergencyType = (Integer) ar.userObj;
                    Rlog.v(TAG, "MSG_SET_EMERGENCY_MODE_DONE for "
                            + emergencyTypeToString(emergencyType));
                    if (ar.exception == null) {
                        mLastEmergencyRegResult = (EmergencyRegResult) ar.result;
                    } else {
                        mLastEmergencyRegResult = null;
                        Rlog.w(TAG, "LastEmergencyRegResult not set. AsyncResult.exception: "
                                + ar.exception);
                    }
                    setEmergencyModeInProgress(false);

                    if (emergencyType == EMERGENCY_TYPE_CALL) {
                        setIsInEmergencyCall(true);
                        completeEmergencyMode(emergencyType);

                        // Case 1) When the emergency call is setting the emergency mode and
                        // the emergency SMS is being sent, completes the SMS future also.
                        // Case 2) When the emergency SMS is setting the emergency mode and
                        // the emergency call is beint started, the SMS request is cancelled and
                        // the call request will be handled.
                        if (mSmsPhone != null) {
                            completeEmergencyMode(EMERGENCY_TYPE_SMS);
                        }
                    } else if (emergencyType == EMERGENCY_TYPE_SMS) {
                        if (mPhone != null && mSmsPhone != null) {
                            // Clear call phone temporarily to exit the emergency mode
                            // if the emergency call is started.
                            if (mIsEmergencyCallStartedDuringEmergencySms) {
                                Phone phone = mPhone;
                                mPhone = null;
                                exitEmergencyMode(mSmsPhone, emergencyType, false);
                                // Restore call phone for further use.
                                mPhone = phone;

                                if (!isSamePhone(mPhone, mSmsPhone)) {
                                    completeEmergencyMode(emergencyType,
                                            DisconnectCause.OUTGOING_EMERGENCY_CALL_PLACED);
                                }
                            } else {
                                completeEmergencyMode(emergencyType);
                            }
                            break;
                        } else {
                            completeEmergencyMode(emergencyType);
                        }

                        if (mIsEmergencyCallStartedDuringEmergencySms) {
                            mIsEmergencyCallStartedDuringEmergencySms = false;
                            turnOnRadioAndSwitchDds(mPhone, EMERGENCY_TYPE_CALL,
                                    mIsTestEmergencyNumber);
                        }
                    }
                    break;
                }
                case MSG_EXIT_EMERGENCY_MODE_DONE: {
                    AsyncResult ar = (AsyncResult) msg.obj;
                    Integer emergencyType = (Integer) ar.userObj;
                    Rlog.v(TAG, "MSG_EXIT_EMERGENCY_MODE_DONE for "
                            + emergencyTypeToString(emergencyType));
                    setEmergencyModeInProgress(false);

                    if (emergencyType == EMERGENCY_TYPE_CALL) {
                        setIsInEmergencyCall(false);
                        if (mOnEcmExitCompleteRunnable != null) {
                            mOnEcmExitCompleteRunnable.run();
                            mOnEcmExitCompleteRunnable = null;
                        }
                    } else if (emergencyType == EMERGENCY_TYPE_SMS) {
                        if (mIsEmergencyCallStartedDuringEmergencySms) {
                            mIsEmergencyCallStartedDuringEmergencySms = false;
                            turnOnRadioAndSwitchDds(mPhone, EMERGENCY_TYPE_CALL,
                                    mIsTestEmergencyNumber);
                        }
                    }
                    break;
                }
                case MSG_SET_EMERGENCY_CALLBACK_MODE_DONE: {
                    AsyncResult ar = (AsyncResult) msg.obj;
                    Integer emergencyType = (Integer) ar.userObj;
                    Rlog.v(TAG, "MSG_SET_EMERGENCY_CALLBACK_MODE_DONE for "
                            + emergencyTypeToString(emergencyType));
                    setEmergencyModeInProgress(false);
                    // When the emergency callback mode is in progress and the emergency SMS is
                    // started, it needs to be completed here for the emergency SMS.
                    if (mSmsPhone != null) {
                        completeEmergencyMode(EMERGENCY_TYPE_SMS);
                    }
                    break;
                }
                case MSG_EXIT_EMERGENCY_MODE: {
                    Rlog.v(TAG, "MSG_EXIT_EMERGENCY_MODE");
                    exitEmergencyModeIfDelayed();
                    break;
                }
                case MSG_SET_EMERGENCY_MODE: {
                    AsyncResult ar = (AsyncResult) msg.obj;
                    Integer emergencyType = (Integer) ar.userObj;
                    Rlog.v(TAG, "MSG_SET_EMERGENCY_MODE for "
                            + emergencyTypeToString(emergencyType) + ", " + mEmergencyMode);
                    // Should be reached here only when starting a new emergency service
                    // while exiting emergency callback mode on the other slot.
                    if (mEmergencyMode != MODE_EMERGENCY_WWAN) return;
                    final Phone phone = (mPhone != null) ? mPhone : mSmsPhone;
                    if (phone != null) {
                        mWasEmergencyModeSetOnModem = true;
                        phone.setEmergencyMode(MODE_EMERGENCY_WWAN,
                                mHandler.obtainMessage(MSG_SET_EMERGENCY_MODE_DONE, emergencyType));
                    }
                    break;
                }
                default:
                    break;
            }
        }
    }

    /**
     * Creates the EmergencyStateTracker singleton instance.
     *
     * @param context                                 The context of the application.
     * @param isSuplDdsSwitchRequiredForEmergencyCall Whether gnss supl requires default data for
     *                                                emergency call.
     */
    public static void make(Context context, boolean isSuplDdsSwitchRequiredForEmergencyCall) {
        if (INSTANCE == null) {
            INSTANCE = new EmergencyStateTracker(context, Looper.myLooper(),
                    isSuplDdsSwitchRequiredForEmergencyCall);
        }
    }

    /**
     * Returns the singleton instance of EmergencyStateTracker.
     *
     * @return {@link EmergencyStateTracker} instance.
     */
    public static EmergencyStateTracker getInstance() {
        if (INSTANCE == null) {
            throw new IllegalStateException("EmergencyStateTracker is not ready!");
        }
        return INSTANCE;
    }

    /**
     * Initializes EmergencyStateTracker.
     */
    private EmergencyStateTracker(Context context, Looper looper,
            boolean isSuplDdsSwitchRequiredForEmergencyCall) {
        mEcmExitTimeoutMs = DEFAULT_ECM_EXIT_TIMEOUT_MS;
        mContext = context;
        mHandler = new MyHandler(looper);
        mIsSuplDdsSwitchRequiredForEmergencyCall = isSuplDdsSwitchRequiredForEmergencyCall;

        PowerManager pm = context.getSystemService(PowerManager.class);
        mWakeLock = (pm != null) ? pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "telephony:" + TAG) : null;
        mConfigManager = context.getSystemService(CarrierConfigManager.class);
        if (mConfigManager != null) {
            // Carrier config changed callback should be executed in handler thread
            mConfigManager.registerCarrierConfigChangeListener(mHandler::post,
                    mCarrierConfigChangeListener);
        } else {
            Rlog.e(TAG, "CarrierConfigLoader is not available.");
        }

        // Register receiver for ECM exit.
        IntentFilter filter = new IntentFilter();
        filter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
        context.registerReceiver(mEcmExitReceiver, filter, null, mHandler);
        mTelephonyManagerProxy = new TelephonyManagerProxyImpl(context);
    }

    /**
     * Initializes EmergencyStateTracker with injections for testing.
     *
     * @param context                                 The context of the application.
     * @param looper                                  The {@link Looper} of the application.
     * @param isSuplDdsSwitchRequiredForEmergencyCall Whether gnss supl requires default data for
     *                                                emergency call.
     * @param phoneFactoryProxy                       The {@link PhoneFactoryProxy} to be injected.
     * @param phoneSwitcherProxy                      The {@link PhoneSwitcherProxy} to be injected.
     * @param telephonyManagerProxy                   The {@link TelephonyManagerProxy} to be
     *                                                injected.
     * @param radioOnHelper                           The {@link RadioOnHelper} to be injected.
     */
    @VisibleForTesting
    public EmergencyStateTracker(Context context, Looper looper,
            boolean isSuplDdsSwitchRequiredForEmergencyCall, PhoneFactoryProxy phoneFactoryProxy,
            PhoneSwitcherProxy phoneSwitcherProxy, TelephonyManagerProxy telephonyManagerProxy,
            RadioOnHelper radioOnHelper, long ecmExitTimeoutMs) {
        mContext = context;
        mHandler = new MyHandler(looper);
        mIsSuplDdsSwitchRequiredForEmergencyCall = isSuplDdsSwitchRequiredForEmergencyCall;
        mPhoneFactoryProxy = phoneFactoryProxy;
        mPhoneSwitcherProxy = phoneSwitcherProxy;
        mTelephonyManagerProxy = telephonyManagerProxy;
        mRadioOnHelper = radioOnHelper;
        mEcmExitTimeoutMs = ecmExitTimeoutMs;
        mWakeLock = null; // Don't declare a wakelock in tests
        mConfigManager = context.getSystemService(CarrierConfigManager.class);
        mConfigManager.registerCarrierConfigChangeListener(mHandler::post,
                mCarrierConfigChangeListener);
        IntentFilter filter = new IntentFilter();
        filter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
        context.registerReceiver(mEcmExitReceiver, filter, null, mHandler);
    }

    /**
     * Starts the process of an emergency call.
     *
     * <p>
     * Handles turning on radio and switching DDS.
     *
     * @param phone                 the {@code Phone} on which to process the emergency call.
     * @param callId                the call id on which to process the emergency call.
     * @param isTestEmergencyNumber whether this is a test emergency number.
     * @return a {@code CompletableFuture} that results in {@code DisconnectCause.NOT_DISCONNECTED}
     *         if emergency call successfully started.
     */
    public CompletableFuture<Integer> startEmergencyCall(@NonNull Phone phone,
            @NonNull String callId, boolean isTestEmergencyNumber) {
        Rlog.i(TAG, "startEmergencyCall: phoneId=" + phone.getPhoneId() + ", callId=" + callId);

        if (mPhone != null) {
            // Create new future to return as to not interfere with any uncompleted futures.
            // Case1) When 2nd emergency call is initiated during an active call on the same phone.
            // Case2) While the device is in ECBM, an emergency call is initiated on the same phone.
            if (isSamePhone(mPhone, phone) && (!mActiveEmergencyCalls.isEmpty() || isInEcm())) {
                mOngoingCallId = callId;
                mIsTestEmergencyNumber = isTestEmergencyNumber;
                return CompletableFuture.completedFuture(DisconnectCause.NOT_DISCONNECTED);
            }

            Rlog.e(TAG, "startEmergencyCall failed. Existing emergency call in progress.");
            return CompletableFuture.completedFuture(DisconnectCause.ERROR_UNSPECIFIED);
        }

        mOngoingCallProperties = 0;
        mCallEmergencyModeFuture = new CompletableFuture<>();

        if (mSmsPhone != null) {
            mIsEmergencyCallStartedDuringEmergencySms = true;
            // Case1) While exiting the emergency mode on the other phone,
            // the emergency mode for this call will be restarted after the exit complete.
            // Case2) While entering the emergency mode on the other phone,
            // exit the emergency mode when receiving the result of setting the emergency mode and
            // the emergency mode for this call will be restarted after the exit complete.
            if (isInEmergencyMode() && !isEmergencyModeInProgress()) {
                exitEmergencyMode(mSmsPhone, EMERGENCY_TYPE_SMS, false);
            }

            mPhone = phone;
            mOngoingCallId = callId;
            mIsTestEmergencyNumber = isTestEmergencyNumber;
            return mCallEmergencyModeFuture;
        }

        mPhone = phone;
        mOngoingCallId = callId;
        mIsTestEmergencyNumber = isTestEmergencyNumber;
        turnOnRadioAndSwitchDds(mPhone, EMERGENCY_TYPE_CALL, mIsTestEmergencyNumber);
        return mCallEmergencyModeFuture;
    }

    /**
     * Ends emergency call.
     *
     * <p>
     * Enter ECM only once all active emergency calls have ended. If a call never reached
     * {@link Call.State#ACTIVE}, then no need to enter ECM.
     *
     * @param callId the call id on which to end the emergency call.
     */
    public void endCall(@NonNull String callId) {
        boolean wasActive = mActiveEmergencyCalls.remove(callId);

        if (Objects.equals(mOngoingCallId, callId)) {
            mOngoingCallId = null;
            mOngoingCallProperties = 0;
        }

        if (wasActive && mActiveEmergencyCalls.isEmpty()
                && isEmergencyCallbackModeSupported()) {
            enterEmergencyCallbackMode();

            if (mOngoingCallId == null) {
                mIsEmergencyCallStartedDuringEmergencySms = false;
                mCallEmergencyModeFuture = null;
            }
        } else if (mOngoingCallId == null) {
            if (isInEcm()) {
                mIsEmergencyCallStartedDuringEmergencySms = false;
                mCallEmergencyModeFuture = null;
                // If the emergency call was initiated during the emergency callback mode,
                // the emergency callback mode should be restored when the emergency call is ended.
                if (mActiveEmergencyCalls.isEmpty()) {
                    setEmergencyMode(mPhone, EMERGENCY_TYPE_CALL, MODE_EMERGENCY_CALLBACK,
                            MSG_SET_EMERGENCY_CALLBACK_MODE_DONE);
                }
            } else {
                exitEmergencyMode(mPhone, EMERGENCY_TYPE_CALL, false);
                clearEmergencyCallInfo();
            }
        }
    }

    private void clearEmergencyCallInfo() {
        mEmergencyCallDomain = NetworkRegistrationInfo.DOMAIN_UNKNOWN;
        mIsTestEmergencyNumber = false;
        mIsEmergencyCallStartedDuringEmergencySms = false;
        mCallEmergencyModeFuture = null;
        mOngoingCallId = null;
        mOngoingCallProperties = 0;
        mPhone = null;
    }

    private void switchDdsAndSetEmergencyMode(Phone phone, @EmergencyType int emergencyType) {
        switchDdsDelayed(phone, result -> {
            Rlog.i(TAG, "switchDdsDelayed: result = " + result);
            if (!result) {
                // DDS Switch timed out/failed, but continue with call as it may still succeed.
                Rlog.e(TAG, "DDS Switch failed.");
            }
            // Once radio is on and DDS switched, must call setEmergencyMode() before selecting
            // emergency domain. EmergencyRegResult is required to determine domain and this is the
            // only API that can receive it before starting domain selection. Once domain selection
            // is finished, the actual emergency mode will be set when onEmergencyTransportChanged()
            // is called.
            setEmergencyMode(phone, emergencyType, MODE_EMERGENCY_WWAN,
                    MSG_SET_EMERGENCY_MODE_DONE);
        });
    }

    /**
     * Triggers modem to set new emergency mode.
     *
     * @param phone the {@code Phone} to set the emergency mode on modem.
     * @param emergencyType the emergency type to identify an emergency call or SMS.
     * @param mode the new emergency mode.
     * @param msg the message to be sent once mode has been set.
     */
    private void setEmergencyMode(Phone phone, @EmergencyType int emergencyType,
            @EmergencyConstants.EmergencyMode int mode, int msg) {
        Rlog.i(TAG, "setEmergencyMode from " + mEmergencyMode + " to " + mode + " for "
                + emergencyTypeToString(emergencyType));

        if (mEmergencyMode == mode) {
            return;
        }
        mEmergencyMode = mode;
        setEmergencyModeInProgress(true);

        Message m = mHandler.obtainMessage(msg, Integer.valueOf(emergencyType));
        if ((mIsTestEmergencyNumber && emergencyType == EMERGENCY_TYPE_CALL)
                || (mIsTestEmergencyNumberForSms && emergencyType == EMERGENCY_TYPE_SMS)) {
            Rlog.d(TAG, "TestEmergencyNumber for " + emergencyTypeToString(emergencyType)
                    + ": Skipping setting emergency mode on modem.");
            // Send back a response for the command, but with null information
            AsyncResult.forMessage(m, null, null);
            // Ensure that we do not accidentally block indefinitely when trying to validate test
            // emergency numbers
            m.sendToTarget();
            return;
        }

        synchronized (mLock) {
            unregisterForDataConnectionStateChanges();
            if (mPhoneToExit != null) {
                if (emergencyType != EMERGENCY_TYPE_CALL) {
                    setIsInEmergencyCall(false);
                }
                mOnEcmExitCompleteRunnable = null;
                if (mPhoneToExit != phone) {
                    // Exit emergency mode on the other phone first,
                    // then set emergency mode on the given phone.
                    mPhoneToExit.exitEmergencyMode(
                            mHandler.obtainMessage(MSG_SET_EMERGENCY_MODE,
                            Integer.valueOf(emergencyType)));
                    mPhoneToExit = null;
                    return;
                }
                mPhoneToExit = null;
            }
            mWasEmergencyModeSetOnModem = true;
            phone.setEmergencyMode(mode, m);
        }
    }

    private void completeEmergencyMode(@EmergencyType int emergencyType) {
        completeEmergencyMode(emergencyType, DisconnectCause.NOT_DISCONNECTED);
    }

    private void completeEmergencyMode(@EmergencyType int emergencyType,
            @DisconnectCauses int result) {
        if (emergencyType == EMERGENCY_TYPE_CALL) {
            if (mCallEmergencyModeFuture != null && !mCallEmergencyModeFuture.isDone()) {
                mCallEmergencyModeFuture.complete(result);
            }

            if (result != DisconnectCause.NOT_DISCONNECTED) {
                clearEmergencyCallInfo();
            }
        } else if (emergencyType == EMERGENCY_TYPE_SMS) {
            if (mSmsEmergencyModeFuture != null && !mSmsEmergencyModeFuture.isDone()) {
                mSmsEmergencyModeFuture.complete(result);
            }

            if (result != DisconnectCause.NOT_DISCONNECTED) {
                clearEmergencySmsInfo();
            }
        }
    }

    /**
     * Checks if the device is currently in the emergency mode or not.
     */
    @VisibleForTesting
    public boolean isInEmergencyMode() {
        return mEmergencyMode != MODE_EMERGENCY_NONE;
    }

    /**
     * Sets the flag to inidicate whether setting the emergency mode on modem is in progress or not.
     */
    private void setEmergencyModeInProgress(boolean isEmergencyModeInProgress) {
        mIsEmergencyModeInProgress = isEmergencyModeInProgress;
    }

    /**
     * Checks whether setting the emergency mode on modem is in progress or not.
     */
    private boolean isEmergencyModeInProgress() {
        return mIsEmergencyModeInProgress;
    }

    /**
     * Notifies external app listeners of emergency mode changes.
     *
     * @param isInEmergencyCall a flag to indicate whether there is an active emergency call.
     */
    private void setIsInEmergencyCall(boolean isInEmergencyCall) {
        mIsInEmergencyCall = isInEmergencyCall;
    }

    /**
     * Checks if there is an ongoing emergency call.
     *
     * @return true if in emergency call
     */
    public boolean isInEmergencyCall() {
        return mIsInEmergencyCall;
    }

    /**
     * Triggers modem to exit emergency mode.
     *
     * @param phone the {@code Phone} to exit the emergency mode.
     * @param emergencyType the emergency type to identify an emergency call or SMS.
     * @param waitForPdnDisconnect indicates whether it shall wait for the disconnection of ePDN.
     */
    private void exitEmergencyMode(Phone phone, @EmergencyType int emergencyType,
            boolean waitForPdnDisconnect) {
        Rlog.i(TAG, "exitEmergencyMode for " + emergencyTypeToString(emergencyType));

        if (emergencyType == EMERGENCY_TYPE_CALL) {
            if (mSmsPhone != null && isSamePhone(phone, mSmsPhone)) {
                // Waits for exiting the emergency mode until the emergency SMS is ended.
                Rlog.i(TAG, "exitEmergencyMode: waits for emergency SMS end.");
                setIsInEmergencyCall(false);
                return;
            }
        } else if (emergencyType == EMERGENCY_TYPE_SMS) {
            if (mPhone != null && isSamePhone(phone, mPhone)) {
                // Waits for exiting the emergency mode until the emergency call is ended.
                Rlog.i(TAG, "exitEmergencyMode: waits for emergency call end.");
                return;
            }
        }

        if (mEmergencyMode == MODE_EMERGENCY_NONE) {
            return;
        }
        mEmergencyMode = MODE_EMERGENCY_NONE;
        setEmergencyModeInProgress(true);

        Message m = mHandler.obtainMessage(
                MSG_EXIT_EMERGENCY_MODE_DONE, Integer.valueOf(emergencyType));
        if (!mWasEmergencyModeSetOnModem) {
            Rlog.d(TAG, "Emergency mode was not set on modem: Skipping exiting emergency mode.");
            // Send back a response for the command, but with null information
            AsyncResult.forMessage(m, null, null);
            // Ensure that we do not accidentally block indefinitely when trying to validate
            // the exit condition.
            m.sendToTarget();
            return;
        }

        synchronized (mLock) {
            mWasEmergencyModeSetOnModem = false;
            if (waitForPdnDisconnect) {
                registerForDataConnectionStateChanges(phone);
                mPhoneToExit = phone;
                if (mPdnDisconnectionTimeoutMs > 0) {
                    // To avoid waiting for the disconnection indefinitely.
                    mHandler.sendEmptyMessageDelayed(MSG_EXIT_EMERGENCY_MODE,
                            mPdnDisconnectionTimeoutMs);
                }
                return;
            } else {
                unregisterForDataConnectionStateChanges();
                mPhoneToExit = null;
            }
            phone.exitEmergencyMode(m);
        }
    }

    /** Returns last {@link EmergencyRegResult} as set by {@code setEmergencyMode()}. */
    public EmergencyRegResult getEmergencyRegResult() {
        return mLastEmergencyRegResult;
    }

    /**
     * Handles emergency transport change by setting new emergency mode.
     *
     * @param emergencyType the emergency type to identify an emergency call or SMS
     * @param mode the new emergency mode
     */
    public void onEmergencyTransportChanged(@EmergencyType int emergencyType,
            @EmergencyConstants.EmergencyMode int mode) {
        if (mHandler.getLooper().isCurrentThread()) {
            Phone phone = null;
            if (emergencyType == EMERGENCY_TYPE_CALL) {
                phone = mPhone;
            } else if (emergencyType == EMERGENCY_TYPE_SMS) {
                phone = mSmsPhone;
            }

            if (phone != null) {
                setEmergencyMode(phone, emergencyType, mode, MSG_SET_EMERGENCY_MODE_DONE);
            }
        } else {
            mHandler.post(() -> {
                onEmergencyTransportChanged(emergencyType, mode);
            });
        }
    }

    /**
     * Notify the tracker that the emergency call domain has been updated.
     * @param phoneType The new PHONE_TYPE_* of the call.
     * @param callId The ID of the call
     */
    public void onEmergencyCallDomainUpdated(int phoneType, String callId) {
        Rlog.d(TAG, "domain update for callId: " + callId);
        int domain = -1;
        switch(phoneType) {
            case (PhoneConstants.PHONE_TYPE_CDMA_LTE):
                //fallthrough
            case (PhoneConstants.PHONE_TYPE_GSM):
                //fallthrough
            case (PhoneConstants.PHONE_TYPE_CDMA): {
                domain = NetworkRegistrationInfo.DOMAIN_CS;
                break;
            }
            case (PhoneConstants.PHONE_TYPE_IMS): {
                domain = NetworkRegistrationInfo.DOMAIN_PS;
                break;
            }
            default: {
                Rlog.w(TAG, "domain updated: Unexpected phoneType:" + phoneType);
            }
        }
        if (mEmergencyCallDomain == domain) return;
        Rlog.i(TAG, "domain updated: from " + mEmergencyCallDomain + " to " + domain);
        mEmergencyCallDomain = domain;
    }

    /**
     * Handles emergency call state change.
     *
     * @param state the new call state
     * @param callId the callId whose state has changed
     */
    public void onEmergencyCallStateChanged(Call.State state, String callId) {
        if (state == Call.State.ACTIVE) {
            mActiveEmergencyCalls.add(callId);
            if (Objects.equals(mOngoingCallId, callId)) {
                Rlog.i(TAG, "call connected " + callId);
                if (mPhone != null
                        && isVoWiFi(mOngoingCallProperties)
                        && mEmergencyMode == EmergencyConstants.MODE_EMERGENCY_WLAN) {
                    // Recover normal service in cellular when VoWiFi is connected
                    mPhone.cancelEmergencyNetworkScan(true, null);
                }
            }
        }
    }

    /**
     * Handles the change of emergency call properties.
     *
     * @param properties the new call properties.
     * @param callId the callId whose state has changed.
     */
    public void onEmergencyCallPropertiesChanged(int properties, String callId) {
        if (Objects.equals(mOngoingCallId, callId)) {
            mOngoingCallProperties = properties;
        }
    }

    /**
     * Handles the radio power off request.
     */
    public void onCellularRadioPowerOffRequested() {
        synchronized (mLock) {
            if (isInEcm()) {
                exitEmergencyCallbackMode(null);
            }
            exitEmergencyModeIfDelayed();
        }
    }

    private static boolean isVoWiFi(int properties) {
        return (properties & android.telecom.Connection.PROPERTY_WIFI) > 0
                || (properties & android.telecom.Connection.PROPERTY_CROSS_SIM) > 0;
    }

    /**
     * Returns {@code true} if device and carrier support emergency callback mode.
     */
    @VisibleForTesting
    public boolean isEmergencyCallbackModeSupported() {
        int subId = mPhone.getSubId();
        if (!SubscriptionManager.isValidSubscriptionId(subId)) {
            // If there is no SIM, refer to the saved last carrier configuration with valid
            // subscription.
            int phoneId = mPhone.getPhoneId();
            Boolean savedConfig = mNoSimEcbmSupported.get(Integer.valueOf(phoneId));
            if (savedConfig == null) {
                // Exceptional case such as with poor boot performance.
                // Usually, the first carrier config change will update the cache.
                // But with poor boot performance, the carrier config change
                // can be delayed for a long time.
                SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
                savedConfig = Boolean.valueOf(
                        sp.getBoolean(KEY_NO_SIM_ECBM_SUPPORT + phoneId, false));
                Rlog.i(TAG, "ECBM value not cached, load from preference");
                mNoSimEcbmSupported.put(Integer.valueOf(phoneId), savedConfig);
            }
            Rlog.i(TAG, "isEmergencyCallbackModeSupported savedConfig=" + savedConfig);
            return savedConfig;
        } else {
            return getConfig(subId,
                    CarrierConfigManager.ImsEmergency.KEY_EMERGENCY_CALLBACK_MODE_SUPPORTED_BOOL,
                    DEFAULT_EMERGENCY_CALLBACK_MODE_SUPPORTED);
        }
    }

    /**
     * Trigger entry into emergency callback mode.
     */
    private void enterEmergencyCallbackMode() {
        Rlog.d(TAG, "enter ECBM");
        setIsInEmergencyCall(false);
        // Check if not in ECM already.
        if (!isInEcm()) {
            setIsInEcm(true);
            if (!mPhone.getUnitTestMode()) {
                TelephonyProperties.in_ecm_mode(true);
            }

            // Notify listeners of the entrance to ECM.
            sendEmergencyCallbackModeChange();
            if (isInImsEcm()) {
                // emergency call registrants are not notified of new emergency call until entering
                // ECBM (see ImsPhone#handleEnterEmergencyCallbackMode)
                ((GsmCdmaPhone) mPhone).notifyEmergencyCallRegistrants(true);
            }

            // Set emergency mode on modem.
            setEmergencyMode(mPhone, EMERGENCY_TYPE_CALL, MODE_EMERGENCY_CALLBACK,
                    MSG_SET_EMERGENCY_CALLBACK_MODE_DONE);

            // Post this runnable so we will automatically exit if no one invokes
            // exitEmergencyCallbackMode() directly.
            long delayInMillis = TelephonyProperties.ecm_exit_timer()
                    .orElse(mEcmExitTimeoutMs);
            mHandler.postDelayed(mExitEcmRunnable, delayInMillis);

            // We don't want to go to sleep while in ECM.
            if (mWakeLock != null) mWakeLock.acquire(delayInMillis);
        }
    }

    /**
     * Exits emergency callback mode and notifies relevant listeners.
     */
    public void exitEmergencyCallbackMode() {
        Rlog.d(TAG, "exit ECBM");
        // Remove pending exit ECM runnable, if any.
        mHandler.removeCallbacks(mExitEcmRunnable);

        if (isInEcm()) {
            setIsInEcm(false);
            if (!mPhone.getUnitTestMode()) {
                TelephonyProperties.in_ecm_mode(false);
            }

            // Release wakeLock.
            if (mWakeLock != null && mWakeLock.isHeld()) {
                try {
                    mWakeLock.release();
                } catch (Exception e) {
                    // Ignore the exception if the system has already released this WakeLock.
                    Rlog.d(TAG, "WakeLock already released: " + e.toString());
                }
            }

            GsmCdmaPhone gsmCdmaPhone = (GsmCdmaPhone) mPhone;
            // Send intents that ECM has changed.
            sendEmergencyCallbackModeChange();
            gsmCdmaPhone.notifyEmergencyCallRegistrants(false);

            // Exit emergency mode on modem.
            // b/299866883: Wait for the disconnection of ePDN before calling exitEmergencyMode.
            exitEmergencyMode(gsmCdmaPhone, EMERGENCY_TYPE_CALL,
                    mEmergencyCallDomain == NetworkRegistrationInfo.DOMAIN_PS);
        }

        mEmergencyCallDomain = NetworkRegistrationInfo.DOMAIN_UNKNOWN;
        mIsTestEmergencyNumber = false;
        mPhone = null;
    }

    /**
     * Exits emergency callback mode and triggers runnable after exit response is received.
     */
    public void exitEmergencyCallbackMode(Runnable onComplete) {
        mOnEcmExitCompleteRunnable = onComplete;
        exitEmergencyCallbackMode();
    }

    /**
     * Sends intents that emergency callback mode changed.
     */
    private void sendEmergencyCallbackModeChange() {
        Rlog.d(TAG, "sendEmergencyCallbackModeChange: isInEcm=" + isInEcm());

        Intent intent = new Intent(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
        intent.putExtra(TelephonyManager.EXTRA_PHONE_IN_ECM_STATE, isInEcm());
        SubscriptionManager.putPhoneIdAndSubIdExtra(intent, mPhone.getPhoneId());
        mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
    }

    /**
     * Returns {@code true} if currently in emergency callback mode.
     *
     * <p>
     * This is a period where the phone should be using as little power as possible and be ready to
     * receive an incoming call from the emergency operator.
     */
    public boolean isInEcm() {
        return mIsInEcm;
    }

    /**
     * Sets the emergency callback mode state.
     *
     * @param isInEcm {@code true} if currently in emergency callback mode, {@code false} otherwise.
     */
    private void setIsInEcm(boolean isInEcm) {
        mIsInEcm = isInEcm;
    }

    /**
     * Returns {@code true} if currently in emergency callback mode over PS
     */
    public boolean isInImsEcm() {
        return mEmergencyCallDomain == NetworkRegistrationInfo.DOMAIN_PS && isInEcm();
    }

    /**
     * Returns {@code true} if currently in emergency callback mode over CS
     */
    public boolean isInCdmaEcm() {
        // Phone can be null in the case where we are not actively tracking an emergency call.
        if (mPhone == null) return false;
        // Ensure that this method doesn't return true when we are attached to GSM.
        return mPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA
                && mEmergencyCallDomain == NetworkRegistrationInfo.DOMAIN_CS && isInEcm();
    }

    /**
     * Starts the process of an emergency SMS.
     *
     * @param phone the {@code Phone} on which to process the emergency SMS.
     * @param smsId the SMS id on which to process the emergency SMS.
     * @param isTestEmergencyNumber whether this is a test emergency number.
     * @return A {@code CompletableFuture} that results in {@code DisconnectCause.NOT_DISCONNECTED}
     *         if the emergency SMS is successfully started.
     */
    public CompletableFuture<Integer> startEmergencySms(@NonNull Phone phone, @NonNull String smsId,
            boolean isTestEmergencyNumber) {
        Rlog.i(TAG, "startEmergencySms: phoneId=" + phone.getPhoneId() + ", smsId=" + smsId);

        // When an emergency call is in progress, it checks whether an emergency call is already in
        // progress on the different phone.
        if (mPhone != null && !isSamePhone(mPhone, phone)) {
            Rlog.e(TAG, "Emergency call is in progress on the other slot.");
            return CompletableFuture.completedFuture(DisconnectCause.ERROR_UNSPECIFIED);
        }

        // When an emergency SMS is in progress, it checks whether an emergency SMS is already in
        // progress on the different phone.
        if (mSmsPhone != null && !isSamePhone(mSmsPhone, phone)) {
            Rlog.e(TAG, "Emergency SMS is in progress on the other slot.");
            return CompletableFuture.completedFuture(DisconnectCause.ERROR_UNSPECIFIED);
        }

        // When the previous emergency SMS is not completed yet,
        // this new request will not be allowed.
        if (mSmsPhone != null && isInEmergencyMode() && isEmergencyModeInProgress()) {
            Rlog.e(TAG, "Existing emergency SMS is in progress.");
            return CompletableFuture.completedFuture(DisconnectCause.ERROR_UNSPECIFIED);
        }

        mSmsPhone = phone;
        mIsTestEmergencyNumberForSms = isTestEmergencyNumber;
        mOngoingEmergencySmsIds.add(smsId);

        // When the emergency mode is already set by the previous emergency call or SMS,
        // completes the future immediately.
        if (isInEmergencyMode() && !isEmergencyModeInProgress()) {
            return CompletableFuture.completedFuture(DisconnectCause.NOT_DISCONNECTED);
        }

        mSmsEmergencyModeFuture = new CompletableFuture<>();
        if (!isInEmergencyMode()) {
            setEmergencyMode(mSmsPhone, EMERGENCY_TYPE_SMS, MODE_EMERGENCY_WWAN,
                    MSG_SET_EMERGENCY_MODE_DONE);
        }
        return mSmsEmergencyModeFuture;
    }

    /**
     * Ends an emergency SMS.
     * This should be called once an emergency SMS is sent.
     *
     * @param smsId the SMS id on which to end the emergency SMS.
     * @param success the flag specifying whether an emergency SMS is successfully sent or not.
     *                {@code true} if SMS is successfully sent, {@code false} otherwise.
     */
    public void endSms(@NonNull String smsId, boolean success) {
        mOngoingEmergencySmsIds.remove(smsId);

        // If the outgoing emergency SMSs are empty, we can try to exit the emergency mode.
        if (mOngoingEmergencySmsIds.isEmpty()) {
            if (isInEcm()) {
                // When the emergency mode is not in MODE_EMERGENCY_CALLBACK,
                // it needs to notify the emergency callback mode to modem.
                if (mActiveEmergencyCalls.isEmpty() && mOngoingCallId == null) {
                    setEmergencyMode(mPhone, EMERGENCY_TYPE_CALL, MODE_EMERGENCY_CALLBACK,
                            MSG_SET_EMERGENCY_CALLBACK_MODE_DONE);
                }
            } else {
                exitEmergencyMode(mSmsPhone, EMERGENCY_TYPE_SMS, false);
            }

            clearEmergencySmsInfo();
        }
    }

    private void clearEmergencySmsInfo() {
        mOngoingEmergencySmsIds.clear();
        mIsTestEmergencyNumberForSms = false;
        mSmsEmergencyModeFuture = null;
        mSmsPhone = null;
    }

    /**
     * Returns {@code true} if any phones from PhoneFactory have radio on.
     */
    private boolean isRadioOn() {
        boolean result = false;
        for (Phone phone : mPhoneFactoryProxy.getPhones()) {
            result |= phone.isRadioOn();
        }
        return result;
    }

    /**
     * Returns {@code true} if airplane mode is on.
     */
    private boolean isAirplaneModeOn(Context context) {
        return Settings.Global.getInt(context.getContentResolver(),
                Settings.Global.AIRPLANE_MODE_ON, 0) > 0;
    }

    /**
     * Ensures that the radio is switched on and that DDS is switched for emergency call/SMS.
     *
     * <p>
     * Once radio is on and DDS switched, must call setEmergencyMode() before completing the future
     * and selecting emergency domain. EmergencyRegResult is required to determine domain and
     * setEmergencyMode() is the only API that can receive it before starting domain selection.
     * Once domain selection is finished, the actual emergency mode will be set when
     * onEmergencyTransportChanged() is called.
     *
     * @param phone the {@code Phone} for the emergency call/SMS.
     * @param emergencyType the emergency type to identify an emergency call or SMS.
     * @param isTestEmergencyNumber a flag to inidicate whether the emergency call/SMS uses the test
     *                              emergency number.
     */
    private void turnOnRadioAndSwitchDds(Phone phone, @EmergencyType int emergencyType,
            boolean isTestEmergencyNumber) {
        final boolean isAirplaneModeOn = isAirplaneModeOn(mContext);
        boolean needToTurnOnRadio = !isRadioOn() || isAirplaneModeOn;
        final SatelliteController satelliteController = SatelliteController.getInstance();
        boolean needToTurnOffSatellite = satelliteController.isSatelliteEnabled();

        if (needToTurnOnRadio || needToTurnOffSatellite) {
            Rlog.i(TAG, "turnOnRadioAndSwitchDds: phoneId=" + phone.getPhoneId() + " for "
                    + emergencyTypeToString(emergencyType));
            if (mRadioOnHelper == null) {
                mRadioOnHelper = new RadioOnHelper(mContext);
            }

            mRadioOnHelper.triggerRadioOnAndListen(new RadioOnStateListener.Callback() {
                @Override
                public void onComplete(RadioOnStateListener listener, boolean isRadioReady) {
                    if (!isRadioReady) {
                        if (satelliteController.isSatelliteEnabled()) {
                            // Could not turn satellite off
                            Rlog.e(TAG, "Failed to turn off satellite modem.");
                            completeEmergencyMode(emergencyType, DisconnectCause.SATELLITE_ENABLED);
                        } else {
                            // Could not turn radio on
                            Rlog.e(TAG, "Failed to turn on radio.");
                            completeEmergencyMode(emergencyType, DisconnectCause.POWER_OFF);
                        }
                    } else {
                        switchDdsAndSetEmergencyMode(phone, emergencyType);
                    }
                }

                @Override
                public boolean isOkToCall(Phone phone, int serviceState, boolean imsVoiceCapable) {
                    // We currently only look to make sure that the radio is on before dialing. We
                    // should be able to make emergency calls at any time after the radio has been
                    // powered on and isn't in the UNAVAILABLE state, even if it is reporting the
                    // OUT_OF_SERVICE state.
                    return phone.getServiceStateTracker().isRadioOn()
                            && !satelliteController.isSatelliteEnabled();
                }

                @Override
                public boolean onTimeout(Phone phone, int serviceState, boolean imsVoiceCapable) {
                    return true;
                }
            }, !isTestEmergencyNumber, phone, isTestEmergencyNumber, 0);
        } else {
            switchDdsAndSetEmergencyMode(phone, emergencyType);
        }
    }

    /**
     * If needed, block until the default data is switched for outgoing emergency call, or
     * timeout expires.
     *
     * @param phone            The Phone to switch the DDS on.
     * @param completeConsumer The consumer to call once the default data subscription has been
     *                         switched, provides {@code true} result if the switch happened
     *                         successfully or {@code false} if the operation timed out/failed.
     */
    @VisibleForTesting
    public void switchDdsDelayed(Phone phone, Consumer<Boolean> completeConsumer) {
        if (phone == null) {
            // Do not block indefinitely.
            completeConsumer.accept(false);
        }
        try {
            // Waiting for PhoneSwitcher to complete the operation.
            CompletableFuture<Boolean> future = possiblyOverrideDefaultDataForEmergencyCall(phone);
            // In the case that there is an issue or bug in PhoneSwitcher logic, do not wait
            // indefinitely for the future to complete. Instead, set a timeout that will complete
            // the future as to not block the outgoing call indefinitely.
            CompletableFuture<Boolean> timeout = new CompletableFuture<>();
            mHandler.postDelayed(() -> timeout.complete(false), DEFAULT_DATA_SWITCH_TIMEOUT_MS);
            // Also ensure that the Consumer is completed on the main thread.
            CompletableFuture<Void> unused = future.acceptEitherAsync(timeout, completeConsumer,
                    mHandler::post);
        } catch (Exception e) {
            Rlog.w(TAG, "switchDdsDelayed - exception= " + e.getMessage());
        }
    }

    /**
     * If needed, block until Default Data subscription is switched for outgoing emergency call.
     *
     * <p>
     * In some cases, we need to try to switch the Default Data subscription before placing the
     * emergency call on DSDS devices. This includes the following situation: - The modem does not
     * support processing GNSS SUPL requests on the non-default data subscription. For some carriers
     * that do not provide a control plane fallback mechanism, the SUPL request will be dropped and
     * we will not be able to get the user's location for the emergency call. In this case, we need
     * to swap default data temporarily.
     *
     * @param phone Evaluates whether or not the default data should be moved to the phone
     *              specified. Should not be null.
     */
    private CompletableFuture<Boolean> possiblyOverrideDefaultDataForEmergencyCall(
            @NonNull Phone phone) {
        int phoneCount = mTelephonyManagerProxy.getPhoneCount();
        // Do not override DDS if this is a single SIM device.
        if (phoneCount <= PhoneConstants.MAX_PHONE_COUNT_SINGLE_SIM) {
            return CompletableFuture.completedFuture(Boolean.TRUE);
        }

        // Do not switch Default data if this device supports emergency SUPL on non-DDS.
        if (!mIsSuplDdsSwitchRequiredForEmergencyCall) {
            Rlog.d(TAG, "possiblyOverrideDefaultDataForEmergencyCall: not switching DDS, does not "
                    + "require DDS switch.");
            return CompletableFuture.completedFuture(Boolean.TRUE);
        }

        // Only override default data if we are IN_SERVICE already.
        if (!isAvailableForEmergencyCalls(phone)) {
            Rlog.d(TAG, "possiblyOverrideDefaultDataForEmergencyCall: not switching DDS");
            return CompletableFuture.completedFuture(Boolean.TRUE);
        }

        // Only override default data if we are not roaming, we do not want to switch onto a network
        // that only supports data plane only (if we do not know).
        boolean isRoaming = phone.getServiceState().getVoiceRoaming();
        // In some roaming conditions, we know the roaming network doesn't support control plane
        // fallback even though the home operator does. For these operators we will need to do a DDS
        // switch anyway to make sure the SUPL request doesn't fail.
        boolean roamingNetworkSupportsControlPlaneFallback = true;
        String[] dataPlaneRoamPlmns = getConfig(phone.getSubId(),
                CarrierConfigManager.Gps.KEY_ES_SUPL_DATA_PLANE_ONLY_ROAMING_PLMN_STRING_ARRAY);
        if (dataPlaneRoamPlmns != null && Arrays.asList(dataPlaneRoamPlmns)
                .contains(phone.getServiceState().getOperatorNumeric())) {
            roamingNetworkSupportsControlPlaneFallback = false;
        }
        if (isRoaming && roamingNetworkSupportsControlPlaneFallback) {
            Rlog.d(TAG, "possiblyOverrideDefaultDataForEmergencyCall: roaming network is assumed "
                    + "to support CP fallback, not switching DDS.");
            return CompletableFuture.completedFuture(Boolean.TRUE);
        }
        // Do not try to swap default data if we support CS fallback or it is assumed that the
        // roaming network supports control plane fallback, we do not want to introduce a lag in
        // emergency call setup time if possible.
        final boolean supportsCpFallback = getConfig(phone.getSubId(),
                CarrierConfigManager.Gps.KEY_ES_SUPL_CONTROL_PLANE_SUPPORT_INT,
                CarrierConfigManager.Gps.SUPL_EMERGENCY_MODE_TYPE_CP_ONLY)
                != CarrierConfigManager.Gps.SUPL_EMERGENCY_MODE_TYPE_DP_ONLY;
        if (supportsCpFallback && roamingNetworkSupportsControlPlaneFallback) {
            Rlog.d(TAG, "possiblyOverrideDefaultDataForEmergencyCall: not switching DDS, carrier "
                    + "supports CP fallback.");
            return CompletableFuture.completedFuture(Boolean.TRUE);
        }

        // Get extension time, may be 0 for some carriers that support ECBM as well. Use
        // CarrierConfig default if format fails.
        int extensionTime = 0;
        try {
            extensionTime = Integer.parseInt(getConfig(phone.getSubId(),
                    CarrierConfigManager.Gps.KEY_ES_EXTENSION_SEC_STRING, "0"));
        } catch (NumberFormatException e) {
            // Just use default.
        }
        CompletableFuture<Boolean> modemResultFuture = new CompletableFuture<>();
        try {
            Rlog.d(TAG, "possiblyOverrideDefaultDataForEmergencyCall: overriding DDS for "
                    + extensionTime + "seconds");
            mPhoneSwitcherProxy.getPhoneSwitcher().overrideDefaultDataForEmergency(
                    phone.getPhoneId(), extensionTime, modemResultFuture);
            // Catch all exceptions, we want to continue with emergency call if possible.
        } catch (Exception e) {
            Rlog.w(TAG,
                    "possiblyOverrideDefaultDataForEmergencyCall: exception = " + e.getMessage());
            modemResultFuture = CompletableFuture.completedFuture(Boolean.FALSE);
        }
        return modemResultFuture;
    }

    // Helper functions for easy CarrierConfigManager access
    private String getConfig(int subId, String key, String defVal) {
        return getConfigBundle(subId, key).getString(key, defVal);
    }
    private int getConfig(int subId, String key, int defVal) {
        return getConfigBundle(subId, key).getInt(key, defVal);
    }
    private String[] getConfig(int subId, String key) {
        return getConfigBundle(subId, key).getStringArray(key);
    }
    private boolean getConfig(int subId, String key, boolean defVal) {
        return getConfigBundle(subId, key).getBoolean(key, defVal);
    }
    private PersistableBundle getConfigBundle(int subId, String key) {
        if (mConfigManager == null) return new PersistableBundle();
        return mConfigManager.getConfigForSubId(subId, key);
    }

    /**
     * Returns true if the state of the Phone is IN_SERVICE or available for emergency calling only.
     */
    private boolean isAvailableForEmergencyCalls(Phone phone) {
        return ServiceState.STATE_IN_SERVICE == phone.getServiceState().getState()
                || phone.getServiceState().isEmergencyOnly();
    }

    /**
     * Checks whether both {@code Phone}s are same or not.
     */
    private static boolean isSamePhone(Phone p1, Phone p2) {
        return p1 != null && p2 != null && (p1.getPhoneId() == p2.getPhoneId());
    }

    private static String emergencyTypeToString(@EmergencyType int emergencyType) {
        switch (emergencyType) {
            case EMERGENCY_TYPE_CALL: return "CALL";
            case EMERGENCY_TYPE_SMS: return "SMS";
            default: return "UNKNOWN";
        }
    }

    private void onCarrierConfigurationChanged(int slotIndex, int subId) {
        Rlog.i(TAG, "onCarrierConfigChanged slotIndex=" + slotIndex + ", subId=" + subId);

        if (slotIndex < 0) {
            return;
        }

        updateNoSimEcbmSupported(slotIndex, subId);
    }

    private void updateNoSimEcbmSupported(int slotIndex, int subId) {
        SharedPreferences sp = null;
        Boolean savedConfig = mNoSimEcbmSupported.get(Integer.valueOf(slotIndex));
        if (savedConfig == null) {
            sp = PreferenceManager.getDefaultSharedPreferences(mContext);
            savedConfig = Boolean.valueOf(
                    sp.getBoolean(KEY_NO_SIM_ECBM_SUPPORT + slotIndex, false));
            mNoSimEcbmSupported.put(Integer.valueOf(slotIndex), savedConfig);
            Rlog.i(TAG, "updateNoSimEcbmSupported load from preference slotIndex=" + slotIndex
                    + ", supported=" + savedConfig);
        }

        if (!SubscriptionManager.isValidSubscriptionId(subId)) {
            // invalid subId
            return;
        }

        PersistableBundle b = getConfigBundle(subId, KEY_EMERGENCY_CALLBACK_MODE_SUPPORTED_BOOL);
        if (b.isEmpty()) {
            Rlog.e(TAG, "updateNoSimEcbmSupported empty result");
            return;
        }

        if (!CarrierConfigManager.isConfigForIdentifiedCarrier(b)) {
            Rlog.i(TAG, "updateNoSimEcbmSupported not carrier specific configuration");
            return;
        }

        boolean carrierConfig = b.getBoolean(KEY_EMERGENCY_CALLBACK_MODE_SUPPORTED_BOOL);
        if (carrierConfig == savedConfig) {
            return;
        }

        mNoSimEcbmSupported.put(Integer.valueOf(slotIndex), Boolean.valueOf(carrierConfig));

        if (sp == null) {
            sp = PreferenceManager.getDefaultSharedPreferences(mContext);
        }
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(KEY_NO_SIM_ECBM_SUPPORT + slotIndex, carrierConfig);
        editor.apply();

        Rlog.i(TAG, "updateNoSimEcbmSupported preference updated slotIndex=" + slotIndex
                + ", supported=" + carrierConfig);
    }

    /** For test purpose only */
    @VisibleForTesting
    public void setPdnDisconnectionTimeoutMs(int timeout) {
        mPdnDisconnectionTimeoutMs = timeout;
    }

    private void exitEmergencyModeIfDelayed() {
        synchronized (mLock) {
            if (mPhoneToExit != null) {
                unregisterForDataConnectionStateChanges();
                mPhoneToExit.exitEmergencyMode(
                        mHandler.obtainMessage(MSG_EXIT_EMERGENCY_MODE_DONE,
                                Integer.valueOf(EMERGENCY_TYPE_CALL)));
                mPhoneToExit = null;
            }
        }
    }

    /**
     * Registers for changes to data connection state.
     */
    private void registerForDataConnectionStateChanges(Phone phone) {
        if ((mDataConnectionStateListener != null) || (phone == null)) {
            return;
        }
        Rlog.i(TAG, "registerForDataConnectionStateChanges");

        mDataConnectionStateListener = new PreciseDataConnectionStateListener();
        mTelephonyManagerProxy.registerTelephonyCallback(phone.getSubId(),
                mHandler::post, mDataConnectionStateListener);
    }

    /**
     * Unregisters for changes to data connection state.
     */
    private void unregisterForDataConnectionStateChanges() {
        if (mDataConnectionStateListener == null) {
            return;
        }
        Rlog.i(TAG, "unregisterForDataConnectionStateChanges");

        mTelephonyManagerProxy.unregisterTelephonyCallback(mDataConnectionStateListener);
        mDataConnectionStateListener = null;
    }
}