aboutsummaryrefslogtreecommitdiff
path: root/src/java/com/android/internal/telephony/metrics/PersistAtomsStorage.java
blob: 13ba91b269db9c3f19aca36f267c87047f4d1790 (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
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
/*
 * Copyright (C) 2020 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.metrics;

import static android.text.format.DateUtils.DAY_IN_MILLIS;

import android.annotation.Nullable;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.telephony.TelephonyManager;
import android.telephony.TelephonyManager.NetworkTypeBitMask;
import android.util.SparseIntArray;

import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.telephony.nano.PersistAtomsProto.CarrierIdMismatch;
import com.android.internal.telephony.nano.PersistAtomsProto.CellularDataServiceSwitch;
import com.android.internal.telephony.nano.PersistAtomsProto.CellularServiceState;
import com.android.internal.telephony.nano.PersistAtomsProto.DataCallSession;
import com.android.internal.telephony.nano.PersistAtomsProto.GbaEvent;
import com.android.internal.telephony.nano.PersistAtomsProto.ImsDedicatedBearerEvent;
import com.android.internal.telephony.nano.PersistAtomsProto.ImsDedicatedBearerListenerEvent;
import com.android.internal.telephony.nano.PersistAtomsProto.ImsRegistrationFeatureTagStats;
import com.android.internal.telephony.nano.PersistAtomsProto.ImsRegistrationServiceDescStats;
import com.android.internal.telephony.nano.PersistAtomsProto.ImsRegistrationStats;
import com.android.internal.telephony.nano.PersistAtomsProto.ImsRegistrationTermination;
import com.android.internal.telephony.nano.PersistAtomsProto.IncomingSms;
import com.android.internal.telephony.nano.PersistAtomsProto.NetworkRequestsV2;
import com.android.internal.telephony.nano.PersistAtomsProto.OutgoingShortCodeSms;
import com.android.internal.telephony.nano.PersistAtomsProto.OutgoingSms;
import com.android.internal.telephony.nano.PersistAtomsProto.PersistAtoms;
import com.android.internal.telephony.nano.PersistAtomsProto.PresenceNotifyEvent;
import com.android.internal.telephony.nano.PersistAtomsProto.RcsAcsProvisioningStats;
import com.android.internal.telephony.nano.PersistAtomsProto.RcsClientProvisioningStats;
import com.android.internal.telephony.nano.PersistAtomsProto.SatelliteController;
import com.android.internal.telephony.nano.PersistAtomsProto.SatelliteIncomingDatagram;
import com.android.internal.telephony.nano.PersistAtomsProto.SatelliteOutgoingDatagram;
import com.android.internal.telephony.nano.PersistAtomsProto.SatelliteProvision;
import com.android.internal.telephony.nano.PersistAtomsProto.SatelliteSession;
import com.android.internal.telephony.nano.PersistAtomsProto.SatelliteSosMessageRecommender;
import com.android.internal.telephony.nano.PersistAtomsProto.SipDelegateStats;
import com.android.internal.telephony.nano.PersistAtomsProto.SipMessageResponse;
import com.android.internal.telephony.nano.PersistAtomsProto.SipTransportFeatureTagStats;
import com.android.internal.telephony.nano.PersistAtomsProto.SipTransportSession;
import com.android.internal.telephony.nano.PersistAtomsProto.UceEventStats;
import com.android.internal.telephony.nano.PersistAtomsProto.UnmeteredNetworks;
import com.android.internal.telephony.nano.PersistAtomsProto.VoiceCallRatUsage;
import com.android.internal.telephony.nano.PersistAtomsProto.VoiceCallSession;
import com.android.internal.util.ArrayUtils;
import com.android.telephony.Rlog;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;

/**
 * Stores and aggregates metrics that should not be pulled at arbitrary frequency.
 *
 * <p>NOTE: while this class checks timestamp against {@code minIntervalMillis}, it is {@link
 * MetricsCollector}'s responsibility to ensure {@code minIntervalMillis} is set correctly.
 */
public class PersistAtomsStorage {
    private static final String TAG = PersistAtomsStorage.class.getSimpleName();

    /** Name of the file where cached statistics are saved to. */
    private static final String FILENAME = "persist_atoms.pb";

    /** Delay to store atoms to persistent storage to bundle multiple operations together. */
    private static final int SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS = 30000;

    /**
     * Delay to store atoms to persistent storage during pulls to avoid unnecessary operations.
     *
     * <p>This delay should be short to avoid duplicating atoms or losing pull timestamp in case of
     * crash or power loss.
     */
    private static final int SAVE_TO_FILE_DELAY_FOR_GET_MILLIS = 500;

    /** Maximum number of call sessions to store between pulls. */
    private final int mMaxNumVoiceCallSessions;

    /**
     * Maximum number of SMS to store between pulls. Incoming messages and outgoing messages are
     * counted separately.
     */
    private final int mMaxNumSms;

    /**
     * Maximum number of carrier ID mismatch events stored on the device to avoid sending duplicated
     * metrics.
     */
    private final int mMaxNumCarrierIdMismatches;

    /** Maximum number of data call sessions to store during pulls. */
    private final int mMaxNumDataCallSessions;

    /** Maximum number of service states to store between pulls. */
    private final int mMaxNumCellularServiceStates;

    /** Maximum number of data service switches to store between pulls. */
    private final int mMaxNumCellularDataSwitches;

    /** Maximum number of IMS registration stats to store between pulls. */
    private final int mMaxNumImsRegistrationStats;

    /** Maximum number of IMS registration terminations to store between pulls. */
    private final int mMaxNumImsRegistrationTerminations;

    /** Maximum number of IMS Registration Feature Tags to store between pulls. */
    private final int mMaxNumImsRegistrationFeatureStats;

    /** Maximum number of RCS Client Provisioning to store between pulls. */
    private final int mMaxNumRcsClientProvisioningStats;

    /** Maximum number of RCS Acs Provisioning to store between pulls. */
    private final int mMaxNumRcsAcsProvisioningStats;

    /** Maximum number of Sip Message Response to store between pulls. */
    private final int mMaxNumSipMessageResponseStats;

    /** Maximum number of Sip Transport Session to store between pulls. */
    private final int mMaxNumSipTransportSessionStats;

    /** Maximum number of Sip Delegate to store between pulls. */
    private final int mMaxNumSipDelegateStats;

    /** Maximum number of Sip Transport Feature Tag to store between pulls. */
    private final int mMaxNumSipTransportFeatureTagStats;

    /** Maximum number of Dedicated Bearer Listener Event to store between pulls. */
    private final int mMaxNumDedicatedBearerListenerEventStats;

    /** Maximum number of Dedicated Bearer Event to store between pulls. */
    private final int mMaxNumDedicatedBearerEventStats;

    /** Maximum number of IMS Registration Service Desc to store between pulls. */
    private final int mMaxNumImsRegistrationServiceDescStats;

    /** Maximum number of UCE Event to store between pulls. */
    private final int mMaxNumUceEventStats;

    /** Maximum number of Presence Notify Event to store between pulls. */
    private final int mMaxNumPresenceNotifyEventStats;

    /** Maximum number of GBA Event to store between pulls. */
    private final int mMaxNumGbaEventStats;

    /** Maximum number of outgoing short code sms to store between pulls. */
    private final int mMaxOutgoingShortCodeSms;

    /** Maximum number of Satellite relevant stats to store between pulls. */
    private final int mMaxNumSatelliteStats;
    private final int mMaxNumSatelliteControllerStats = 1;

    /** Stores persist atoms and persist states of the puller. */
    @VisibleForTesting protected PersistAtoms mAtoms;

    /** Aggregates RAT duration and call count. */
    private final VoiceCallRatTracker mVoiceCallRatTracker;

    /** Whether atoms should be saved immediately, skipping the delay. */
    @VisibleForTesting protected boolean mSaveImmediately;

    private final Context mContext;
    private final Handler mHandler;
    private final HandlerThread mHandlerThread;
    private static final SecureRandom sRandom = new SecureRandom();

    private Runnable mSaveRunnable =
            new Runnable() {
                @Override
                public void run() {
                    saveAtomsToFileNow();
                }
            };

    public PersistAtomsStorage(Context context) {
        mContext = context;

        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_RAM_LOW)) {
            Rlog.i(TAG, "Low RAM device");
            mMaxNumVoiceCallSessions = 10;
            mMaxNumSms = 5;
            mMaxNumCarrierIdMismatches = 8;
            mMaxNumDataCallSessions = 5;
            mMaxNumCellularServiceStates = 10;
            mMaxNumCellularDataSwitches = 5;
            mMaxNumImsRegistrationStats = 5;
            mMaxNumImsRegistrationTerminations = 5;
            mMaxNumImsRegistrationFeatureStats = 15;
            mMaxNumRcsClientProvisioningStats = 5;
            mMaxNumRcsAcsProvisioningStats = 5;
            mMaxNumSipMessageResponseStats = 10;
            mMaxNumSipTransportSessionStats = 10;
            mMaxNumSipDelegateStats = 5;
            mMaxNumSipTransportFeatureTagStats = 15;
            mMaxNumDedicatedBearerListenerEventStats = 5;
            mMaxNumDedicatedBearerEventStats = 5;
            mMaxNumImsRegistrationServiceDescStats = 15;
            mMaxNumUceEventStats = 5;
            mMaxNumPresenceNotifyEventStats = 10;
            mMaxNumGbaEventStats = 5;
            mMaxOutgoingShortCodeSms = 5;
            mMaxNumSatelliteStats = 5;
        } else {
            mMaxNumVoiceCallSessions = 50;
            mMaxNumSms = 25;
            mMaxNumCarrierIdMismatches = 40;
            mMaxNumDataCallSessions = 15;
            mMaxNumCellularServiceStates = 50;
            mMaxNumCellularDataSwitches = 50;
            mMaxNumImsRegistrationStats = 10;
            mMaxNumImsRegistrationTerminations = 10;
            mMaxNumImsRegistrationFeatureStats = 25;
            mMaxNumRcsClientProvisioningStats = 10;
            mMaxNumRcsAcsProvisioningStats = 10;
            mMaxNumSipMessageResponseStats = 25;
            mMaxNumSipTransportSessionStats = 25;
            mMaxNumSipDelegateStats = 10;
            mMaxNumSipTransportFeatureTagStats = 25;
            mMaxNumDedicatedBearerListenerEventStats = 10;
            mMaxNumDedicatedBearerEventStats = 10;
            mMaxNumImsRegistrationServiceDescStats = 25;
            mMaxNumUceEventStats = 25;
            mMaxNumPresenceNotifyEventStats = 50;
            mMaxNumGbaEventStats = 10;
            mMaxOutgoingShortCodeSms = 10;
            mMaxNumSatelliteStats = 15;
        }

        mAtoms = loadAtomsFromFile();
        mVoiceCallRatTracker = VoiceCallRatTracker.fromProto(mAtoms.voiceCallRatUsage);

        mHandlerThread = new HandlerThread("PersistAtomsThread");
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper());
        mSaveImmediately = false;
    }

    /** Adds a call to the storage. */
    public synchronized void addVoiceCallSession(VoiceCallSession call) {
        mAtoms.voiceCallSession =
                insertAtRandomPlace(mAtoms.voiceCallSession, call, mMaxNumVoiceCallSessions);
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);

        Rlog.d(TAG, "Add new voice call session: " + call.toString());
    }

    /** Adds RAT usages to the storage when a call session ends. */
    public synchronized void addVoiceCallRatUsage(VoiceCallRatTracker ratUsages) {
        mVoiceCallRatTracker.mergeWith(ratUsages);
        mAtoms.voiceCallRatUsage = mVoiceCallRatTracker.toProto();
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds an incoming SMS to the storage. */
    public synchronized void addIncomingSms(IncomingSms sms) {
        sms.hashCode = SmsStats.getSmsHashCode(sms);
        mAtoms.incomingSms = insertAtRandomPlace(mAtoms.incomingSms, sms, mMaxNumSms);
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);

        // To be removed
        Rlog.d(TAG, "Add new incoming SMS atom: " + sms.toString());
    }

    /** Adds an outgoing SMS to the storage. */
    public synchronized void addOutgoingSms(OutgoingSms sms) {
        sms.hashCode = SmsStats.getSmsHashCode(sms);
        // Update the retry id, if needed, so that it's unique and larger than all
        // previous ones. (this algorithm ignores the fact that some SMS atoms might
        // be dropped due to limit in size of the array).
        for (OutgoingSms storedSms : mAtoms.outgoingSms) {
            if (storedSms.messageId == sms.messageId && storedSms.retryId >= sms.retryId) {
                sms.retryId = storedSms.retryId + 1;
            }
        }

        mAtoms.outgoingSms = insertAtRandomPlace(mAtoms.outgoingSms, sms, mMaxNumSms);
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);

        // To be removed
        Rlog.d(TAG, "Add new outgoing SMS atom: " + sms.toString());
    }

    /** Adds a service state to the storage, together with data service switch if any. */
    public synchronized void addCellularServiceStateAndCellularDataServiceSwitch(
            CellularServiceState state, @Nullable CellularDataServiceSwitch serviceSwitch) {
        CellularServiceState existingState = find(state);
        if (existingState != null) {
            existingState.totalTimeMillis += state.totalTimeMillis;
            existingState.lastUsedMillis = getWallTimeMillis();
        } else {
            state.lastUsedMillis = getWallTimeMillis();
            mAtoms.cellularServiceState =
                    insertAtRandomPlace(
                            mAtoms.cellularServiceState, state, mMaxNumCellularServiceStates);
        }

        if (serviceSwitch != null) {
            CellularDataServiceSwitch existingSwitch = find(serviceSwitch);
            if (existingSwitch != null) {
                existingSwitch.switchCount += serviceSwitch.switchCount;
                existingSwitch.lastUsedMillis = getWallTimeMillis();
            } else {
                serviceSwitch.lastUsedMillis = getWallTimeMillis();
                mAtoms.cellularDataServiceSwitch =
                        insertAtRandomPlace(
                                mAtoms.cellularDataServiceSwitch,
                                serviceSwitch,
                                mMaxNumCellularDataSwitches);
            }
        }

        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a data call session to the storage. */
    public synchronized void addDataCallSession(DataCallSession dataCall) {
        int index = findIndex(dataCall);
        if (index >= 0) {
            DataCallSession existingCall = mAtoms.dataCallSession[index];
            dataCall.ratSwitchCount += existingCall.ratSwitchCount;
            dataCall.durationMinutes += existingCall.durationMinutes;

            dataCall.handoverFailureCauses = IntStream.concat(Arrays.stream(
                            dataCall.handoverFailureCauses),
                    Arrays.stream(existingCall.handoverFailureCauses))
                    .limit(DataCallSessionStats.SIZE_LIMIT_HANDOVER_FAILURES).toArray();
            dataCall.handoverFailureRat = IntStream.concat(Arrays.stream(
                            dataCall.handoverFailureRat),
                    Arrays.stream(existingCall.handoverFailureRat))
                    .limit(DataCallSessionStats.SIZE_LIMIT_HANDOVER_FAILURES).toArray();

            mAtoms.dataCallSession[index] = dataCall;
        } else {
            mAtoms.dataCallSession =
                    insertAtRandomPlace(mAtoms.dataCallSession, dataCall, mMaxNumDataCallSessions);
        }

        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /**
     * Adds a new carrier ID mismatch event to the storage.
     *
     * @return true if the item was not present and was added to the persistent storage, false
     *     otherwise.
     */
    public synchronized boolean addCarrierIdMismatch(CarrierIdMismatch carrierIdMismatch) {
        // Check if the details of the SIM cards are already present and in case return.
        if (find(carrierIdMismatch) != null) {
            return false;
        }
        // Add the new CarrierIdMismatch at the end of the array, so that the same atom will not be
        // sent again in future.
        if (mAtoms.carrierIdMismatch.length == mMaxNumCarrierIdMismatches) {
            System.arraycopy(
                    mAtoms.carrierIdMismatch,
                    1,
                    mAtoms.carrierIdMismatch,
                    0,
                    mMaxNumCarrierIdMismatches - 1);
            mAtoms.carrierIdMismatch[mMaxNumCarrierIdMismatches - 1] = carrierIdMismatch;
        } else {
            mAtoms.carrierIdMismatch =
                    ArrayUtils.appendElement(
                            CarrierIdMismatch.class,
                            mAtoms.carrierIdMismatch,
                            carrierIdMismatch,
                            true);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
        return true;
    }

    /** Adds IMS registration stats to the storage. */
    public synchronized void addImsRegistrationStats(ImsRegistrationStats stats) {
        ImsRegistrationStats existingStats = find(stats);
        if (existingStats != null) {
            existingStats.registeredMillis += stats.registeredMillis;
            existingStats.voiceCapableMillis += stats.voiceCapableMillis;
            existingStats.voiceAvailableMillis += stats.voiceAvailableMillis;
            existingStats.smsCapableMillis += stats.smsCapableMillis;
            existingStats.smsAvailableMillis += stats.smsAvailableMillis;
            existingStats.videoCapableMillis += stats.videoCapableMillis;
            existingStats.videoAvailableMillis += stats.videoAvailableMillis;
            existingStats.utCapableMillis += stats.utCapableMillis;
            existingStats.utAvailableMillis += stats.utAvailableMillis;
            existingStats.lastUsedMillis = getWallTimeMillis();
        } else {
            stats.lastUsedMillis = getWallTimeMillis();
            mAtoms.imsRegistrationStats =
                    insertAtRandomPlace(
                            mAtoms.imsRegistrationStats, stats, mMaxNumImsRegistrationStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds IMS registration termination to the storage. */
    public synchronized void addImsRegistrationTermination(ImsRegistrationTermination termination) {
        ImsRegistrationTermination existingTermination = find(termination);
        if (existingTermination != null) {
            existingTermination.count += termination.count;
            existingTermination.lastUsedMillis = getWallTimeMillis();
        } else {
            termination.lastUsedMillis = getWallTimeMillis();
            mAtoms.imsRegistrationTermination =
                    insertAtRandomPlace(
                            mAtoms.imsRegistrationTermination,
                            termination,
                            mMaxNumImsRegistrationTerminations);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /**
     * Stores the version of the carrier ID matching table.
     *
     * @return true if the version is newer than last available version, false otherwise.
     */
    public synchronized boolean setCarrierIdTableVersion(int carrierIdTableVersion) {
        if (mAtoms.carrierIdTableVersion < carrierIdTableVersion) {
            mAtoms.carrierIdTableVersion = carrierIdTableVersion;
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
            return true;
        } else {
            return false;
        }
    }

    /**
     * Store the number of times auto data switch feature is toggled.
     */
    public synchronized void recordToggledAutoDataSwitch() {
        mAtoms.autoDataSwitchToggleCount++;
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link NetworkRequestsV2} to the storage. */
    public synchronized void addNetworkRequestsV2(NetworkRequestsV2 networkRequests) {
        NetworkRequestsV2 existingMetrics = find(networkRequests);
        if (existingMetrics != null) {
            existingMetrics.requestCount += networkRequests.requestCount;
        } else {
            NetworkRequestsV2 newMetrics = new NetworkRequestsV2();
            newMetrics.capability = networkRequests.capability;
            newMetrics.carrierId = networkRequests.carrierId;
            newMetrics.requestCount = networkRequests.requestCount;
            mAtoms.networkRequestsV2 =
                    ArrayUtils.appendElement(
                            NetworkRequestsV2.class, mAtoms.networkRequestsV2, newMetrics, true);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link ImsRegistrationFeatureTagStats} to the storage. */
    public synchronized void addImsRegistrationFeatureTagStats(
                ImsRegistrationFeatureTagStats stats) {
        ImsRegistrationFeatureTagStats existingStats = find(stats);
        if (existingStats != null) {
            existingStats.registeredMillis += stats.registeredMillis;
        } else {
            mAtoms.imsRegistrationFeatureTagStats =
                insertAtRandomPlace(mAtoms.imsRegistrationFeatureTagStats,
                    stats, mMaxNumImsRegistrationFeatureStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link RcsClientProvisioningStats} to the storage. */
    public synchronized void addRcsClientProvisioningStats(RcsClientProvisioningStats stats) {
        RcsClientProvisioningStats existingStats = find(stats);
        if (existingStats != null) {
            existingStats.count += 1;
        } else {
            mAtoms.rcsClientProvisioningStats =
                insertAtRandomPlace(mAtoms.rcsClientProvisioningStats, stats,
                        mMaxNumRcsClientProvisioningStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link RcsAcsProvisioningStats} to the storage. */
    public synchronized void addRcsAcsProvisioningStats(RcsAcsProvisioningStats stats) {
        RcsAcsProvisioningStats existingStats = find(stats);
        if (existingStats != null) {
            existingStats.count += 1;
            existingStats.stateTimerMillis += stats.stateTimerMillis;
        } else {
            // prevent that wrong count from caller effects total count
            stats.count = 1;
            mAtoms.rcsAcsProvisioningStats =
                insertAtRandomPlace(mAtoms.rcsAcsProvisioningStats, stats,
                        mMaxNumRcsAcsProvisioningStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link SipDelegateStats} to the storage. */
    public synchronized void addSipDelegateStats(SipDelegateStats stats) {
        mAtoms.sipDelegateStats = insertAtRandomPlace(mAtoms.sipDelegateStats, stats,
                mMaxNumSipDelegateStats);
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link SipTransportFeatureTagStats} to the storage. */
    public synchronized void addSipTransportFeatureTagStats(SipTransportFeatureTagStats stats) {
        SipTransportFeatureTagStats lastStat = find(stats);
        if (lastStat != null) {
            lastStat.associatedMillis += stats.associatedMillis;
        } else {
            mAtoms.sipTransportFeatureTagStats =
                    insertAtRandomPlace(mAtoms.sipTransportFeatureTagStats, stats,
                            mMaxNumSipTransportFeatureTagStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link SipMessageResponse} to the storage. */
    public synchronized void addSipMessageResponse(SipMessageResponse stats) {
        SipMessageResponse existingStats = find(stats);
        if (existingStats != null) {
            existingStats.count += 1;
        } else {
            mAtoms.sipMessageResponse = insertAtRandomPlace(mAtoms.sipMessageResponse, stats,
                    mMaxNumSipMessageResponseStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link SipTransportSession} to the storage. */
    public synchronized void addCompleteSipTransportSession(SipTransportSession stats) {
        SipTransportSession existingStats = find(stats);
        if (existingStats != null) {
            existingStats.sessionCount += 1;
            if (stats.isEndedGracefully) {
                existingStats.endedGracefullyCount += 1;
            }
        } else {
            mAtoms.sipTransportSession =
                    insertAtRandomPlace(mAtoms.sipTransportSession, stats,
                            mMaxNumSipTransportSessionStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link ImsDedicatedBearerListenerEvent} to the storage. */
    public synchronized void addImsDedicatedBearerListenerEvent(
                ImsDedicatedBearerListenerEvent stats) {
        ImsDedicatedBearerListenerEvent existingStats = find(stats);
        if (existingStats != null) {
            existingStats.eventCount += 1;
        } else {
            mAtoms.imsDedicatedBearerListenerEvent =
                insertAtRandomPlace(mAtoms.imsDedicatedBearerListenerEvent,
                    stats, mMaxNumDedicatedBearerListenerEventStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link ImsDedicatedBearerEvent} to the storage. */
    public synchronized void addImsDedicatedBearerEvent(ImsDedicatedBearerEvent stats) {
        ImsDedicatedBearerEvent existingStats = find(stats);
        if (existingStats != null) {
            existingStats.count += 1;
        } else {
            mAtoms.imsDedicatedBearerEvent =
                insertAtRandomPlace(mAtoms.imsDedicatedBearerEvent, stats,
                        mMaxNumDedicatedBearerEventStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link ImsRegistrationServiceDescStats} to the storage. */
    public synchronized void addImsRegistrationServiceDescStats(
            ImsRegistrationServiceDescStats stats) {
        ImsRegistrationServiceDescStats existingStats = find(stats);
        if (existingStats != null) {
            existingStats.publishedMillis += stats.publishedMillis;
        } else {
            mAtoms.imsRegistrationServiceDescStats =
                insertAtRandomPlace(mAtoms.imsRegistrationServiceDescStats,
                    stats, mMaxNumImsRegistrationServiceDescStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link UceEventStats} to the storage. */
    public synchronized void addUceEventStats(UceEventStats stats) {
        UceEventStats existingStats = find(stats);
        if (existingStats != null) {
            existingStats.count += 1;
        } else {
            mAtoms.uceEventStats =
                insertAtRandomPlace(mAtoms.uceEventStats, stats, mMaxNumUceEventStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link PresenceNotifyEvent} to the storage. */
    public synchronized void addPresenceNotifyEvent(PresenceNotifyEvent stats) {
        PresenceNotifyEvent existingStats = find(stats);
        if (existingStats != null) {
            existingStats.rcsCapsCount += stats.rcsCapsCount;
            existingStats.mmtelCapsCount += stats.mmtelCapsCount;
            existingStats.noCapsCount += stats.noCapsCount;
            existingStats.count += stats.count;
        } else {
            mAtoms.presenceNotifyEvent =
                insertAtRandomPlace(mAtoms.presenceNotifyEvent, stats,
                        mMaxNumPresenceNotifyEventStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link GbaEvent} to the storage. */
    public synchronized void addGbaEvent(GbaEvent stats) {
        GbaEvent existingStats = find(stats);
        if (existingStats != null) {
            existingStats.count += 1;
        } else {
            mAtoms.gbaEvent =
                insertAtRandomPlace(mAtoms.gbaEvent, stats, mMaxNumGbaEventStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /**
     *  Sets the unmetered networks bitmask for a given phone id. If the carrier id
     *  doesn't match the existing UnmeteredNetworks' carrier id, the bitmask is
     *  first reset to 0.
     */
    public synchronized void addUnmeteredNetworks(
            int phoneId, int carrierId, @NetworkTypeBitMask long bitmask) {
        UnmeteredNetworks stats = findUnmeteredNetworks(phoneId);
        boolean needToSave = true;
        if (stats == null) {
            stats = new UnmeteredNetworks();
            stats.phoneId = phoneId;
            stats.carrierId = carrierId;
            stats.unmeteredNetworksBitmask = bitmask;
            mAtoms.unmeteredNetworks =
                    ArrayUtils.appendElement(
                            UnmeteredNetworks.class, mAtoms.unmeteredNetworks, stats, true);
        } else {
            // Reset the bitmask to 0 if carrier id doesn't match.
            if (stats.carrierId != carrierId) {
                stats.carrierId = carrierId;
                stats.unmeteredNetworksBitmask = 0;
            }
            if ((stats.unmeteredNetworksBitmask | bitmask) != stats.unmeteredNetworksBitmask) {
                stats.unmeteredNetworksBitmask |= bitmask;
            } else {
                needToSave = false;
            }
        }
        // Only save if something changes.
        if (needToSave) {
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
        }
    }

    /** Adds an outgoing short code sms to the storage. */
    public synchronized void addOutgoingShortCodeSms(OutgoingShortCodeSms shortCodeSms) {
        OutgoingShortCodeSms existingOutgoingShortCodeSms = find(shortCodeSms);
        if (existingOutgoingShortCodeSms != null) {
            existingOutgoingShortCodeSms.shortCodeSmsCount += 1;
        } else {
            mAtoms.outgoingShortCodeSms = insertAtRandomPlace(mAtoms.outgoingShortCodeSms,
                    shortCodeSms, mMaxOutgoingShortCodeSms);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link SatelliteController} to the storage. */
    public synchronized void addSatelliteControllerStats(SatelliteController stats) {
        // SatelliteController is a single data point
        SatelliteController[] atomArray = mAtoms.satelliteController;
        if (atomArray == null || atomArray.length == 0) {
            atomArray = new SatelliteController[] {new SatelliteController()};
        }

        SatelliteController atom = atomArray[0];
        atom.countOfSatelliteServiceEnablementsSuccess
                += stats.countOfSatelliteServiceEnablementsSuccess;
        atom.countOfSatelliteServiceEnablementsFail
                += stats.countOfSatelliteServiceEnablementsFail;
        atom.countOfOutgoingDatagramSuccess
                += stats.countOfOutgoingDatagramSuccess;
        atom.countOfOutgoingDatagramFail
                += stats.countOfOutgoingDatagramFail;
        atom.countOfIncomingDatagramSuccess
                += stats.countOfIncomingDatagramSuccess;
        atom.countOfIncomingDatagramFail
                += stats.countOfIncomingDatagramFail;
        atom.countOfDatagramTypeSosSmsSuccess
                += stats.countOfDatagramTypeSosSmsSuccess;
        atom.countOfDatagramTypeSosSmsFail
                += stats.countOfDatagramTypeSosSmsFail;
        atom.countOfDatagramTypeLocationSharingSuccess
                += stats.countOfDatagramTypeLocationSharingSuccess;
        atom.countOfDatagramTypeLocationSharingFail
                += stats.countOfDatagramTypeLocationSharingFail;
        atom.countOfProvisionSuccess
                += stats.countOfProvisionSuccess;
        atom.countOfProvisionFail
                += stats.countOfProvisionFail;
        atom.countOfDeprovisionSuccess
                += stats.countOfDeprovisionSuccess;
        atom.countOfDeprovisionFail
                += stats.countOfDeprovisionFail;
        atom.totalServiceUptimeSec
                += stats.totalServiceUptimeSec;
        atom.totalBatteryConsumptionPercent
                += stats.totalBatteryConsumptionPercent;
        atom.totalBatteryChargedTimeSec
                += stats.totalBatteryChargedTimeSec;

        mAtoms.satelliteController = atomArray;
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link SatelliteSession} to the storage. */
    public synchronized void addSatelliteSessionStats(SatelliteSession stats) {
        SatelliteSession existingStats = find(stats);
        if (existingStats != null) {
            existingStats.count += 1;
        } else {
            mAtoms.satelliteSession =
                    insertAtRandomPlace(mAtoms.satelliteSession, stats, mMaxNumSatelliteStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link SatelliteIncomingDatagram} to the storage. */
    public synchronized void addSatelliteIncomingDatagramStats(SatelliteIncomingDatagram stats) {
        mAtoms.satelliteIncomingDatagram =
                insertAtRandomPlace(mAtoms.satelliteIncomingDatagram, stats, mMaxNumSatelliteStats);
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link SatelliteOutgoingDatagram} to the storage. */
    public synchronized void addSatelliteOutgoingDatagramStats(SatelliteOutgoingDatagram stats) {
        mAtoms.satelliteOutgoingDatagram =
                insertAtRandomPlace(mAtoms.satelliteOutgoingDatagram, stats, mMaxNumSatelliteStats);
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link SatelliteProvision} to the storage. */
    public synchronized void addSatelliteProvisionStats(SatelliteProvision stats) {
        mAtoms.satelliteProvision =
                insertAtRandomPlace(mAtoms.satelliteProvision, stats, mMaxNumSatelliteStats);
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /** Adds a new {@link SatelliteSosMessageRecommender} to the storage. */
    public synchronized void addSatelliteSosMessageRecommenderStats(
            SatelliteSosMessageRecommender stats) {
        SatelliteSosMessageRecommender existingStats = find(stats);
        if (existingStats != null) {
            existingStats.count += 1;
        } else {
            mAtoms.satelliteSosMessageRecommender =
                    insertAtRandomPlace(mAtoms.satelliteSosMessageRecommender, stats,
                            mMaxNumSatelliteStats);
        }
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_UPDATE_MILLIS);
    }

    /**
     * Returns and clears the voice call sessions if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized VoiceCallSession[] getVoiceCallSessions(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.voiceCallSessionPullTimestampMillis > minIntervalMillis) {
            mAtoms.voiceCallSessionPullTimestampMillis = getWallTimeMillis();
            VoiceCallSession[] previousCalls = mAtoms.voiceCallSession;
            mAtoms.voiceCallSession = new VoiceCallSession[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousCalls;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the voice call RAT usages if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized VoiceCallRatUsage[] getVoiceCallRatUsages(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.voiceCallRatUsagePullTimestampMillis > minIntervalMillis) {
            mAtoms.voiceCallRatUsagePullTimestampMillis = getWallTimeMillis();
            VoiceCallRatUsage[] previousUsages = mAtoms.voiceCallRatUsage;
            mVoiceCallRatTracker.clear();
            mAtoms.voiceCallRatUsage = new VoiceCallRatUsage[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousUsages;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the incoming SMS if last pulled longer than {@code minIntervalMillis} ago,
     * otherwise returns {@code null}.
     */
    @Nullable
    public synchronized IncomingSms[] getIncomingSms(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.incomingSmsPullTimestampMillis > minIntervalMillis) {
            mAtoms.incomingSmsPullTimestampMillis = getWallTimeMillis();
            IncomingSms[] previousIncomingSms = mAtoms.incomingSms;
            mAtoms.incomingSms = new IncomingSms[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousIncomingSms;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the outgoing SMS if last pulled longer than {@code minIntervalMillis} ago,
     * otherwise returns {@code null}.
     */
    @Nullable
    public synchronized OutgoingSms[] getOutgoingSms(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.outgoingSmsPullTimestampMillis > minIntervalMillis) {
            mAtoms.outgoingSmsPullTimestampMillis = getWallTimeMillis();
            OutgoingSms[] previousOutgoingSms = mAtoms.outgoingSms;
            mAtoms.outgoingSms = new OutgoingSms[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousOutgoingSms;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the data call session if last pulled longer than {@code minIntervalMillis}
     * ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized DataCallSession[] getDataCallSessions(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.dataCallSessionPullTimestampMillis > minIntervalMillis) {
            mAtoms.dataCallSessionPullTimestampMillis = getWallTimeMillis();
            DataCallSession[] previousDataCallSession = mAtoms.dataCallSession;
            mAtoms.dataCallSession = new DataCallSession[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            for (DataCallSession dataCallSession : previousDataCallSession) {
                // sort to de-correlate any potential pattern for UII concern
                sortBaseOnArray(dataCallSession.handoverFailureCauses,
                        dataCallSession.handoverFailureRat);
            }
            return previousDataCallSession;
        } else {
            return null;
        }
    }

    /**
     * Sort the other array base on the natural order of the primary array. Both arrays will be
     * sorted in-place.
     * @param primary The primary array to be sorted.
     * @param other The other array to be sorted in the order of primary array.
     */
    private void sortBaseOnArray(int[] primary, int[] other) {
        if (other.length != primary.length) return;
        int[] index = IntStream.range(0, primary.length).boxed()
                .sorted(Comparator.comparingInt(i -> primary[i]))
                .mapToInt(Integer::intValue)
                .toArray();
        int[] primaryCopy = Arrays.copyOf(primary,  primary.length);
        int[] otherCopy = Arrays.copyOf(other,  other.length);
        for (int i = 0; i < index.length; i++) {
            primary[i] = primaryCopy[index[i]];
            other[i] = otherCopy[index[i]];
        }
    }


    /**
     * Returns and clears the service state durations if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized CellularServiceState[] getCellularServiceStates(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.cellularServiceStatePullTimestampMillis
                > minIntervalMillis) {
            mAtoms.cellularServiceStatePullTimestampMillis = getWallTimeMillis();
            CellularServiceState[] previousStates = mAtoms.cellularServiceState;
            Arrays.stream(previousStates).forEach(state -> state.lastUsedMillis = 0L);
            mAtoms.cellularServiceState = new CellularServiceState[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousStates;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the service state durations if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized CellularDataServiceSwitch[] getCellularDataServiceSwitches(
            long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.cellularDataServiceSwitchPullTimestampMillis
                > minIntervalMillis) {
            mAtoms.cellularDataServiceSwitchPullTimestampMillis = getWallTimeMillis();
            CellularDataServiceSwitch[] previousSwitches = mAtoms.cellularDataServiceSwitch;
            Arrays.stream(previousSwitches)
                    .forEach(serviceSwitch -> serviceSwitch.lastUsedMillis = 0L);
            mAtoms.cellularDataServiceSwitch = new CellularDataServiceSwitch[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousSwitches;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the IMS registration statistics normalized to 24h cycle if last
     * pulled longer than {@code minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized ImsRegistrationStats[] getImsRegistrationStats(long minIntervalMillis) {
        long intervalMillis =
                getWallTimeMillis() - mAtoms.imsRegistrationStatsPullTimestampMillis;
        if (intervalMillis > minIntervalMillis) {
            mAtoms.imsRegistrationStatsPullTimestampMillis = getWallTimeMillis();
            ImsRegistrationStats[] previousStats = mAtoms.imsRegistrationStats;
            Arrays.stream(previousStats).forEach(stats -> stats.lastUsedMillis = 0L);
            mAtoms.imsRegistrationStats = new ImsRegistrationStats[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return normalizeData(previousStats, intervalMillis);
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the IMS registration terminations if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized ImsRegistrationTermination[] getImsRegistrationTerminations(
            long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.imsRegistrationTerminationPullTimestampMillis
                > minIntervalMillis) {
            mAtoms.imsRegistrationTerminationPullTimestampMillis = getWallTimeMillis();
            ImsRegistrationTermination[] previousTerminations = mAtoms.imsRegistrationTermination;
            Arrays.stream(previousTerminations)
                    .forEach(termination -> termination.lastUsedMillis = 0L);
            mAtoms.imsRegistrationTermination = new ImsRegistrationTermination[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousTerminations;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the network requests if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized NetworkRequestsV2[] getNetworkRequestsV2(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.networkRequestsV2PullTimestampMillis > minIntervalMillis) {
            mAtoms.networkRequestsV2PullTimestampMillis = getWallTimeMillis();
            NetworkRequestsV2[] previousNetworkRequests = mAtoms.networkRequestsV2;
            mAtoms.networkRequestsV2 = new NetworkRequestsV2[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousNetworkRequests;
        } else {
            return null;
        }
    }

    /** @return the number of times auto data switch mobile data policy is toggled. */
    public synchronized int getAutoDataSwitchToggleCount() {
        int count = mAtoms.autoDataSwitchToggleCount;
        if (count > 0) {
            mAtoms.autoDataSwitchToggleCount = 0;
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
        }
        return count;
    }

    /**
     * Returns and clears the ImsRegistrationFeatureTagStats if last pulled longer than
     * {@code minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized ImsRegistrationFeatureTagStats[] getImsRegistrationFeatureTagStats(
            long minIntervalMillis) {
        long intervalMillis =
                getWallTimeMillis() - mAtoms.rcsAcsProvisioningStatsPullTimestampMillis;
        if (intervalMillis > minIntervalMillis) {
            mAtoms.imsRegistrationFeatureTagStatsPullTimestampMillis = getWallTimeMillis();
            ImsRegistrationFeatureTagStats[] previousStats =
                    mAtoms.imsRegistrationFeatureTagStats;
            mAtoms.imsRegistrationFeatureTagStats = new ImsRegistrationFeatureTagStats[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousStats;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the RcsClientProvisioningStats if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized RcsClientProvisioningStats[] getRcsClientProvisioningStats(
            long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.rcsClientProvisioningStatsPullTimestampMillis
                > minIntervalMillis) {
            mAtoms.rcsClientProvisioningStatsPullTimestampMillis = getWallTimeMillis();
            RcsClientProvisioningStats[] previousStats = mAtoms.rcsClientProvisioningStats;
            mAtoms.rcsClientProvisioningStats = new RcsClientProvisioningStats[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousStats;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the RcsAcsProvisioningStats normalized to 24h cycle if last pulled
     * longer than {@code minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized RcsAcsProvisioningStats[] getRcsAcsProvisioningStats(
            long minIntervalMillis) {
        long intervalMillis =
                getWallTimeMillis() - mAtoms.rcsAcsProvisioningStatsPullTimestampMillis;
        if (intervalMillis > minIntervalMillis) {
            mAtoms.rcsAcsProvisioningStatsPullTimestampMillis = getWallTimeMillis();
            RcsAcsProvisioningStats[] previousStats = mAtoms.rcsAcsProvisioningStats;

            for (RcsAcsProvisioningStats stat: previousStats) {
                // in case pull interval is greater than 24H, normalize it as of one day interval
                if (intervalMillis > DAY_IN_MILLIS) {
                    stat.stateTimerMillis = normalizeDurationTo24H(stat.stateTimerMillis,
                            intervalMillis);
                }
            }

            mAtoms.rcsAcsProvisioningStats = new RcsAcsProvisioningStats[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousStats;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the SipDelegateStats if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized SipDelegateStats[] getSipDelegateStats(long minIntervalMillis) {
        long intervalMillis = getWallTimeMillis() - mAtoms.sipDelegateStatsPullTimestampMillis;
        if (intervalMillis > minIntervalMillis) {
            mAtoms.sipDelegateStatsPullTimestampMillis = getWallTimeMillis();
            SipDelegateStats[] previousStats = mAtoms.sipDelegateStats;

            for (SipDelegateStats stat: previousStats) {
                // in case pull interval is greater than 24H, normalize it as of one day interval
                if (intervalMillis > DAY_IN_MILLIS) {
                    stat.uptimeMillis = normalizeDurationTo24H(stat.uptimeMillis,
                            intervalMillis);
                }
            }

            mAtoms.sipDelegateStats = new SipDelegateStats[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousStats;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the SipTransportFeatureTagStats if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized SipTransportFeatureTagStats[] getSipTransportFeatureTagStats(
            long minIntervalMillis) {
        long intervalMillis =
                getWallTimeMillis() - mAtoms.sipTransportFeatureTagStatsPullTimestampMillis;
        if (intervalMillis > minIntervalMillis) {
            mAtoms.sipTransportFeatureTagStatsPullTimestampMillis = getWallTimeMillis();
            SipTransportFeatureTagStats[] previousStats = mAtoms.sipTransportFeatureTagStats;

            for (SipTransportFeatureTagStats stat: previousStats) {
                // in case pull interval is greater than 24H, normalize it as of one day interval
                if (intervalMillis > DAY_IN_MILLIS) {
                    stat.associatedMillis = normalizeDurationTo24H(stat.associatedMillis,
                            intervalMillis);
                }
            }

            mAtoms.sipTransportFeatureTagStats = new SipTransportFeatureTagStats[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousStats;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the SipMessageResponse if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized SipMessageResponse[] getSipMessageResponse(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.sipMessageResponsePullTimestampMillis
                > minIntervalMillis) {
            mAtoms.sipMessageResponsePullTimestampMillis = getWallTimeMillis();
            SipMessageResponse[] previousStats =
                    mAtoms.sipMessageResponse;
            mAtoms.sipMessageResponse = new SipMessageResponse[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousStats;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the SipTransportSession if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized SipTransportSession[] getSipTransportSession(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.sipTransportSessionPullTimestampMillis
                > minIntervalMillis) {
            mAtoms.sipTransportSessionPullTimestampMillis = getWallTimeMillis();
            SipTransportSession[] previousStats =
                    mAtoms.sipTransportSession;
            mAtoms.sipTransportSession = new SipTransportSession[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousStats;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the ImsDedicatedBearerListenerEvent if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized ImsDedicatedBearerListenerEvent[] getImsDedicatedBearerListenerEvent(
            long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.imsDedicatedBearerListenerEventPullTimestampMillis
                > minIntervalMillis) {
            mAtoms.imsDedicatedBearerListenerEventPullTimestampMillis = getWallTimeMillis();
            ImsDedicatedBearerListenerEvent[] previousStats =
                mAtoms.imsDedicatedBearerListenerEvent;
            mAtoms.imsDedicatedBearerListenerEvent = new ImsDedicatedBearerListenerEvent[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousStats;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the ImsDedicatedBearerEvent if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized ImsDedicatedBearerEvent[] getImsDedicatedBearerEvent(
            long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.imsDedicatedBearerEventPullTimestampMillis
                  > minIntervalMillis) {
            mAtoms.imsDedicatedBearerEventPullTimestampMillis = getWallTimeMillis();
            ImsDedicatedBearerEvent[] previousStats =
                mAtoms.imsDedicatedBearerEvent;
            mAtoms.imsDedicatedBearerEvent = new ImsDedicatedBearerEvent[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousStats;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the ImsRegistrationServiceDescStats if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized ImsRegistrationServiceDescStats[] getImsRegistrationServiceDescStats(long
            minIntervalMillis) {
        long intervalMillis =
                getWallTimeMillis() - mAtoms.imsRegistrationServiceDescStatsPullTimestampMillis;
        if (intervalMillis > minIntervalMillis) {
            mAtoms.imsRegistrationServiceDescStatsPullTimestampMillis = getWallTimeMillis();
            ImsRegistrationServiceDescStats[] previousStats =
                mAtoms.imsRegistrationServiceDescStats;

            for (ImsRegistrationServiceDescStats stat: previousStats) {
                // in case pull interval is greater than 24H, normalize it as of one day interval
                if (intervalMillis > DAY_IN_MILLIS) {
                    stat.publishedMillis = normalizeDurationTo24H(stat.publishedMillis,
                            intervalMillis);
                }
            }

            mAtoms.imsRegistrationServiceDescStats = new ImsRegistrationServiceDescStats[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousStats;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the UceEventStats if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized UceEventStats[] getUceEventStats(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.uceEventStatsPullTimestampMillis > minIntervalMillis) {
            mAtoms.uceEventStatsPullTimestampMillis = getWallTimeMillis();
            UceEventStats[] previousStats = mAtoms.uceEventStats;
            mAtoms.uceEventStats = new UceEventStats[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousStats;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the PresenceNotifyEvent if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized PresenceNotifyEvent[] getPresenceNotifyEvent(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.presenceNotifyEventPullTimestampMillis
                > minIntervalMillis) {
            mAtoms.presenceNotifyEventPullTimestampMillis = getWallTimeMillis();
            PresenceNotifyEvent[] previousStats = mAtoms.presenceNotifyEvent;
            mAtoms.presenceNotifyEvent = new PresenceNotifyEvent[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousStats;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the GbaEvent if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized GbaEvent[] getGbaEvent(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.gbaEventPullTimestampMillis > minIntervalMillis) {
            mAtoms.gbaEventPullTimestampMillis = getWallTimeMillis();
            GbaEvent[] previousStats = mAtoms.gbaEvent;
            mAtoms.gbaEvent = new GbaEvent[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousStats;
        } else {
            return null;
        }
    }

    /**
     *  Returns the unmetered networks bitmask for a given phone id. Returns 0 if there is
     *  no existing UnmeteredNetworks for the given phone id or the carrier id doesn't match.
     *  Existing UnmeteredNetworks is discarded after.
     */
    public synchronized @NetworkTypeBitMask long getUnmeteredNetworks(int phoneId, int carrierId) {
        UnmeteredNetworks existingStats = findUnmeteredNetworks(phoneId);
        if (existingStats == null) {
            return 0L;
        }
        @NetworkTypeBitMask
        long bitmask =
                existingStats.carrierId != carrierId ? 0L : existingStats.unmeteredNetworksBitmask;
        mAtoms.unmeteredNetworks =
                sanitizeAtoms(
                        ArrayUtils.removeElement(
                                UnmeteredNetworks.class,
                                mAtoms.unmeteredNetworks,
                                existingStats),
                        UnmeteredNetworks.class);
        saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
        return bitmask;
    }

    /**
     * Returns and clears the OutgoingShortCodeSms if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized OutgoingShortCodeSms[] getOutgoingShortCodeSms(long minIntervalMillis) {
        if ((getWallTimeMillis() - mAtoms.outgoingShortCodeSmsPullTimestampMillis)
                > minIntervalMillis) {
            mAtoms.outgoingShortCodeSmsPullTimestampMillis = getWallTimeMillis();
            OutgoingShortCodeSms[] previousOutgoingShortCodeSms = mAtoms.outgoingShortCodeSms;
            mAtoms.outgoingShortCodeSms = new OutgoingShortCodeSms[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return previousOutgoingShortCodeSms;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the {@link SatelliteController} stats if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized SatelliteController[] getSatelliteControllerStats(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.satelliteControllerPullTimestampMillis
                > minIntervalMillis) {
            mAtoms.satelliteControllerPullTimestampMillis = getWallTimeMillis();
            SatelliteController[] statsArray = mAtoms.satelliteController;
            mAtoms.satelliteController = new SatelliteController[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return statsArray;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the {@link SatelliteSession} stats if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized SatelliteSession[] getSatelliteSessionStats(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.satelliteSessionPullTimestampMillis
                > minIntervalMillis) {
            mAtoms.satelliteSessionPullTimestampMillis = getWallTimeMillis();
            SatelliteSession[] statsArray = mAtoms.satelliteSession;
            mAtoms.satelliteSession = new SatelliteSession[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return statsArray;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the {@link SatelliteIncomingDatagram} stats if last pulled longer than
     * {@code minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized SatelliteIncomingDatagram[] getSatelliteIncomingDatagramStats(
            long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.satelliteIncomingDatagramPullTimestampMillis
                > minIntervalMillis) {
            mAtoms.satelliteIncomingDatagramPullTimestampMillis = getWallTimeMillis();
            SatelliteIncomingDatagram[] statsArray = mAtoms.satelliteIncomingDatagram;
            mAtoms.satelliteIncomingDatagram = new SatelliteIncomingDatagram[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return statsArray;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the {@link SatelliteOutgoingDatagram} stats if last pulled longer than
     * {@code minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized SatelliteOutgoingDatagram[] getSatelliteOutgoingDatagramStats(
            long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.satelliteOutgoingDatagramPullTimestampMillis
                > minIntervalMillis) {
            mAtoms.satelliteOutgoingDatagramPullTimestampMillis = getWallTimeMillis();
            SatelliteOutgoingDatagram[] statsArray = mAtoms.satelliteOutgoingDatagram;
            mAtoms.satelliteOutgoingDatagram = new SatelliteOutgoingDatagram[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return statsArray;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the {@link SatelliteProvision} stats if last pulled longer than {@code
     * minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized SatelliteProvision[] getSatelliteProvisionStats(long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.satelliteProvisionPullTimestampMillis
                > minIntervalMillis) {
            mAtoms.satelliteProvisionPullTimestampMillis = getWallTimeMillis();
            SatelliteProvision[] statsArray = mAtoms.satelliteProvision;
            mAtoms.satelliteProvision = new SatelliteProvision[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return statsArray;
        } else {
            return null;
        }
    }

    /**
     * Returns and clears the {@link SatelliteSosMessageRecommender} stats if last pulled longer
     * than {@code minIntervalMillis} ago, otherwise returns {@code null}.
     */
    @Nullable
    public synchronized SatelliteSosMessageRecommender[] getSatelliteSosMessageRecommenderStats(
            long minIntervalMillis) {
        if (getWallTimeMillis() - mAtoms.satelliteSosMessageRecommenderPullTimestampMillis
                > minIntervalMillis) {
            mAtoms.satelliteProvisionPullTimestampMillis = getWallTimeMillis();
            SatelliteSosMessageRecommender[] statsArray = mAtoms.satelliteSosMessageRecommender;
            mAtoms.satelliteSosMessageRecommender = new SatelliteSosMessageRecommender[0];
            saveAtomsToFile(SAVE_TO_FILE_DELAY_FOR_GET_MILLIS);
            return statsArray;
        } else {
            return null;
        }
    }

    /** Saves {@link PersistAtoms} to a file in private storage immediately. */
    public synchronized void flushAtoms() {
        saveAtomsToFile(0);
    }

    /** Clears atoms for testing purpose. */
    public synchronized void clearAtoms() {
        mAtoms = makeNewPersistAtoms();
        saveAtomsToFile(0);
    }

    /** Loads {@link PersistAtoms} from a file in private storage. */
    private PersistAtoms loadAtomsFromFile() {
        try {
            PersistAtoms atoms =
                    PersistAtoms.parseFrom(
                            Files.readAllBytes(mContext.getFileStreamPath(FILENAME).toPath()));
            // Start from scratch if build changes, since mixing atoms from different builds could
            // produce strange results
            if (!Build.FINGERPRINT.equals(atoms.buildFingerprint)) {
                Rlog.d(TAG, "Build changed");
                return makeNewPersistAtoms();
            }
            // check all the fields in case of situations such as OTA or crash during saving
            atoms.voiceCallRatUsage =
                    sanitizeAtoms(atoms.voiceCallRatUsage, VoiceCallRatUsage.class);
            atoms.voiceCallSession =
                    sanitizeAtoms(
                            atoms.voiceCallSession,
                            VoiceCallSession.class,
                            mMaxNumVoiceCallSessions);
            atoms.incomingSms = sanitizeAtoms(atoms.incomingSms, IncomingSms.class, mMaxNumSms);
            atoms.outgoingSms = sanitizeAtoms(atoms.outgoingSms, OutgoingSms.class, mMaxNumSms);
            atoms.carrierIdMismatch =
                    sanitizeAtoms(
                            atoms.carrierIdMismatch,
                            CarrierIdMismatch.class,
                            mMaxNumCarrierIdMismatches);
            atoms.dataCallSession =
                    sanitizeAtoms(
                            atoms.dataCallSession,
                            DataCallSession.class,
                            mMaxNumDataCallSessions);
            atoms.cellularServiceState =
                    sanitizeAtoms(
                            atoms.cellularServiceState,
                            CellularServiceState.class,
                            mMaxNumCellularServiceStates);
            atoms.cellularDataServiceSwitch =
                    sanitizeAtoms(
                            atoms.cellularDataServiceSwitch,
                            CellularDataServiceSwitch.class,
                            mMaxNumCellularDataSwitches);
            atoms.imsRegistrationStats =
                    sanitizeAtoms(
                            atoms.imsRegistrationStats,
                            ImsRegistrationStats.class,
                            mMaxNumImsRegistrationStats);
            atoms.imsRegistrationTermination =
                    sanitizeAtoms(
                            atoms.imsRegistrationTermination,
                            ImsRegistrationTermination.class,
                            mMaxNumImsRegistrationTerminations);
            atoms.networkRequestsV2 =
                    sanitizeAtoms(atoms.networkRequestsV2, NetworkRequestsV2.class);
            atoms.imsRegistrationFeatureTagStats =
                    sanitizeAtoms(
                            atoms.imsRegistrationFeatureTagStats,
                            ImsRegistrationFeatureTagStats.class,
                            mMaxNumImsRegistrationFeatureStats);
            atoms.rcsClientProvisioningStats =
                    sanitizeAtoms(
                            atoms.rcsClientProvisioningStats,
                            RcsClientProvisioningStats.class,
                            mMaxNumRcsClientProvisioningStats);
            atoms.rcsAcsProvisioningStats =
                    sanitizeAtoms(
                            atoms.rcsAcsProvisioningStats,
                            RcsAcsProvisioningStats.class,
                            mMaxNumRcsAcsProvisioningStats);
            atoms.sipDelegateStats =
                    sanitizeAtoms(
                            atoms.sipDelegateStats,
                            SipDelegateStats.class,
                            mMaxNumSipDelegateStats);
            atoms.sipTransportFeatureTagStats =
                    sanitizeAtoms(
                            atoms.sipTransportFeatureTagStats,
                            SipTransportFeatureTagStats.class,
                            mMaxNumSipTransportFeatureTagStats);
            atoms.sipMessageResponse =
                    sanitizeAtoms(
                            atoms.sipMessageResponse,
                            SipMessageResponse.class,
                            mMaxNumSipMessageResponseStats);
            atoms.sipTransportSession =
                    sanitizeAtoms(
                            atoms.sipTransportSession,
                            SipTransportSession.class,
                            mMaxNumSipTransportSessionStats);
            atoms.imsDedicatedBearerListenerEvent =
                    sanitizeAtoms(
                            atoms.imsDedicatedBearerListenerEvent,
                            ImsDedicatedBearerListenerEvent.class,
                            mMaxNumDedicatedBearerListenerEventStats);
            atoms.imsDedicatedBearerEvent =
                    sanitizeAtoms(
                            atoms.imsDedicatedBearerEvent,
                            ImsDedicatedBearerEvent.class,
                            mMaxNumDedicatedBearerEventStats);
            atoms.imsRegistrationServiceDescStats =
                    sanitizeAtoms(
                            atoms.imsRegistrationServiceDescStats,
                            ImsRegistrationServiceDescStats.class,
                            mMaxNumImsRegistrationServiceDescStats);
            atoms.uceEventStats =
                    sanitizeAtoms(
                            atoms.uceEventStats,
                            UceEventStats.class,
                            mMaxNumUceEventStats);
            atoms.presenceNotifyEvent =
                    sanitizeAtoms(
                            atoms.presenceNotifyEvent,
                            PresenceNotifyEvent.class,
                            mMaxNumPresenceNotifyEventStats);
            atoms.gbaEvent =
                    sanitizeAtoms(
                            atoms.gbaEvent,
                            GbaEvent.class,
                            mMaxNumGbaEventStats);
            atoms.unmeteredNetworks =
                    sanitizeAtoms(
                            atoms.unmeteredNetworks,
                            UnmeteredNetworks.class
                    );
            atoms.outgoingShortCodeSms = sanitizeAtoms(atoms.outgoingShortCodeSms,
                    OutgoingShortCodeSms.class, mMaxOutgoingShortCodeSms);
            atoms.satelliteController = sanitizeAtoms(atoms.satelliteController,
                            SatelliteController.class, mMaxNumSatelliteControllerStats);
            atoms.satelliteSession = sanitizeAtoms(atoms.satelliteSession,
                    SatelliteSession.class, mMaxNumSatelliteStats);
            atoms.satelliteIncomingDatagram = sanitizeAtoms(atoms.satelliteIncomingDatagram,
                            SatelliteIncomingDatagram.class, mMaxNumSatelliteStats);
            atoms.satelliteOutgoingDatagram = sanitizeAtoms(atoms.satelliteOutgoingDatagram,
                            SatelliteOutgoingDatagram.class, mMaxNumSatelliteStats);
            atoms.satelliteProvision = sanitizeAtoms(atoms.satelliteProvision,
                            SatelliteProvision.class, mMaxNumSatelliteStats);
            atoms.satelliteSosMessageRecommender = sanitizeAtoms(
                    atoms.satelliteSosMessageRecommender, SatelliteSosMessageRecommender.class,
                    mMaxNumSatelliteStats);

            // out of caution, sanitize also the timestamps
            atoms.voiceCallRatUsagePullTimestampMillis =
                    sanitizeTimestamp(atoms.voiceCallRatUsagePullTimestampMillis);
            atoms.voiceCallSessionPullTimestampMillis =
                    sanitizeTimestamp(atoms.voiceCallSessionPullTimestampMillis);
            atoms.incomingSmsPullTimestampMillis =
                    sanitizeTimestamp(atoms.incomingSmsPullTimestampMillis);
            atoms.outgoingSmsPullTimestampMillis =
                    sanitizeTimestamp(atoms.outgoingSmsPullTimestampMillis);
            atoms.dataCallSessionPullTimestampMillis =
                    sanitizeTimestamp(atoms.dataCallSessionPullTimestampMillis);
            atoms.cellularServiceStatePullTimestampMillis =
                    sanitizeTimestamp(atoms.cellularServiceStatePullTimestampMillis);
            atoms.cellularDataServiceSwitchPullTimestampMillis =
                    sanitizeTimestamp(atoms.cellularDataServiceSwitchPullTimestampMillis);
            atoms.imsRegistrationStatsPullTimestampMillis =
                    sanitizeTimestamp(atoms.imsRegistrationStatsPullTimestampMillis);
            atoms.imsRegistrationTerminationPullTimestampMillis =
                    sanitizeTimestamp(atoms.imsRegistrationTerminationPullTimestampMillis);
            atoms.networkRequestsV2PullTimestampMillis =
                    sanitizeTimestamp(atoms.networkRequestsV2PullTimestampMillis);
            atoms.imsRegistrationFeatureTagStatsPullTimestampMillis =
                    sanitizeTimestamp(atoms.imsRegistrationFeatureTagStatsPullTimestampMillis);
            atoms.rcsClientProvisioningStatsPullTimestampMillis =
                    sanitizeTimestamp(atoms.rcsClientProvisioningStatsPullTimestampMillis);
            atoms.rcsAcsProvisioningStatsPullTimestampMillis =
                    sanitizeTimestamp(atoms.rcsAcsProvisioningStatsPullTimestampMillis);
            atoms.sipDelegateStatsPullTimestampMillis =
                    sanitizeTimestamp(atoms.sipDelegateStatsPullTimestampMillis);
            atoms.sipTransportFeatureTagStatsPullTimestampMillis =
                    sanitizeTimestamp(atoms.sipTransportFeatureTagStatsPullTimestampMillis);
            atoms.sipMessageResponsePullTimestampMillis =
                    sanitizeTimestamp(atoms.sipMessageResponsePullTimestampMillis);
            atoms.sipTransportSessionPullTimestampMillis =
                    sanitizeTimestamp(atoms.sipTransportSessionPullTimestampMillis);
            atoms.imsDedicatedBearerListenerEventPullTimestampMillis =
                    sanitizeTimestamp(atoms.imsDedicatedBearerListenerEventPullTimestampMillis);
            atoms.imsDedicatedBearerEventPullTimestampMillis =
                    sanitizeTimestamp(atoms.imsDedicatedBearerEventPullTimestampMillis);
            atoms.imsRegistrationServiceDescStatsPullTimestampMillis =
                    sanitizeTimestamp(atoms.imsRegistrationServiceDescStatsPullTimestampMillis);
            atoms.uceEventStatsPullTimestampMillis =
                    sanitizeTimestamp(atoms.uceEventStatsPullTimestampMillis);
            atoms.presenceNotifyEventPullTimestampMillis =
                    sanitizeTimestamp(atoms.presenceNotifyEventPullTimestampMillis);
            atoms.gbaEventPullTimestampMillis =
                    sanitizeTimestamp(atoms.gbaEventPullTimestampMillis);
            atoms.outgoingShortCodeSmsPullTimestampMillis =
                    sanitizeTimestamp(atoms.outgoingShortCodeSmsPullTimestampMillis);
            atoms.satelliteControllerPullTimestampMillis =
                    sanitizeTimestamp(atoms.satelliteControllerPullTimestampMillis);
            atoms.satelliteSessionPullTimestampMillis =
                    sanitizeTimestamp(atoms.satelliteSessionPullTimestampMillis);
            atoms.satelliteIncomingDatagramPullTimestampMillis =
                    sanitizeTimestamp(atoms.satelliteIncomingDatagramPullTimestampMillis);
            atoms.satelliteOutgoingDatagramPullTimestampMillis =
                    sanitizeTimestamp(atoms.satelliteOutgoingDatagramPullTimestampMillis);
            atoms.satelliteProvisionPullTimestampMillis =
                    sanitizeTimestamp(atoms.satelliteProvisionPullTimestampMillis);
            atoms.satelliteSosMessageRecommenderPullTimestampMillis =
                    sanitizeTimestamp(atoms.satelliteSosMessageRecommenderPullTimestampMillis);
            return atoms;
        } catch (NoSuchFileException e) {
            Rlog.d(TAG, "PersistAtoms file not found");
        } catch (IOException | NullPointerException e) {
            Rlog.e(TAG, "cannot load/parse PersistAtoms", e);
        }
        return makeNewPersistAtoms();
    }

    /**
     * Posts message to save a copy of {@link PersistAtoms} to a file after a delay or immediately.
     *
     * <p>The delay is introduced to avoid too frequent operations to disk, which would negatively
     * impact the power consumption.
     */
    private synchronized void saveAtomsToFile(int delayMillis) {
        mHandler.removeCallbacks(mSaveRunnable);
        if (delayMillis > 0 && !mSaveImmediately) {
            if (mHandler.postDelayed(mSaveRunnable, delayMillis)) {
                return;
            }
        }
        // In case of error posting the event or if delay is 0, save immediately
        saveAtomsToFileNow();
    }

    /** Saves a copy of {@link PersistAtoms} to a file in private storage. */
    private synchronized void saveAtomsToFileNow() {
        try (FileOutputStream stream = mContext.openFileOutput(FILENAME, Context.MODE_PRIVATE)) {
            stream.write(PersistAtoms.toByteArray(mAtoms));
        } catch (IOException e) {
            Rlog.e(TAG, "cannot save PersistAtoms", e);
        }
    }

    /**
     * Returns the service state that has the same dimension values with the given one, or {@code
     * null} if it does not exist.
     */
    private @Nullable CellularServiceState find(CellularServiceState key) {
        for (CellularServiceState state : mAtoms.cellularServiceState) {
            if (state.voiceRat == key.voiceRat
                    && state.dataRat == key.dataRat
                    && state.voiceRoamingType == key.voiceRoamingType
                    && state.dataRoamingType == key.dataRoamingType
                    && state.isEndc == key.isEndc
                    && state.simSlotIndex == key.simSlotIndex
                    && state.isMultiSim == key.isMultiSim
                    && state.carrierId == key.carrierId
                    && state.isEmergencyOnly == key.isEmergencyOnly
                    && state.isInternetPdnUp == key.isInternetPdnUp) {
                return state;
            }
        }
        return null;
    }

    /**
     * Returns the data service switch that has the same dimension values with the given one, or
     * {@code null} if it does not exist.
     */
    private @Nullable CellularDataServiceSwitch find(CellularDataServiceSwitch key) {
        for (CellularDataServiceSwitch serviceSwitch : mAtoms.cellularDataServiceSwitch) {
            if (serviceSwitch.ratFrom == key.ratFrom
                    && serviceSwitch.ratTo == key.ratTo
                    && serviceSwitch.simSlotIndex == key.simSlotIndex
                    && serviceSwitch.isMultiSim == key.isMultiSim
                    && serviceSwitch.carrierId == key.carrierId) {
                return serviceSwitch;
            }
        }
        return null;
    }

    /**
     * Returns the carrier ID mismatch event that has the same dimension values with the given one,
     * or {@code null} if it does not exist.
     */
    private @Nullable CarrierIdMismatch find(CarrierIdMismatch key) {
        for (CarrierIdMismatch mismatch : mAtoms.carrierIdMismatch) {
            if (mismatch.mccMnc.equals(key.mccMnc)
                    && mismatch.gid1.equals(key.gid1)
                    && mismatch.spn.equals(key.spn)
                    && mismatch.pnn.equals(key.pnn)) {
                return mismatch;
            }
        }
        return null;
    }

    /**
     * Returns the IMS registration stats that has the same dimension values with the given one, or
     * {@code null} if it does not exist.
     */
    private @Nullable ImsRegistrationStats find(ImsRegistrationStats key) {
        for (ImsRegistrationStats stats : mAtoms.imsRegistrationStats) {
            if (stats.carrierId == key.carrierId
                    && stats.simSlotIndex == key.simSlotIndex
                    && stats.rat == key.rat) {
                return stats;
            }
        }
        return null;
    }

    /**
     * Returns the IMS registration termination that has the same dimension values with the given
     * one, or {@code null} if it does not exist.
     */
    private @Nullable ImsRegistrationTermination find(ImsRegistrationTermination key) {
        for (ImsRegistrationTermination termination : mAtoms.imsRegistrationTermination) {
            if (termination.carrierId == key.carrierId
                    && termination.isMultiSim == key.isMultiSim
                    && termination.ratAtEnd == key.ratAtEnd
                    && termination.setupFailed == key.setupFailed
                    && termination.reasonCode == key.reasonCode
                    && termination.extraCode == key.extraCode
                    && termination.extraMessage.equals(key.extraMessage)) {
                return termination;
            }
        }
        return null;
    }

    /**
     * Returns the network requests event that has the same carrier id and capability as the given
     * one, or {@code null} if it does not exist.
     */
    private @Nullable NetworkRequestsV2 find(NetworkRequestsV2 key) {
        for (NetworkRequestsV2 item : mAtoms.networkRequestsV2) {
            if (item.carrierId == key.carrierId && item.capability == key.capability) {
                return item;
            }
        }
        return null;
    }

    /**
     * Returns the index of data call session that has the same random dimension as the given one,
     * or -1 if it does not exist.
     */
    private int findIndex(DataCallSession key) {
        for (int i = 0; i < mAtoms.dataCallSession.length; i++) {
            if (mAtoms.dataCallSession[i].dimension == key.dimension) {
                return i;
            }
        }
        return -1;
    }
    /**
     * Returns the Dedicated Bearer Listener event that has the same carrier id, slot id, rat, qci
     * and established state as the given one, or {@code null} if it does not exist.
     */
    private @Nullable ImsDedicatedBearerListenerEvent find(ImsDedicatedBearerListenerEvent key) {
        for (ImsDedicatedBearerListenerEvent stats : mAtoms.imsDedicatedBearerListenerEvent) {
            if (stats.carrierId == key.carrierId
                    && stats.slotId == key.slotId
                    && stats.ratAtEnd == key.ratAtEnd
                    && stats.qci == key.qci
                    && stats.dedicatedBearerEstablished == key.dedicatedBearerEstablished) {
                return stats;
            }
        }
        return null;
    }

    /**
     * Returns the Dedicated Bearer event that has the same carrier id, slot id, rat,
     * qci, bearer state, local/remote connection and exsting listener as the given one,
     * or {@code null} if it does not exist.
     */
    private @Nullable ImsDedicatedBearerEvent find(ImsDedicatedBearerEvent key) {
        for (ImsDedicatedBearerEvent stats : mAtoms.imsDedicatedBearerEvent) {
            if (stats.carrierId == key.carrierId
                    && stats.slotId == key.slotId
                    && stats.ratAtEnd == key.ratAtEnd
                    && stats.qci == key.qci
                    && stats.bearerState == key.bearerState
                    && stats.localConnectionInfoReceived == key.localConnectionInfoReceived
                    && stats.remoteConnectionInfoReceived == key.remoteConnectionInfoReceived
                    && stats.hasListeners == key.hasListeners) {
                return stats;
            }
        }
        return null;
    }

    /**
     * Returns the Registration Feature Tag that has the same carrier id, slot id,
     * feature tag name or custom feature tag name and registration tech as the given one,
     * or {@code null} if it does not exist.
     */
    private @Nullable ImsRegistrationFeatureTagStats find(ImsRegistrationFeatureTagStats key) {
        for (ImsRegistrationFeatureTagStats stats : mAtoms.imsRegistrationFeatureTagStats) {
            if (stats.carrierId == key.carrierId
                    && stats.slotId == key.slotId
                    && stats.featureTagName == key.featureTagName
                    && stats.registrationTech == key.registrationTech) {
                return stats;
            }
        }
        return null;
    }

    /**
     * Returns Client Provisioning that has the same carrier id, slot id and event as the given
     * one, or {@code null} if it does not exist.
     */
    private @Nullable RcsClientProvisioningStats find(RcsClientProvisioningStats key) {
        for (RcsClientProvisioningStats stats : mAtoms.rcsClientProvisioningStats) {
            if (stats.carrierId == key.carrierId
                    && stats.slotId == key.slotId
                    && stats.event == key.event) {
                return stats;
            }
        }
        return null;
    }

    /**
     * Returns ACS Provisioning that has the same carrier id, slot id, response code, response type
     * and SR supported as the given one, or {@code null} if it does not exist.
     */
    private @Nullable RcsAcsProvisioningStats find(RcsAcsProvisioningStats key) {
        for (RcsAcsProvisioningStats stats : mAtoms.rcsAcsProvisioningStats) {
            if (stats.carrierId == key.carrierId
                    && stats.slotId == key.slotId
                    && stats.responseCode == key.responseCode
                    && stats.responseType == key.responseType
                    && stats.isSingleRegistrationEnabled == key.isSingleRegistrationEnabled) {
                return stats;
            }
        }
        return null;
    }

    /**
     * Returns Sip Message Response that has the same carrier id, slot id, method, response,
     * direction and error as the given one, or {@code null} if it does not exist.
     */
    private @Nullable SipMessageResponse find(SipMessageResponse key) {
        for (SipMessageResponse stats : mAtoms.sipMessageResponse) {
            if (stats.carrierId == key.carrierId
                    && stats.slotId == key.slotId
                    && stats.sipMessageMethod == key.sipMessageMethod
                    && stats.sipMessageResponse == key.sipMessageResponse
                    && stats.sipMessageDirection == key.sipMessageDirection
                    && stats.messageError == key.messageError) {
                return stats;
            }
        }
        return null;
    }

    /**
     * Returns Sip Transport Session that has the same carrier id, slot id, method, direction and
     * response as the given one, or {@code null} if it does not exist.
     */
    private @Nullable SipTransportSession find(SipTransportSession key) {
        for (SipTransportSession stats : mAtoms.sipTransportSession) {
            if (stats.carrierId == key.carrierId
                    && stats.slotId == key.slotId
                    && stats.sessionMethod == key.sessionMethod
                    && stats.sipMessageDirection == key.sipMessageDirection
                    && stats.sipResponse == key.sipResponse) {
                return stats;
            }
        }
        return null;
    }

    /**
     * Returns Registration Service Desc Stats that has the same carrier id, slot id, service id or
     * custom service id, service id version and registration tech as the given one,
     * or {@code null} if it does not exist.
     */
    private @Nullable ImsRegistrationServiceDescStats find(ImsRegistrationServiceDescStats key) {
        for (ImsRegistrationServiceDescStats stats : mAtoms.imsRegistrationServiceDescStats) {
            if (stats.carrierId == key.carrierId
                    && stats.slotId == key.slotId
                    && stats.serviceIdName == key.serviceIdName
                    && stats.serviceIdVersion == key.serviceIdVersion
                    && stats.registrationTech == key.registrationTech) {
                return stats;
            }
        }
        return null;
    }

    /**
     * Returns UCE Event Stats that has the same carrier id, slot id, event result, command code and
     * network response as the given one, or {@code null} if it does not exist.
     */
    private @Nullable UceEventStats find(UceEventStats key) {
        for (UceEventStats stats : mAtoms.uceEventStats) {
            if (stats.carrierId == key.carrierId
                    && stats.slotId == key.slotId
                    && stats.type == key.type
                    && stats.successful == key.successful
                    && stats.commandCode == key.commandCode
                    && stats.networkResponse == key.networkResponse) {
                return stats;
            }
        }
        return null;
    }

    /**
     * Returns Presence Notify Event that has the same carrier id, slot id, reason and body in
     * response as the given one, or {@code null} if it does not exist.
     */
    private @Nullable PresenceNotifyEvent find(PresenceNotifyEvent key) {
        for (PresenceNotifyEvent stats : mAtoms.presenceNotifyEvent) {
            if (stats.carrierId == key.carrierId
                    && stats.slotId == key.slotId
                    && stats.reason == key.reason
                    && stats.contentBodyReceived == key.contentBodyReceived) {
                return stats;
            }
        }
        return null;
    }

    /**
     * Returns GBA Event that has the same carrier id, slot id, result of operation and fail reason
     * as the given one, or {@code null} if it does not exist.
     */
    private @Nullable GbaEvent find(GbaEvent key) {
        for (GbaEvent stats : mAtoms.gbaEvent) {
            if (stats.carrierId == key.carrierId
                    && stats.slotId == key.slotId
                    && stats.successful == key.successful
                    && stats.failedReason == key.failedReason) {
                return stats;
            }
        }
        return null;
    }

    /**
     * Returns Sip Transport Feature Tag Stats that has the same carrier id, slot id, feature tag
     * name, deregister reason, denied reason and feature tag name or custom feature tag name as
     * the given one, or {@code null} if it does not exist.
     */
    private @Nullable SipTransportFeatureTagStats find(SipTransportFeatureTagStats key) {
        for (SipTransportFeatureTagStats stat : mAtoms.sipTransportFeatureTagStats) {
            if (stat.carrierId == key.carrierId
                    && stat.slotId == key.slotId
                    && stat.featureTagName == key.featureTagName
                    && stat.sipTransportDeregisteredReason == key.sipTransportDeregisteredReason
                    && stat.sipTransportDeniedReason == key.sipTransportDeniedReason) {
                return stat;
            }
        }
        return null;
    }

    /** Returns the UnmeteredNetworks given a phone id. */
    private @Nullable UnmeteredNetworks findUnmeteredNetworks(int phoneId) {
        for (UnmeteredNetworks unmeteredNetworks : mAtoms.unmeteredNetworks) {
            if (unmeteredNetworks.phoneId == phoneId) {
                return unmeteredNetworks;
            }
        }
        return null;
    }

    /**
     * Returns OutgoingShortCodeSms atom that has same category, xmlVersion as the given one,
     * or {@code null} if it does not exist.
     */
    private @Nullable OutgoingShortCodeSms find(OutgoingShortCodeSms key) {
        for (OutgoingShortCodeSms shortCodeSms : mAtoms.outgoingShortCodeSms) {
            if (shortCodeSms.category == key.category
                    && shortCodeSms.xmlVersion == key.xmlVersion) {
                return shortCodeSms;
            }
        }
        return null;
    }

    /**
     * Returns SatelliteOutgoingDatagram atom that has same values or {@code null}
     * if it does not exist.
     */
    private @Nullable SatelliteSession find(
            SatelliteSession key) {
        for (SatelliteSession stats : mAtoms.satelliteSession) {
            if (stats.satelliteServiceInitializationResult
                    == key.satelliteServiceInitializationResult
                    && stats.satelliteTechnology == key.satelliteTechnology) {
                return stats;
            }
        }
        return null;
    }

    /**
     * Returns SatelliteOutgoingDatagram atom that has same values or {@code null}
     * if it does not exist.
     */
    private @Nullable SatelliteSosMessageRecommender find(
            SatelliteSosMessageRecommender key) {
        for (SatelliteSosMessageRecommender stats : mAtoms.satelliteSosMessageRecommender) {
            if (stats.isDisplaySosMessageSent == key.isDisplaySosMessageSent
                    && stats.countOfTimerStarted == key.countOfTimerStarted
                    && stats.isImsRegistered == key.isImsRegistered
                    && stats.cellularServiceState == key.cellularServiceState) {
                return stats;
            }
        }
        return null;
    }

    /**
     * Inserts a new element in a random position in an array with a maximum size.
     *
     * <p>If the array is full, merge with existing item if possible or replace one item randomly.
     */
    private static <T> T[] insertAtRandomPlace(T[] storage, T instance, int maxLength) {
        final int newLength = storage.length + 1;
        final boolean arrayFull = (newLength > maxLength);
        T[] result = Arrays.copyOf(storage, arrayFull ? maxLength : newLength);
        if (newLength == 1) {
            result[0] = instance;
        } else if (arrayFull) {
            if (instance instanceof OutgoingSms || instance instanceof IncomingSms) {
                mergeSmsOrEvictInFullStorage(result, instance);
            } else {
                result[findItemToEvict(storage)] = instance;
            }
        } else {
            // insert at random place (by moving the item at the random place to the end)
            int insertAt = sRandom.nextInt(newLength);
            result[newLength - 1] = result[insertAt];
            result[insertAt] = instance;
        }
        return result;
    }

    /**
     * Merge new sms in a full storage.
     *
     * <p>If new sms is similar to old sms, merge them.
     * If not, merge 2 old similar sms and add the new sms.
     * If not, replace old sms with the lowest count.
     */
    private static <T> void mergeSmsOrEvictInFullStorage(T[] storage, T instance) {
        // key: hashCode, value: smsIndex
        SparseIntArray map = new SparseIntArray();
        int smsIndex1 = -1;
        int smsIndex2 = -1;
        int indexLowestCount = -1;
        int minCount = Integer.MAX_VALUE;

        for (int i = 0; i < storage.length; i++) {
            // If the new SMS can be merged to an existing item, merge it and return immediately.
            if (areSmsMergeable(storage[i], instance)) {
                storage[i] = mergeSms(storage[i], instance);
                return;
            }

            // Keep sms index with lowest count to evict, in case we cannot merge any 2 messages.
            int smsCount = getSmsCount(storage[i]);
            if (smsCount < minCount) {
                indexLowestCount = i;
                minCount = smsCount;
            }

            // Find any 2 messages in the storage that can be merged together.
            if (smsIndex1 != -1) {
                int smsHashCode = getSmsHashCode(storage[i]);
                if (map.indexOfKey(smsHashCode) < 0) {
                    map.append(smsHashCode, i);
                } else {
                    smsIndex1 = map.get(smsHashCode);
                    smsIndex2 = i;
                }
            }
        }

        // Merge 2 similar old sms and add the new sms
        if (smsIndex1 != -1) {
            storage[smsIndex1] = mergeSms(storage[smsIndex1], storage[smsIndex2]);
            storage[smsIndex2] = instance;
            return;
        }

        // Or replace old sms that has the lowest count
        storage[indexLowestCount] = instance;
        return;
    }

    private static <T> int getSmsHashCode(T sms) {
        return sms instanceof OutgoingSms
                ? ((OutgoingSms) sms).hashCode : ((IncomingSms) sms).hashCode;
    }

    private static <T> int getSmsCount(T sms) {
        return sms instanceof OutgoingSms
                ? ((OutgoingSms) sms).count : ((IncomingSms) sms).count;
    }

    /** Compares 2 SMS hash codes to check if they can be clubbed together in the metrics. */
    private static <T> boolean areSmsMergeable(T instance1, T instance2) {
        return getSmsHashCode(instance1) == getSmsHashCode(instance2);
    }

    /** Merges sms2 data on top of sms1 and returns the merged value. */
    private static <T> T mergeSms(T sms1, T sms2) {
        if (sms1 instanceof OutgoingSms) {
            OutgoingSms tSms1 = (OutgoingSms) sms1;
            OutgoingSms tSms2 = (OutgoingSms) sms2;
            tSms1.intervalMillis = (tSms1.intervalMillis * tSms1.count
                    + tSms2.intervalMillis * tSms2.count) / (tSms1.count + tSms2.count);
            tSms1.count += tSms2.count;
        } else if (sms1 instanceof IncomingSms) {
            IncomingSms tSms1 = (IncomingSms) sms1;
            IncomingSms tSms2 = (IncomingSms) sms2;
            tSms1.count += tSms2.count;
        }
        return sms1;
    }

    /** Returns index of the item suitable for eviction when the array is full. */
    private static <T> int findItemToEvict(T[] array) {
        if (array instanceof CellularServiceState[]) {
            // Evict the item that was used least recently
            CellularServiceState[] arr = (CellularServiceState[]) array;
            return IntStream.range(0, arr.length)
                    .reduce((i, j) -> arr[i].lastUsedMillis < arr[j].lastUsedMillis ? i : j)
                    .getAsInt();
        }

        if (array instanceof CellularDataServiceSwitch[]) {
            // Evict the item that was used least recently
            CellularDataServiceSwitch[] arr = (CellularDataServiceSwitch[]) array;
            return IntStream.range(0, arr.length)
                    .reduce((i, j) -> arr[i].lastUsedMillis < arr[j].lastUsedMillis ? i : j)
                    .getAsInt();
        }

        if (array instanceof ImsRegistrationStats[]) {
            // Evict the item that was used least recently
            ImsRegistrationStats[] arr = (ImsRegistrationStats[]) array;
            return IntStream.range(0, arr.length)
                    .reduce((i, j) -> arr[i].lastUsedMillis < arr[j].lastUsedMillis ? i : j)
                    .getAsInt();
        }

        if (array instanceof ImsRegistrationTermination[]) {
            // Evict the item that was used least recently
            ImsRegistrationTermination[] arr = (ImsRegistrationTermination[]) array;
            return IntStream.range(0, arr.length)
                    .reduce((i, j) -> arr[i].lastUsedMillis < arr[j].lastUsedMillis ? i : j)
                    .getAsInt();
        }

        if (array instanceof VoiceCallSession[]) {
            // For voice calls, try to keep emergency calls over regular calls.
            VoiceCallSession[] arr = (VoiceCallSession[]) array;
            int[] nonEmergencyCallIndexes = IntStream.range(0, arr.length)
                    .filter(i -> !arr[i].isEmergency)
                    .toArray();
            if (nonEmergencyCallIndexes.length > 0) {
                return nonEmergencyCallIndexes[sRandom.nextInt(nonEmergencyCallIndexes.length)];
            }
            // If all calls in the storage are emergency calls, proceed with default case
            // even if the new call is not an emergency call.
        }

        return sRandom.nextInt(array.length);
    }

    /** Sanitizes the loaded array of atoms to avoid null values. */
    private <T> T[] sanitizeAtoms(T[] array, Class<T> cl) {
        return ArrayUtils.emptyIfNull(array, cl);
    }

    /** Sanitizes the loaded array of atoms loaded to avoid null values and enforce max length. */
    private <T> T[] sanitizeAtoms(T[] array, Class<T> cl, int maxLength) {
        array = sanitizeAtoms(array, cl);
        if (array.length > maxLength) {
            return Arrays.copyOf(array, maxLength);
        }
        return array;
    }

    /** Sanitizes the timestamp of the last pull loaded from persistent storage. */
    private long sanitizeTimestamp(long timestamp) {
        return timestamp <= 0L ? getWallTimeMillis() : timestamp;
    }

    /**
     * Returns {@link ImsRegistrationStats} array with durations normalized to 24 hours
     * depending on the interval.
     */
    private ImsRegistrationStats[] normalizeData(ImsRegistrationStats[] stats,
            long intervalMillis) {
        for (int i = 0; i < stats.length; i++) {
            stats[i].registeredMillis =
                    normalizeDurationTo24H(stats[i].registeredMillis, intervalMillis);
            stats[i].voiceCapableMillis =
                    normalizeDurationTo24H(stats[i].voiceCapableMillis, intervalMillis);
            stats[i].voiceAvailableMillis =
                    normalizeDurationTo24H(stats[i].voiceAvailableMillis, intervalMillis);
            stats[i].smsCapableMillis =
                    normalizeDurationTo24H(stats[i].smsCapableMillis, intervalMillis);
            stats[i].smsAvailableMillis =
                    normalizeDurationTo24H(stats[i].smsAvailableMillis, intervalMillis);
            stats[i].videoCapableMillis =
                    normalizeDurationTo24H(stats[i].videoCapableMillis, intervalMillis);
            stats[i].videoAvailableMillis =
                    normalizeDurationTo24H(stats[i].videoAvailableMillis, intervalMillis);
            stats[i].utCapableMillis =
                    normalizeDurationTo24H(stats[i].utCapableMillis, intervalMillis);
            stats[i].utAvailableMillis =
                    normalizeDurationTo24H(stats[i].utAvailableMillis, intervalMillis);
        }
        return stats;
    }

    /** Returns a duration normalized to 24 hours. */
    private long normalizeDurationTo24H(long timeInMillis, long intervalMillis) {
        long interval = intervalMillis < 1000 ? 1 : intervalMillis / 1000;
        return ((timeInMillis / 1000) * (DAY_IN_MILLIS / 1000) / interval) * 1000;
    }

    /** Returns an empty PersistAtoms with pull timestamp set to current time. */
    private PersistAtoms makeNewPersistAtoms() {
        PersistAtoms atoms = new PersistAtoms();
        // allow pulling only after some time so data are sufficiently aggregated
        long currentTime = getWallTimeMillis();
        atoms.buildFingerprint = Build.FINGERPRINT;
        atoms.voiceCallRatUsagePullTimestampMillis = currentTime;
        atoms.voiceCallSessionPullTimestampMillis = currentTime;
        atoms.incomingSmsPullTimestampMillis = currentTime;
        atoms.outgoingSmsPullTimestampMillis = currentTime;
        atoms.carrierIdTableVersion = TelephonyManager.UNKNOWN_CARRIER_ID_LIST_VERSION;
        atoms.dataCallSessionPullTimestampMillis = currentTime;
        atoms.cellularServiceStatePullTimestampMillis = currentTime;
        atoms.cellularDataServiceSwitchPullTimestampMillis = currentTime;
        atoms.imsRegistrationStatsPullTimestampMillis = currentTime;
        atoms.imsRegistrationTerminationPullTimestampMillis = currentTime;
        atoms.networkRequestsPullTimestampMillis = currentTime;
        atoms.networkRequestsV2PullTimestampMillis = currentTime;
        atoms.imsRegistrationFeatureTagStatsPullTimestampMillis = currentTime;
        atoms.rcsClientProvisioningStatsPullTimestampMillis = currentTime;
        atoms.rcsAcsProvisioningStatsPullTimestampMillis = currentTime;
        atoms.sipDelegateStatsPullTimestampMillis = currentTime;
        atoms.sipTransportFeatureTagStatsPullTimestampMillis = currentTime;
        atoms.sipMessageResponsePullTimestampMillis = currentTime;
        atoms.sipTransportSessionPullTimestampMillis = currentTime;
        atoms.imsDedicatedBearerListenerEventPullTimestampMillis = currentTime;
        atoms.imsDedicatedBearerEventPullTimestampMillis = currentTime;
        atoms.imsRegistrationServiceDescStatsPullTimestampMillis = currentTime;
        atoms.uceEventStatsPullTimestampMillis = currentTime;
        atoms.presenceNotifyEventPullTimestampMillis = currentTime;
        atoms.gbaEventPullTimestampMillis = currentTime;
        atoms.outgoingShortCodeSmsPullTimestampMillis = currentTime;
        atoms.satelliteControllerPullTimestampMillis = currentTime;
        atoms.satelliteSessionPullTimestampMillis = currentTime;
        atoms.satelliteIncomingDatagramPullTimestampMillis = currentTime;
        atoms.satelliteOutgoingDatagramPullTimestampMillis = currentTime;
        atoms.satelliteProvisionPullTimestampMillis = currentTime;
        atoms.satelliteSosMessageRecommenderPullTimestampMillis = currentTime;

        Rlog.d(TAG, "created new PersistAtoms");
        return atoms;
    }

    @VisibleForTesting
    protected long getWallTimeMillis() {
        // Epoch time in UTC, preserved across reboots, but can be adjusted e.g. by the user or NTP
        return System.currentTimeMillis();
    }
}