aboutsummaryrefslogtreecommitdiff
path: root/Common/src/com/googlecode/android_scripting/facade/telephony/TelephonyManagerFacade.java
blob: e60e5f15f30451975b51bd663f356086687d97bb (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
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
/*
 * Copyright (C) 2017 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.googlecode.android_scripting.facade.telephony;

import android.annotation.Nullable;
import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.TrafficStats;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.Telephony;
import android.sysprop.TelephonyProperties;
import android.telephony.AvailableNetworkInfo;
import android.telephony.CellInfo;
import android.telephony.CellLocation;
import android.telephony.NeighboringCellInfo;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;

import com.android.internal.telephony.RILConstants;

import com.google.common.io.BaseEncoding;
import com.googlecode.android_scripting.Log;
import com.googlecode.android_scripting.facade.AndroidFacade;
import com.googlecode.android_scripting.facade.EventFacade;
import com.googlecode.android_scripting.facade.FacadeManager;
import com.googlecode.android_scripting.facade.telephony.TelephonyStateListeners
                                                   .ActiveDataSubIdChangeListener;
import com.googlecode.android_scripting.facade.telephony.TelephonyStateListeners
                                                   .CallStateChangeListener;
import com.googlecode.android_scripting.facade.telephony.TelephonyStateListeners
                                                   .CellInfoChangeListener;
import com.googlecode.android_scripting.facade.telephony.TelephonyStateListeners
                                                   .DataConnectionRealTimeInfoChangeListener;
import com.googlecode.android_scripting.facade.telephony.TelephonyStateListeners
                                                   .DataConnectionStateChangeListener;
import com.googlecode.android_scripting.facade.telephony.TelephonyStateListeners
                                                   .DisplayInfoStateChangeListener;
import com.googlecode.android_scripting.facade.telephony.TelephonyStateListeners
                                                   .ServiceStateChangeListener;
import com.googlecode.android_scripting.facade.telephony.TelephonyStateListeners
                                                   .SignalStrengthChangeListener;
import com.googlecode.android_scripting.facade.telephony.TelephonyStateListeners
                                                   .VoiceMailStateChangeListener;
import com.googlecode.android_scripting.jsonrpc.RpcReceiver;
import com.googlecode.android_scripting.rpc.Rpc;
import com.googlecode.android_scripting.rpc.RpcDefault;
import com.googlecode.android_scripting.rpc.RpcOptional;
import com.googlecode.android_scripting.rpc.RpcParameter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * Exposes TelephonyManager functionality.
 *
 */
public class TelephonyManagerFacade extends RpcReceiver {

    private final Service mService;
    private final AndroidFacade mAndroidFacade;
    private final EventFacade mEventFacade;
    private final TelephonyManager mTelephonyManager;
    private final SubscriptionManager mSubscriptionManager;
    private List<AvailableNetworkInfo> availableNetworkList;
    private HashMap<Integer, StateChangeListener> mStateChangeListeners =
                             new HashMap<Integer, StateChangeListener>();

    private static final String[] sProjection = new String[] {
            Telephony.Carriers._ID, // 0
            Telephony.Carriers.NAME, // 1
            Telephony.Carriers.APN, // 2
            Telephony.Carriers.PROXY, // 3
            Telephony.Carriers.PORT, // 4
            Telephony.Carriers.USER, // 5
            Telephony.Carriers.SERVER, // 6
            Telephony.Carriers.PASSWORD, // 7
            Telephony.Carriers.MMSC, // 8
            Telephony.Carriers.MCC, // 9
            Telephony.Carriers.MNC, // 10
            Telephony.Carriers.NUMERIC, // 11
            Telephony.Carriers.MMSPROXY,// 12
            Telephony.Carriers.MMSPORT, // 13
            Telephony.Carriers.AUTH_TYPE, // 14
            Telephony.Carriers.TYPE, // 15
            Telephony.Carriers.PROTOCOL, // 16
            Telephony.Carriers.CARRIER_ENABLED, // 17
            Telephony.Carriers.BEARER_BITMASK, // 18
            Telephony.Carriers.ROAMING_PROTOCOL, // 19
            Telephony.Carriers.MVNO_TYPE, // 20
            Telephony.Carriers.MVNO_MATCH_DATA // 21
    };

    public TelephonyManagerFacade(FacadeManager manager) {
        super(manager);
        mService = manager.getService();
        mTelephonyManager =
                (TelephonyManager) mService.getSystemService(Context.TELEPHONY_SERVICE);
        mAndroidFacade = manager.getReceiver(AndroidFacade.class);
        mEventFacade = manager.getReceiver(EventFacade.class);
        mSubscriptionManager = SubscriptionManager.from(mService);
    }

    /**
    * Reset TelephonyManager settings to factory default.
    * @param subId the subriber id to be reset, use default id if not provided.
    */
    @Rpc(description = "Resets TelephonyManager settings to factory default.")
    public void telephonyFactoryReset(
            @RpcOptional @RpcParameter(name = "subId") Integer subId) {
        if (subId == null) {
            subId = SubscriptionManager.getDefaultVoiceSubscriptionId();
        }
        mTelephonyManager.factoryReset(subId);
    }

    /**
    * Reset TelephonyManager settings to factory default.
    * @param subId the subriber id to be reset, use default id if not provided.
    */
    @Rpc(description = "Resets Telephony and IMS settings to factory default.")
    public void telephonyResetSettings(
            @RpcOptional @RpcParameter(name = "subId") Integer subId) {
        if (subId == null) {
            subId = SubscriptionManager.getDefaultVoiceSubscriptionId();
        }
        mTelephonyManager.createForSubscriptionId(subId).resetSettings();
    }

    @Rpc(description = "Set network preference.")
    public boolean telephonySetPreferredNetworkTypes(
        @RpcParameter(name = "nwPreference") String nwPreference) {
        return telephonySetPreferredNetworkTypesForSubscription(nwPreference,
                SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Set network preference for subscription.")
    public boolean telephonySetPreferredNetworkTypesForSubscription(
            @RpcParameter(name = "nwPreference") String nwPreference,
            @RpcParameter(name = "subId") Integer subId) {
        int networkPreferenceInt = TelephonyUtils.getNetworkModeIntfromString(
            nwPreference);
        if (RILConstants.RIL_ERRNO_INVALID_RESPONSE != networkPreferenceInt) {
            return mTelephonyManager.setPreferredNetworkType(
                subId, networkPreferenceInt);
        } else {
            return false;
        }
    }

    /**
    * Set network selection mode to automatic for subscriber.
    * @param subId the subriber id to be set.
    */
    @Rpc(description = "Set network selection mode to automatic for subscriber.")
    public void telephonySetNetworkSelectionModeAutomaticForSubscription(
            @RpcParameter(name = "subId") Integer subId) {
        mTelephonyManager.setNetworkSelectionModeAutomatic();
    }

    @Rpc(description = "Get network preference.")
    public String telephonyGetPreferredNetworkTypes() {
        return telephonyGetPreferredNetworkTypesForSubscription(
                SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Get network preference for subscription.")
    public String telephonyGetPreferredNetworkTypesForSubscription(
            @RpcParameter(name = "subId") Integer subId) {
        int networkPreferenceInt = mTelephonyManager.getPreferredNetworkType(subId);
        return TelephonyUtils.getNetworkModeStringfromInt(networkPreferenceInt);
    }

    @Rpc(description = "Get current voice network type")
    public String telephonyGetCurrentVoiceNetworkType() {
        return telephonyGetCurrentVoiceNetworkTypeForSubscription(
                SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Get current voice network type for subscription")
    public String telephonyGetCurrentVoiceNetworkTypeForSubscription(
            @RpcParameter(name = "subId") Integer subId) {
        return TelephonyUtils.getNetworkTypeString(
            mTelephonyManager.getVoiceNetworkType(subId));
    }

    @Rpc(description = "Get current data network type")
    public String telephonyGetCurrentDataNetworkType() {
        return telephonyGetCurrentDataNetworkTypeForSubscription(
                SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Get current data network type for subscription")
    public String telephonyGetCurrentDataNetworkTypeForSubscription(
            @RpcParameter(name = "subId") Integer subId) {
        return TelephonyUtils.getNetworkTypeString(
            mTelephonyManager.getDataNetworkType(subId));
    }

    @Rpc(description = "Get if phone have voice capability")
    public Boolean telephonyIsVoiceCapable() {
        return mTelephonyManager.isVoiceCapable();
    }

    @Rpc(description = "Get preferred network setting for " +
                       "default subscription ID .Return value is integer.")
    public int telephonyGetPreferredNetworkTypeInteger() {
        return telephonyGetPreferredNetworkTypeIntegerForSubscription(
                                         SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Get preferred network setting for " +
                       "specified subscription ID .Return value is integer.")
    public int telephonyGetPreferredNetworkTypeIntegerForSubscription(
               @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getPreferredNetworkType(subId);
    }

    @Rpc(description = "Starts tracking call state change" +
                       "for default subscription ID.")
    public Boolean telephonyStartTrackingCallState() {
        return telephonyStartTrackingCallStateForSubscription(
                              SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Starts tracking call state change" +
                       "for specified subscription ID.")
    public Boolean telephonyStartTrackingCallStateForSubscription(
                @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, true);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mCallStateChangeListener,
            CallStateChangeListener.sListeningStates);
        return true;
    }

    @Rpc(description = "Starts tracking cell info change" +
                       "for default subscription ID.")
    public Boolean telephonyStartTrackingCellInfoChange() {
        return telephonyStartTrackingCellInfoChangeForSubscription(
                              SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Starts tracking cell info change" +
                       "for specified subscription ID.")
    public Boolean telephonyStartTrackingCellInfoChangeForSubscription(
                @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, true);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mCellInfoChangeListener,
            PhoneStateListener.LISTEN_CELL_INFO);
        return true;
    }

    @Rpc(description = "Starts tracking active opportunistic data change" +
                       "for default subscription ID.")
    public Boolean telephonyStartTrackingActiveDataChange() {
        return telephonyStartTrackingActiveDataChangeForSubscription(
                              SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Starts tracking active opportunistic data change" +
                       "for specified subscription ID.")
    public Boolean telephonyStartTrackingActiveDataChangeForSubscription(
                @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, true);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mActiveDataSubIdChangeListener,
            PhoneStateListener.LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE);
        return true;
    }

    @Rpc(description = "Starts tracking display info change" +
                       "for default subscription ID.")
    public Boolean telephonyStartTrackingDisplayInfoChange() {
        return telephonyStartTrackingDisplayInfoChangeForSubscription(
                              SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Starts tracking display info change" +
                       "for specified subscription ID.")
    public Boolean telephonyStartTrackingDisplayInfoChangeForSubscription(
                @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, true);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mDisplayInfoStateChangeListener,
            PhoneStateListener.LISTEN_DISPLAY_INFO_CHANGED);
        return true;
    }

    @Rpc(description = "Turn on/off precise listening on fore/background or" +
                       " ringing calls for default voice subscription ID.")
    public Boolean telephonyAdjustPreciseCallStateListenLevel(
            @RpcParameter(name = "type") String type,
            @RpcParameter(name = "listen") Boolean listen) {
        return telephonyAdjustPreciseCallStateListenLevelForSubscription(type, listen,
                                 SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Turn on/off precise listening on fore/background or" +
                       " ringing calls for specified subscription ID.")
    public Boolean telephonyAdjustPreciseCallStateListenLevelForSubscription(
            @RpcParameter(name = "type") String type,
            @RpcParameter(name = "listen") Boolean listen,
            @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, true);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }

        if (type.equals(TelephonyConstants.PRECISE_CALL_STATE_LISTEN_LEVEL_FOREGROUND)) {
            listener.mCallStateChangeListener.listenForeground = listen;
        } else if (type.equals(TelephonyConstants.PRECISE_CALL_STATE_LISTEN_LEVEL_RINGING)) {
            listener.mCallStateChangeListener.listenRinging = listen;
        } else if (type.equals(TelephonyConstants.PRECISE_CALL_STATE_LISTEN_LEVEL_BACKGROUND)) {
            listener.mCallStateChangeListener.listenBackground = listen;
        } else {
            throw new IllegalArgumentException("Invalid listen level type " + type);
        }

        return true;
    }

    @Rpc(description = "Stops tracking cell info change " +
            "for default voice subscription ID.")
    public Boolean telephonyStopTrackingCellInfoChange() {
        return telephonyStopTrackingCellInfoChangeForSubscription(
                SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Stops tracking cell info change " +
                       "for specified subscription ID.")
    public Boolean telephonyStopTrackingCellInfoChangeForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, false);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mCellInfoChangeListener,
            PhoneStateListener.LISTEN_NONE);
        return true;
    }

    @Rpc(description = "Stops tracking active opportunistic data " +
            "for default subscription ID.")
    public Boolean telephonyStopTrackingActiveDataChange() {
        return telephonyStopTrackingActiveDataChangeForSubscription(
                SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Stops tracking active opportunistic data " +
                       "for specified subscription ID.")
    public Boolean telephonyStopTrackingActiveDataChangeForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, false);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mActiveDataSubIdChangeListener,
            PhoneStateListener.LISTEN_NONE);
        return true;
    }

    @Rpc(description = "Stops tracking display info change " +
                       "for default subscription ID.")
    public Boolean telephonyStopTrackingDisplayInfoChange() {
        return telephonyStopTrackingDisplayInfoChangeForSubscription(
                SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Stops tracking display info change " +
                       "for specified subscription ID.")
    public Boolean telephonyStopTrackingDisplayInfoChangeForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, false);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mDisplayInfoStateChangeListener,
            PhoneStateListener.LISTEN_NONE);
        return true;
    }

    @Rpc(description = "Stops tracking call state change " +
            "for default voice subscription ID.")
    public Boolean telephonyStopTrackingCallStateChange() {
        return telephonyStopTrackingCallStateChangeForSubscription(
                SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Stops tracking call state change " +
                       "for specified subscription ID.")
    public Boolean telephonyStopTrackingCallStateChangeForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, false);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mCallStateChangeListener,
            PhoneStateListener.LISTEN_NONE);
        return true;
    }

    @Rpc(description = "Starts tracking data connection real time info change" +
                       "for default subscription ID.")
    public Boolean telephonyStartTrackingDataConnectionRTInfoChange() {
        return telephonyStartTrackingDataConnectionRTInfoChangeForSubscription(
                                 SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Starts tracking data connection real time info change" +
                       "for specified subscription ID.")
    public Boolean telephonyStartTrackingDataConnectionRTInfoChangeForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, true);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mDataConnectionRTInfoChangeListener,
            DataConnectionRealTimeInfoChangeListener.sListeningStates);
        return true;
    }

    @Rpc(description = "Stops tracking data connection real time info change" +
                       "for default subscription ID.")
    public Boolean telephonyStopTrackingDataConnectionRTInfoChange() {
        return telephonyStopTrackingDataConnectionRTInfoChangeForSubscription(
                                 SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Stops tracking data connection real time info change" +
                       "for specified subscription ID.")
    public Boolean telephonyStopTrackingDataConnectionRTInfoChangeForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, false);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mDataConnectionRTInfoChangeListener,
            PhoneStateListener.LISTEN_NONE);
        return true;
    }

    @Rpc(description = "Starts tracking data connection state change" +
                       "for default subscription ID..")
    public Boolean telephonyStartTrackingDataConnectionStateChange() {
        return telephonyStartTrackingDataConnectionStateChangeForSubscription(
                                 SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Starts tracking data connection state change" +
                       "for specified subscription ID.")
    public Boolean telephonyStartTrackingDataConnectionStateChangeForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, true);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mDataConnectionStateChangeListener,
            DataConnectionStateChangeListener.sListeningStates);
        return true;
    }

    @Rpc(description = "Stops tracking data connection state change " +
                       "for default subscription ID..")
    public Boolean telephonyStopTrackingDataConnectionStateChange() {
        return telephonyStopTrackingDataConnectionStateChangeForSubscription(
                                 SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Stops tracking data connection state change " +
                       "for specified subscription ID..")
    public Boolean telephonyStopTrackingDataConnectionStateChangeForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, false);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mDataConnectionStateChangeListener,
            PhoneStateListener.LISTEN_NONE);
        return true;
    }

    @Rpc(description = "Starts tracking service state change " +
                       "for default subscription ID.")
    public Boolean telephonyStartTrackingServiceStateChange() {
        return telephonyStartTrackingServiceStateChangeForSubscription(
                                 SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Starts tracking service state change " +
                       "for specified subscription ID.")
    public Boolean telephonyStartTrackingServiceStateChangeForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, true);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mServiceStateChangeListener,
            ServiceStateChangeListener.sListeningStates);
        return true;
    }

    @Rpc(description = "Stops tracking service state change " +
                       "for default subscription ID.")
    public Boolean telephonyStopTrackingServiceStateChange() {
        return telephonyStopTrackingServiceStateChangeForSubscription(
                                 SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Stops tracking service state change " +
                       "for specified subscription ID.")
    public Boolean telephonyStopTrackingServiceStateChangeForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, false);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mServiceStateChangeListener,
            PhoneStateListener.LISTEN_NONE);
            return true;
    }

    @Rpc(description = "Starts tracking signal strength change " +
                       "for default subscription ID.")
    public Boolean telephonyStartTrackingSignalStrengthChange() {
        return telephonyStartTrackingSignalStrengthChangeForSubscription(
                                 SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Starts tracking signal strength change " +
                       "for specified subscription ID.")
    public Boolean telephonyStartTrackingSignalStrengthChangeForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, true);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mSignalStrengthChangeListener,
            SignalStrengthChangeListener.sListeningStates);
        return true;
    }

    @Rpc(description = "Stops tracking signal strength change " +
                       "for default subscription ID.")
    public Boolean telephonyStopTrackingSignalStrengthChange() {
        return telephonyStopTrackingSignalStrengthChangeForSubscription(
                                 SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Stops tracking signal strength change " +
                       "for specified subscription ID.")
    public Boolean telephonyStopTrackingSignalStrengthChangeForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, false);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mSignalStrengthChangeListener,
            PhoneStateListener.LISTEN_NONE);
        return true;
    }

    @Rpc(description = "Starts tracking voice mail state change " +
                       "for default subscription ID.")
    public Boolean telephonyStartTrackingVoiceMailStateChange() {
        return telephonyStartTrackingVoiceMailStateChangeForSubscription(
                                 SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Starts tracking voice mail state change " +
                       "for specified subscription ID.")
    public Boolean telephonyStartTrackingVoiceMailStateChangeForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, true);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mVoiceMailStateChangeListener,
            VoiceMailStateChangeListener.sListeningStates);
        return true;
    }

    @Rpc(description = "Stops tracking voice mail state change " +
                       "for default subscription ID.")
    public Boolean telephonyStopTrackingVoiceMailStateChange() {
        return telephonyStopTrackingVoiceMailStateChangeForSubscription(
                                 SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
    }

    @Rpc(description = "Stops tracking voice mail state change " +
                       "for specified subscription ID.")
    public Boolean telephonyStopTrackingVoiceMailStateChangeForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, false);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return false;
        }
        mTelephonyManager.createForSubscriptionId(subId).listen(
            listener.mVoiceMailStateChangeListener,
            PhoneStateListener.LISTEN_NONE);
        return true;
    }

    @Rpc(description = "Answers an incoming ringing call.")
    public void telephonyAnswerCall() throws RemoteException {
        mTelephonyManager.silenceRinger();
        mTelephonyManager.answerRingingCall();
    }

    @Rpc(description = "Returns the radio on/off state.")
    public Boolean telephonyIsRadioOn() {
        return mTelephonyManager.isRadioOn();
    }

    @Rpc(description = "Sets the radio to an on/off state.")
    public Boolean telephonySetRadioPower(
        @RpcParameter(name = "turnOn") boolean turnOn) {
        return mTelephonyManager.setRadioPower(turnOn);
    }

    @Rpc(description = "Returns the current cell location.")
    public CellLocation telephonyGetCellLocation() {
        return mTelephonyManager.getCellLocation();
    }

    /**
     *  Returns carrier id of the current subscription.
     * @return Carrier id of the current subscription.
     */
    @Rpc(description = "Returns the numeric CarrierId for current subscription")
    public int telephonyGetSimCarrierId() {
        return mTelephonyManager.getSimCarrierId();
    }

    /**
     *  Returns carrier id name of the current subscription.
     * @return Carrier id name of the current subscription
     */
    @Rpc(description = "Returns Carrier Name for current subscription")
    public CharSequence telephonyGetSimCarrierIdName() {
        return mTelephonyManager.getSimCarrierIdName();
    }

    @Rpc(description = "Returns the numeric name (MCC+MNC) of registered operator." +
                       "for default subscription ID")
    public String telephonyGetNetworkOperator() {
        return telephonyGetNetworkOperatorForSubscription(
                        SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Returns the numeric name (MCC+MNC) of registered operator" +
                       "for specified subscription ID.")
    public String telephonyGetNetworkOperatorForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getNetworkOperator(subId);
    }

    @Rpc(description = "Returns the alphabetic name of current registered operator" +
                       "for specified subscription ID.")
    public String telephonyGetNetworkOperatorName() {
        return telephonyGetNetworkOperatorNameForSubscription(
                        SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Returns the alphabetic name of registered operator " +
                       "for specified subscription ID.")
    public String telephonyGetNetworkOperatorNameForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getNetworkOperatorName(subId);
    }

    @Rpc(description = "Returns the current RAT in use on the device.+" +
                       "for default subscription ID")
    public String telephonyGetNetworkType() {

        Log.d("sl4a:getNetworkType() is deprecated!" +
                "Please use getVoiceNetworkType()" +
                " or getDataNetworkTpe()");

        return telephonyGetNetworkTypeForSubscription(
                       SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Returns the current RAT in use on the device" +
            " for a given Subscription.")
    public String telephonyGetNetworkTypeForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {

        Log.d("sl4a:getNetworkTypeForSubscriber() is deprecated!" +
                "Please use getVoiceNetworkType()" +
                " or getDataNetworkTpe()");

        return TelephonyUtils.getNetworkTypeString(
            mTelephonyManager.getNetworkType(subId));
    }

    @Rpc(description = "Returns the current voice RAT for" +
            " the default voice subscription.")
    public String telephonyGetVoiceNetworkType() {
        return telephonyGetVoiceNetworkTypeForSubscription(
                         SubscriptionManager.getDefaultVoiceSubscriptionId());
    }

    @Rpc(description = "Returns the current voice RAT for" +
            " the specified voice subscription.")
    public String telephonyGetVoiceNetworkTypeForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return TelephonyUtils.getNetworkTypeString(
            mTelephonyManager.getVoiceNetworkType(subId));
    }

    @Rpc(description = "Returns the current data RAT for" +
            " the defaut data subscription")
    public String telephonyGetDataNetworkType() {
        return telephonyGetDataNetworkTypeForSubscription(
                         SubscriptionManager.getDefaultDataSubscriptionId());
    }

    @Rpc(description = "Returns the current data RAT for" +
            " the specified data subscription")
    public String telephonyGetDataNetworkTypeForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return TelephonyUtils.getNetworkTypeString(
            mTelephonyManager.getDataNetworkType(subId));
    }

    @Rpc(description = "Returns the device phone type.")
    public String telephonyGetPhoneType() {
        return TelephonyUtils.getPhoneTypeString(
            mTelephonyManager.getPhoneType());
    }

    @Rpc(description = "Return if setAlwaysAllowMMSData is set correctly")
    public boolean telephonySetAlwaysAllowMmsData(
            @RpcParameter(name = "subId") Integer subId,
            @RpcParameter(name = "alwaysAllow") Boolean alwaysAllow) {
        boolean wasAlwaysAllow = mTelephonyManager.isMobileDataPolicyEnabled(
                TelephonyManager.MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED);
        mTelephonyManager.createForSubscriptionId(subId)
                .setMobileDataPolicyEnabled(
                        TelephonyManager.MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED, alwaysAllow);
        return wasAlwaysAllow == alwaysAllow;
    }

    /**
    * Sets Data Roaming flag for a particular sub Id
    * @param subId the subscriber id
    * @param isEnabled can you set to true or false
    */
    @Rpc(description = "Sets data roaming for a sub Id")
    public void telephonySetDataRoamingEnabled(
            @RpcParameter(name = "subId") Integer subId,
            @RpcParameter(name = "isEnabled") Boolean isEnabled) {
        mTelephonyManager.createForSubscriptionId(subId).setDataRoamingEnabled(isEnabled);
    }

    @Rpc(description = "Returns preferred opportunistic data subscription Id")
    public Integer telephonyGetPreferredOpportunisticDataSubscription() {
        return mTelephonyManager.getPreferredOpportunisticDataSubscription();
    }

    @Rpc(description = "Sets preferred opportunistic data subscription Id")
    public void telephonySetPreferredOpportunisticDataSubscription(
            @RpcParameter(name = "subId") Integer subId,
            @RpcParameter(name = "needValidation") Boolean needValidation) {
        mTelephonyManager.setPreferredOpportunisticDataSubscription(
                   subId, needValidation, null, null);
    }

    @Rpc(description = "Updates Available Networks")
    public void telephonyUpdateAvailableNetworks(
            @RpcParameter(name = "subId") Integer subId) {

        availableNetworkList = new ArrayList<>();
        List<String> mccmmc = new ArrayList<String>();
        List<Integer> bands = new ArrayList<Integer>();

        availableNetworkList.add(
            new AvailableNetworkInfo(
                subId,
                AvailableNetworkInfo.PRIORITY_HIGH,
                mccmmc,
                bands));

        mTelephonyManager.updateAvailableNetworks(availableNetworkList, null, null);
    }

    /**
    * Get device phone type for a subscription.
    * @param subId the subscriber id
    * @return the phone type string for the subscriber.
    */
    @Rpc(description = "Returns the device phone type for a subscription.")
    public String telephonyGetPhoneTypeForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return TelephonyUtils.getPhoneTypeString(
            mTelephonyManager.getCurrentPhoneType(subId));
    }

    @Rpc(description = "Returns the MCC for default subscription ID")
    public String telephonyGetSimCountryIso() {
         return telephonyGetSimCountryIsoForSubscription(
                      SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Returns the MCC for specified subscription ID")
    public String telephonyGetSimCountryIsoForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getSimCountryIso(subId);
    }

    @Rpc(description = "Returns the MCC+MNC for default subscription ID")
    public String telephonyGetSimOperator() {
        return telephonyGetSimOperatorForSubscription(
                  SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Returns the MCC+MNC for specified subscription ID")
    public String telephonyGetSimOperatorForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getSimOperator(subId);
    }

    @Rpc(description = "Returns the Service Provider Name (SPN)" +
                       "for default subscription ID")
    public String telephonyGetSimOperatorName() {
        return telephonyGetSimOperatorNameForSubscription(
                  SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Returns the Service Provider Name (SPN)" +
                       " for specified subscription ID.")
    public String telephonyGetSimOperatorNameForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getSimOperatorName(subId);
    }

    @Rpc(description = "Returns the serial number of the SIM for " +
                       "default subscription ID, or Null if unavailable")
    public String telephonyGetSimSerialNumber() {
        return telephonyGetSimSerialNumberForSubscription(
                  SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Returns the serial number of the SIM for " +
                       "specified subscription ID, or Null if unavailable")
    public String telephonyGetSimSerialNumberForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getSimSerialNumber(subId);
    }

    /**
     * Set SIM card power state.
     *
     * @param state  State of SIM (0: power down, 1: power up, 2: pass through)
     **/
    @Rpc(description = "Set the SIM power state of the SIM card for default slot ID.")
    public void telephonySetSimPowerState(
                  @RpcParameter(name = "state") Integer state) {
        mTelephonyManager.setSimPowerState(state);
    }

    /**
     * Set SIM card power state.
     *
     * @param slotId SIM slot id
     * @param state  State of SIM (0: power down, 1: power up, 2: pass through)
     **/
    @Rpc(description = "Set the SIM power state for SIM slot slotId.")
    public void telephonySetSimStateForSlotId(
                  @RpcParameter(name = "slotId") Integer slotId,
                  @RpcParameter(name = "state") Integer state) {
        mTelephonyManager.setSimPowerStateForSlot(slotId, state);
    }

    @Rpc(description = "Returns the state of the SIM card for default slot ID.")
    public String telephonyGetSimState() {
        return telephonyGetSimStateForSlotId(
                  mTelephonyManager.getSlotIndex());
    }

    @Rpc(description = "Returns the state of the SIM card for specified slot ID.")
    public String telephonyGetSimStateForSlotId(
                  @RpcParameter(name = "slotId") Integer slotId) {
        return TelephonyUtils.getSimStateString(
            mTelephonyManager.getSimState(slotId));
    }

    /**
     * Switch device mode multisim
     *
     * @param numOfSims (1: single sim, 2: multi sim)
     **/
    @Rpc(description = "Switch configs to enable multi-sim or switch back to single-sim")
    public void telephonySwitchMultiSimConfig(
            @RpcParameter(name = "numOfSims")
            Integer numOfSims) {
        mTelephonyManager.switchMultiSimConfig(numOfSims.intValue());
    }

    /**
     * Gets device mode multisim
     *
     * @return phoneCount (1-single sim, 2-dual sim, 3-tri sim)
     **/
    @Rpc(description = "Returns if device is in Single, Dual, Tri SIM Mode")
    public Integer telephonyGetPhoneCount() {
        return mTelephonyManager.getPhoneCount();
    }

    @Rpc(description = "Get Authentication Challenge Response from a " +
            "given SIM Application")
    public String telephonyGetIccSimChallengeResponse(
            @RpcParameter(name = "appType") Integer appType,
            @RpcParameter(name = "authType") Integer authType,
            @RpcParameter(name = "hexChallenge") String hexChallenge) {
        return telephonyGetIccSimChallengeResponseForSubscription(
                SubscriptionManager.getDefaultSubscriptionId(), appType, authType, hexChallenge);
    }

    @Rpc(description = "Get Authentication Challenge Response from a " +
            "given SIM Application for a specified Subscription")
    public String telephonyGetIccSimChallengeResponseForSubscription(
            @RpcParameter(name = "subId") Integer subId,
            @RpcParameter(name = "appType") Integer appType,
            @RpcParameter(name = "authType") Integer authType,
            @RpcParameter(name = "hexChallenge") String hexChallenge) {

        try {
            String b64Data = BaseEncoding.base64().encode(BaseEncoding.base16().decode(hexChallenge));
            String b64Result = mTelephonyManager.getIccAuthentication(subId, appType, authType, b64Data);
            return (b64Result != null)
                    ? BaseEncoding.base16().encode(BaseEncoding.base64().decode(b64Result)) : null;
        } catch(Exception e) {
            Log.e("Exception in phoneGetIccSimChallengeResponseForSubscription" + e.toString());
            return null;
        }
    }

    /**
    * Supply the puk code and pin for locked SIM.
    * @param puk the puk code string
    * @param pin the puk pin string
    * @return    true or false for supplying the puk code and pin successfully or unsuccessfully.
    */
    @Rpc(description = "Supply Puk and Pin for locked SIM.")
    public boolean telephonySupplyPuk(
            @RpcParameter(name = "puk") String puk,
            @RpcParameter(name = "pin") String pin) {
        return mTelephonyManager.supplyPuk(puk, pin);
    }

    /**
    * Supply pin for locked SIM.
    * @param pin the puk pin string
    * @return    true or false for supplying the pin successfully or unsuccessfully.
    */
    @Rpc(description = "Supply Pin for locked SIM.")
    public boolean telephonySupplyPin(
            @RpcParameter(name = "pin") String pin) {
        return mTelephonyManager.supplyPin(pin);
    }

    @Rpc(description = "Returns the unique subscriber ID (such as IMSI) " +
            "for default subscription ID, or null if unavailable")
    public String telephonyGetSubscriberId() {
        return telephonyGetSubscriberIdForSubscription(
                SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Returns the unique subscriber ID (such as IMSI) " +
                       "for specified subscription ID, or null if unavailable")
    public String telephonyGetSubscriberIdForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getSubscriberId(subId);
    }

    @Rpc(description = "Retrieves the alphabetic id associated with the" +
                       " voice mail number for default subscription ID.")
    public String telephonyGetVoiceMailAlphaTag() {
        return telephonyGetVoiceMailAlphaTagForSubscription(
                   SubscriptionManager.getDefaultSubscriptionId());
    }


    @Rpc(description = "Retrieves the alphabetic id associated with the " +
                       "voice mail number for specified subscription ID.")
    public String telephonyGetVoiceMailAlphaTagForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getVoiceMailAlphaTag(subId);
    }

    @Rpc(description = "Returns the voice mail number " +
                       "for default subscription ID; null if unavailable.")
    public String telephonyGetVoiceMailNumber() {
        return telephonyGetVoiceMailNumberForSubscription(
                   SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Returns the voice mail number " +
                        "for specified subscription ID; null if unavailable.")
    public String telephonyGetVoiceMailNumberForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getVoiceMailNumber(subId);
    }

    @Rpc(description = "Get voice message count for specified subscription ID.")
    public Integer telephonyGetVoiceMailCountForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getVoiceMessageCount(subId);
    }

    @Rpc(description = "Get voice message count for default subscription ID.")
    public Integer telephonyGetVoiceMailCount() {
        return mTelephonyManager.getVoiceMessageCount();
    }

    @Rpc(description = "Returns true if the device is in  roaming state" +
                       "for default subscription ID")
    public Boolean telephonyCheckNetworkRoaming() {
        return telephonyCheckNetworkRoamingForSubscription(
                             SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Returns true if the device is in roaming state " +
                       "for specified subscription ID")
    public Boolean telephonyCheckNetworkRoamingForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.isNetworkRoaming(subId);
    }

    @Rpc(description = "Returns the unique device ID such as MEID or IMEI " +
                       "for deault sim slot ID, null if unavailable")
    public String telephonyGetDeviceId() {
        return telephonyGetDeviceIdForSlotId(mTelephonyManager.getSlotIndex());
    }

    @Rpc(description = "Returns the unique device ID such as MEID or IMEI for" +
                       " specified slot ID, null if unavailable")
    public String telephonyGetDeviceIdForSlotId(
                  @RpcParameter(name = "slotId")
                  Integer slotId){
        return mTelephonyManager.getDeviceId(slotId);
    }

    @Rpc(description = "Returns the modem sw version, such as IMEI-SV;" +
                       " null if unavailable")
    public String telephonyGetDeviceSoftwareVersion() {
        return mTelephonyManager.getDeviceSoftwareVersion();
    }

    @Rpc(description = "Returns phone # string \"line 1\", such as MSISDN " +
                       "for default subscription ID; null if unavailable")
    public String telephonyGetLine1Number() {
        return mTelephonyManager.getLine1Number();
    }

    @Rpc(description = "Returns phone # string \"line 1\", such as MSISDN " +
                       "for specified subscription ID; null if unavailable")
    public String telephonyGetLine1NumberForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getLine1Number(subId);
    }

    @Rpc(description = "Returns the Alpha Tag for the default subscription " +
                       "ID; null if unavailable")
    public String telephonyGetLine1AlphaTag() {
        return mTelephonyManager.getLine1AlphaTag();
    }

    @Rpc(description = "Returns the Alpha Tag for the specified subscription " +
                       "ID; null if unavailable")
    public String telephonyGetLine1AlphaTagForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getLine1AlphaTag(subId);
    }

    @Rpc(description = "Set the Line1-number (phone number) and Alpha Tag" +
                       "for the default subscription")
    public Boolean telephonySetLine1Number(
                @RpcParameter(name = "number") String number,
                @RpcOptional
                @RpcParameter(name = "alphaTag") String alphaTag) {
        return mTelephonyManager.setLine1NumberForDisplay(alphaTag, number);
    }

    @Rpc(description = "Set the Line1-number (phone number) and Alpha Tag" +
                       "for the specified subscription")
    public Boolean telephonySetLine1NumberForSubscription(
                @RpcParameter(name = "subId") Integer subId,
                @RpcParameter(name = "number") String number,
                @RpcOptional
                @RpcParameter(name = "alphaTag") String alphaTag) {
        return mTelephonyManager.setLine1NumberForDisplay(subId, alphaTag, number);
    }

    @Rpc(description = "Returns the neighboring cell information of the device.")
    public List<NeighboringCellInfo> telephonyGetNeighboringCellInfo() {
        return mTelephonyManager.getNeighboringCellInfo();
    }

    @Rpc(description =  "Sets the minimum reporting interval for CellInfo" +
                        "0-as quickly as possible, 0x7FFFFFF-off")
    public void telephonySetCellInfoListRate(
                @RpcParameter(name = "rate") Integer rate
            ) {
        mTelephonyManager.setCellInfoListRate(rate);
    }

    /**
     * Request a list of the current (latest) CellInfo.
     *
     * <p>When invoked on a device running Q or later, this will only return cached info.
     */
    @Rpc(description = "Returns all observed cell information from all radios"
                       + "on the device including the primary and neighboring cells.")
    public List<CellInfo> telephonyGetAllCellInfo() {
        return mTelephonyManager.getAllCellInfo();
    }

    private abstract class FacadeCellInfoCallback extends TelephonyManager.CellInfoCallback {
        public List<CellInfo> cellInfo;
    }

    /** Request an asynchronous update for the latest CellInfo */
    @Rpc(description = "Request updated CellInfo scan information for"
                       + " primary and neighboring cells.")
    public List<CellInfo> telephonyRequestCellInfoUpdate() {
        FacadeCellInfoCallback tmCiCb = new FacadeCellInfoCallback() {
            @Override
            public void onCellInfo(List<CellInfo> ci) {
                synchronized (this) {
                    this.cellInfo = ci;
                    notifyAll();
                }
            }

            @Override
            public void onError(int errorCode, Throwable detail) {
                Log.d("Error in telephonyRequestCellInfoUpdate(): errorCode=" + errorCode
                        + "detail=" + detail);
            }
        };

        synchronized (tmCiCb) {
            mTelephonyManager.requestCellInfoUpdate(
                    new Executor() {
                        public void execute(Runnable r) {
                            Log.d("Running cellInfo Executor");
                            r.run();
                        }
                    }, tmCiCb);
            try {
                tmCiCb.wait(3000 /* millis */);
            } catch (InterruptedException e) {
                Log.d("Timed out waiting for cellInfo Executor");
                return null;
            }
        }
        return tmCiCb.cellInfo;
    }

    @Rpc(description = "Returns True if cellular data is enabled for" +
                       "default data subscription ID.")
    public Boolean telephonyIsDataEnabled() {
        return telephonyIsDataEnabledForSubscription(
                   SubscriptionManager.getDefaultDataSubscriptionId());
    }

    @Rpc(description = "Returns True if data connection is enabled.")
    public Boolean telephonyIsDataEnabledForSubscription(
                   @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getDataEnabled(subId);
    }

    @Rpc(description = "Toggles data connection on /off for" +
                       " default data subscription ID.")
    public void telephonyToggleDataConnection(
                @RpcParameter(name = "enabled")
                @RpcOptional Boolean enabled) {
        telephonyToggleDataConnectionForSubscription(
                         SubscriptionManager.getDefaultDataSubscriptionId(), enabled);
    }

    @Rpc(description = "Toggles data connection on/off for" +
                       " specified subscription ID")
    public void telephonyToggleDataConnectionForSubscription(
                @RpcParameter(name = "subId") Integer subId,
                @RpcParameter(name = "enabled")
                @RpcOptional Boolean enabled) {
        if (enabled == null) {
            enabled = !telephonyIsDataEnabledForSubscription(subId);
        }
        mTelephonyManager.setDataEnabled(subId, enabled);
    }

    @Rpc(description = "Sets an APN and make that as preferred APN.")
    public void telephonySetAPN(@RpcParameter(name = "name") final String name,
                       @RpcParameter(name = "apn") final String apn,
                       @RpcParameter(name = "type") @RpcOptional @RpcDefault("")
                       final String type,
                       @RpcParameter(name = "subId") @RpcOptional Integer subId) {
        //TODO: b/26273471 Need to find out how to set APN for specific subId
        Uri uri;
        Cursor cursor;

        String mcc = "";
        String mnc = "";

        List<String> numerics = TelephonyProperties.icc_operator_numeric();
        String numeric = numerics.isEmpty() ? null : numerics.get(0);
        // MCC is first 3 chars and then in 2 - 3 chars of MNC
        if (numeric != null && numeric.length() > 4) {
            // Country code
            mcc = numeric.substring(0, 3);
            // Network code
            mnc = numeric.substring(3);
        }

        uri = mService.getContentResolver().insert(
                Telephony.Carriers.CONTENT_URI, new ContentValues());
        if (uri == null) {
            Log.w("Failed to insert new provider into " + Telephony.Carriers.CONTENT_URI);
            return;
        }

        cursor = mService.getContentResolver().query(uri, sProjection, null, null, null);
        cursor.moveToFirst();

        ContentValues values = new ContentValues();

        values.put(Telephony.Carriers.NAME, name);
        values.put(Telephony.Carriers.APN, apn);
        values.put(Telephony.Carriers.PROXY, "");
        values.put(Telephony.Carriers.PORT, "");
        values.put(Telephony.Carriers.MMSPROXY, "");
        values.put(Telephony.Carriers.MMSPORT, "");
        values.put(Telephony.Carriers.USER, "");
        values.put(Telephony.Carriers.SERVER, "");
        values.put(Telephony.Carriers.PASSWORD, "");
        values.put(Telephony.Carriers.MMSC, "");
        values.put(Telephony.Carriers.TYPE, type);
        values.put(Telephony.Carriers.MCC, mcc);
        values.put(Telephony.Carriers.MNC, mnc);
        values.put(Telephony.Carriers.NUMERIC, mcc + mnc);

        int ret = mService.getContentResolver().update(uri, values, null, null);
        Log.d("after update " + ret);
        cursor.close();

        // Make this APN as the preferred
        String where = "name=\"" + name + "\"";

        Cursor c = mService.getContentResolver().query(
                Telephony.Carriers.CONTENT_URI,
                new String[] {
                        "_id", "name", "apn", "type"
                }, where, null,
                Telephony.Carriers.DEFAULT_SORT_ORDER);
        if (c != null) {
            c.moveToFirst();
            String key = c.getString(0);
            final String PREFERRED_APN_URI = "content://telephony/carriers/preferapn";
            ContentResolver resolver = mService.getContentResolver();
            ContentValues prefAPN = new ContentValues();
            prefAPN.put("apn_id", key);
            resolver.update(Uri.parse(PREFERRED_APN_URI), prefAPN, null, null);
        }
        c.close();
    }

    @Rpc(description = "Returns the number of APNs defined")
    public int telephonyGetNumberOfAPNs(
               @RpcParameter(name = "subId")
               @RpcOptional Integer subId) {
        //TODO: b/26273471 Need to find out how to get Number of APNs for specific subId
        int result = 0;

        Cursor cursor = mService.getContentResolver().query(
                Telephony.Carriers.SIM_APN_URI,
                new String[] {"_id", "name", "apn", "type"}, null, null,
                Telephony.Carriers.DEFAULT_SORT_ORDER);

        if (cursor != null) {
            result = cursor.getCount();
        }
        cursor.close();
        return result;
    }

    @Rpc(description = "Returns the currently selected APN name")
    public String telephonyGetSelectedAPN(
                  @RpcParameter(name = "subId")
                  @RpcOptional Integer subId) {
        //TODO: b/26273471 Need to find out how to get selected APN for specific subId
        String key = null;
        int ID_INDEX = 0;
        final String PREFERRED_APN_URI = "content://telephony/carriers/preferapn";

        Cursor cursor = mService.getContentResolver().query(Uri.parse(PREFERRED_APN_URI),
                new String[] {"name"}, null, null, Telephony.Carriers.DEFAULT_SORT_ORDER);

        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            key = cursor.getString(ID_INDEX);
        }
        cursor.close();
        return key;
    }

    @Rpc(description = "Returns the current data connection state")
    public String telephonyGetDataConnectionState() {
        return TelephonyUtils.getDataConnectionStateString(
            mTelephonyManager.getDataState());
    }

    @Rpc(description = "Returns Total Rx Bytes.")
    public long getTotalRxBytes() {
        return TrafficStats.getTotalRxBytes();
    }

    @Rpc(description = "Returns Total Tx Bytes.")
    public long getTotalTxBytes() {
        return TrafficStats.getTotalTxBytes();
    }

    @Rpc(description = "Returns Total Rx Packets.")
    public long getTotalRxPackets() {
        return TrafficStats.getTotalRxPackets();
    }

    @Rpc(description = "Returns Total Tx Packets.")
    public long getTotalTxPackets() {
        return TrafficStats.getTotalTxPackets();
    }

    @Rpc(description = "Returns Mobile Network Rx Bytes.")
    public long getMobileRxBytes() {
        return TrafficStats.getMobileRxBytes();
    }

    @Rpc(description = "Returns Mobile Network Tx Bytes.")
    public long getMobileTxBytes() {
        return TrafficStats.getMobileTxBytes();
    }

    @Rpc(description = "Returns Mobile Network Packets.")
    public long getMobileRxPackets() {
        return TrafficStats.getMobileRxPackets();
    }

    @Rpc(description = "Returns Mobile Network Packets.")
    public long getMobileTxPackets() {
        return TrafficStats.getMobileTxPackets();
    }

    @Rpc(description = "Returns a given UID Rx Bytes.")
    public long getUidRxBytes(
            @RpcParameter(name = "uid") Integer uid) {
        return TrafficStats.getUidRxBytes(uid);
    }

    @Rpc(description = "Returns a given UID Rx Packets.")
    public long getUidRxPackets(
            @RpcParameter(name = "uid") Integer uid) {
        return TrafficStats.getUidRxPackets(uid);
    }

    @Rpc(description = "Enables or Disables Video Calling()")
    public void telephonyEnableVideoCalling(
            @RpcParameter(name = "enable") boolean enable) {
        mTelephonyManager.enableVideoCalling(enable);
    }

    @Rpc(description = "Returns a boolean of whether or not " +
            "video calling setting is enabled by the user")
    public Boolean telephonyIsVideoCallingEnabled() {
        return mTelephonyManager.isVideoCallingEnabled();
    }

    @Rpc(description = "Returns a boolean of whether video calling is available for use")
    public Boolean telephonyIsVideoCallingAvailable() {
        return mTelephonyManager.isVideoTelephonyAvailable();
    }

    @Rpc(description = "Returns a boolean of whether or not the device is ims registered")
    public Boolean telephonyIsImsRegistered() {
        return mTelephonyManager.isImsRegistered();
    }

    @Rpc(description = "Returns a boolean of whether or not volte calling is available for use")
    public Boolean telephonyIsVolteAvailable() {
        return mTelephonyManager.isVolteAvailable();
    }

    @Rpc(description = "Returns a boolean of whether or not wifi calling is available for use")
    public Boolean telephonyIsWifiCallingAvailable() {
        return mTelephonyManager.isWifiCallingAvailable();
    }

    @Rpc(description = "Returns the service state string for default subscription ID")
    public ServiceState telephonyGetServiceState() {
        return telephonyGetServiceStateForSubscription(
                                 SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Returns the service state string for specified subscription ID")
    public ServiceState telephonyGetServiceStateForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return mTelephonyManager.getServiceStateForSubscriber(subId);
    }

    @Rpc(description = "Returns the call state for default subscription ID")
    public String telephonyGetCallState() {
        return telephonyGetCallStateForSubscription(
                               SubscriptionManager.getDefaultSubscriptionId());
    }

    @Rpc(description = "Returns the call state for specified subscription ID")
    public String telephonyGetCallStateForSubscription(
                  @RpcParameter(name = "subId") Integer subId) {
        return TelephonyUtils.getTelephonyCallStateString(
            mTelephonyManager.getCallState(subId));
    }

    @Rpc(description = "Returns current signal strength for default subscription ID.")
    public SignalStrength telephonyGetSignalStrength() {
        return mTelephonyManager.getSignalStrength();
    }

    @Rpc(description = "Returns current signal strength for specified subscription ID.")
    public SignalStrength telephonyGetSignalStrengthForSubscription(
                    @RpcParameter(name = "subId") Integer subId) {
        StateChangeListener listener = getStateChangeListenerForSubscription(subId, false);
        if(listener == null) {
            Log.e("Invalid subscription ID");
            return null;
        }
        return listener.mSignalStrengthChangeListener.mSignalStrengths;
    }

    @Rpc(description = "Returns the sim count.")
    public int telephonyGetSimCount() {
        return mTelephonyManager.getSimCount();
    }

    /**
     * Get the list of Forbidden PLMNs stored on the USIM
     * profile of the SIM for the default subscription.
     */
    @Rpc(description = "Returns a list of forbidden PLMNs")
    public @Nullable List<String> telephonyGetForbiddenPlmns() {
        String[] fplmns = mTelephonyManager.getForbiddenPlmns(
                SubscriptionManager.getDefaultSubscriptionId(),
                TelephonyManager.APPTYPE_USIM);

        if (fplmns != null) {
            return Arrays.asList(fplmns);
        }
        return null;
    }

    private StateChangeListener getStateChangeListenerForSubscription(
            int subId,
            boolean createIfNeeded) {

       if(mStateChangeListeners.get(subId) == null) {
            if(createIfNeeded == false) {
                return null;
            }

            if(mSubscriptionManager.isValidSubscriptionId(subId) == false) {
                Log.e("Cannot get listener for invalid/inactive subId");
                return null;
            }

            mStateChangeListeners.put(subId, new StateChangeListener(subId));
        }

        return mStateChangeListeners.get(subId);
    }

    //FIXME: This whole class needs reworking. Why do we have separate listeners for everything?
    //We need one listener that overrides multiple methods.
    private final class StateChangeListener {
        public ServiceStateChangeListener mServiceStateChangeListener;
        public SignalStrengthChangeListener mSignalStrengthChangeListener;
        public CallStateChangeListener mCallStateChangeListener;
        public CellInfoChangeListener mCellInfoChangeListener;
        public DataConnectionStateChangeListener mDataConnectionStateChangeListener;
        public ActiveDataSubIdChangeListener mActiveDataSubIdChangeListener;
        public DisplayInfoStateChangeListener mDisplayInfoStateChangeListener;
        public DataConnectionRealTimeInfoChangeListener mDataConnectionRTInfoChangeListener;
        public VoiceMailStateChangeListener mVoiceMailStateChangeListener;

        public StateChangeListener(int subId) {
            mServiceStateChangeListener =
                new ServiceStateChangeListener(mEventFacade, subId, mService.getMainLooper());
            mSignalStrengthChangeListener =
                new SignalStrengthChangeListener(mEventFacade, subId, mService.getMainLooper());
            mDataConnectionStateChangeListener =
                new DataConnectionStateChangeListener(
                        mEventFacade, mTelephonyManager, subId, mService.getMainLooper());
            mActiveDataSubIdChangeListener =
                new ActiveDataSubIdChangeListener(
                        mEventFacade, mTelephonyManager, subId, mService.getMainLooper());
            mDisplayInfoStateChangeListener =
                new DisplayInfoStateChangeListener(
                        mEventFacade, mTelephonyManager, subId, mService.getMainLooper());
            mCallStateChangeListener =
                new CallStateChangeListener(mEventFacade, subId, mService.getMainLooper());
            mCellInfoChangeListener =
                new CellInfoChangeListener(mEventFacade, subId, mService.getMainLooper());
            mDataConnectionRTInfoChangeListener =
                new DataConnectionRealTimeInfoChangeListener(
                        mEventFacade, subId, mService.getMainLooper());
            mVoiceMailStateChangeListener =
                new VoiceMailStateChangeListener(mEventFacade, subId, mService.getMainLooper());
        }

        public void shutdown() {
            mTelephonyManager.listen(
                    mServiceStateChangeListener,
                    PhoneStateListener.LISTEN_NONE);
            mTelephonyManager.listen(
                    mSignalStrengthChangeListener,
                    PhoneStateListener.LISTEN_NONE);
            mTelephonyManager.listen(
                    mCallStateChangeListener,
                    PhoneStateListener.LISTEN_NONE);
            mTelephonyManager.listen(
                    mActiveDataSubIdChangeListener,
                    PhoneStateListener.LISTEN_NONE);
            mTelephonyManager.listen(
                    mDisplayInfoStateChangeListener,
                    PhoneStateListener.LISTEN_NONE);
            mTelephonyManager.listen(
                    mCellInfoChangeListener,
                    PhoneStateListener.LISTEN_NONE);
            mTelephonyManager.listen(
                    mDataConnectionStateChangeListener,
                    PhoneStateListener.LISTEN_NONE);
            mTelephonyManager.listen(
                    mDataConnectionRTInfoChangeListener,
                    PhoneStateListener.LISTEN_NONE);
            mTelephonyManager.listen(
                    mVoiceMailStateChangeListener,
                    PhoneStateListener.LISTEN_NONE);
        }

        protected void finalize() {
            try {
                shutdown();
            } catch(Exception e) {}
        }
    }

    @Override
    public void shutdown() {
        for(StateChangeListener listener : mStateChangeListeners.values()) {
            listener.shutdown();
        }
    }
}