aboutsummaryrefslogtreecommitdiff
path: root/shadows/framework/src/main/java/org/robolectric/shadows/ShadowLocationManager.java
blob: 9cbf5eefab4798a274fe2511681f2c61df3f91f4 (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
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
package org.robolectric.shadows;

import static android.location.LocationManager.GPS_PROVIDER;
import static android.location.LocationManager.NETWORK_PROVIDER;
import static android.location.LocationManager.PASSIVE_PROVIDER;
import static android.os.Build.VERSION_CODES.P;
import static android.provider.Settings.Secure.LOCATION_MODE;
import static android.provider.Settings.Secure.LOCATION_MODE_BATTERY_SAVING;
import static android.provider.Settings.Secure.LOCATION_MODE_HIGH_ACCURACY;
import static android.provider.Settings.Secure.LOCATION_MODE_OFF;
import static android.provider.Settings.Secure.LOCATION_MODE_SENSORS_ONLY;
import static android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED;
import static java.util.concurrent.TimeUnit.NANOSECONDS;

import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.GnssAntennaInfo;
import android.location.GnssMeasurementsEvent;
import android.location.GnssStatus;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.location.LocationRequest;
import android.location.OnNmeaMessageListener;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.os.SystemClock;
import android.os.UserHandle;
import android.os.WorkSource;
import android.provider.Settings.Secure;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.GuardedBy;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Consumer;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.annotation.Resetter;
import org.robolectric.shadows.ShadowSettings.ShadowSecure;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.ReflectionHelpers.ClassParameter;

/**
 * Shadow for {@link LocationManager}. Note that the default state of location on Android devices is
 * location on, gps provider enabled, network provider disabled.
 */
@SuppressWarnings("deprecation")
@Implements(value = LocationManager.class, looseSignatures = true)
public class ShadowLocationManager {

  private static final String TAG = "ShadowLocationManager";

  private static final long GET_CURRENT_LOCATION_TIMEOUT_MS = 30 * 1000;
  private static final long MAX_CURRENT_LOCATION_AGE_MS = 10 * 1000;

  /**
   * ProviderProperties is not public prior to S, so a new class is required to represent it prior
   * to that platform.
   */
  public static class ProviderProperties {
    @Nullable private final Object properties;

    private final boolean requiresNetwork;
    private final boolean requiresSatellite;
    private final boolean requiresCell;
    private final boolean hasMonetaryCost;
    private final boolean supportsAltitude;
    private final boolean supportsSpeed;
    private final boolean supportsBearing;
    private final int powerRequirement;
    private final int accuracy;

    @RequiresApi(VERSION_CODES.S)
    ProviderProperties(android.location.provider.ProviderProperties properties) {
      this.properties = Objects.requireNonNull(properties);
      this.requiresNetwork = false;
      this.requiresSatellite = false;
      this.requiresCell = false;
      this.hasMonetaryCost = false;
      this.supportsAltitude = false;
      this.supportsSpeed = false;
      this.supportsBearing = false;
      this.powerRequirement = 0;
      this.accuracy = 0;
    }

    public ProviderProperties(
        boolean requiresNetwork,
        boolean requiresSatellite,
        boolean requiresCell,
        boolean hasMonetaryCost,
        boolean supportsAltitude,
        boolean supportsSpeed,
        boolean supportsBearing,
        int powerRequirement,
        int accuracy) {
      if (RuntimeEnvironment.getApiLevel() >= VERSION_CODES.S) {
        properties =
            new android.location.provider.ProviderProperties.Builder()
                .setHasNetworkRequirement(requiresNetwork)
                .setHasSatelliteRequirement(requiresSatellite)
                .setHasCellRequirement(requiresCell)
                .setHasMonetaryCost(hasMonetaryCost)
                .setHasAltitudeSupport(supportsAltitude)
                .setHasSpeedSupport(supportsSpeed)
                .setHasBearingSupport(supportsBearing)
                .setPowerUsage(powerRequirement)
                .setAccuracy(accuracy)
                .build();
      } else {
        properties = null;
      }

      this.requiresNetwork = requiresNetwork;
      this.requiresSatellite = requiresSatellite;
      this.requiresCell = requiresCell;
      this.hasMonetaryCost = hasMonetaryCost;
      this.supportsAltitude = supportsAltitude;
      this.supportsSpeed = supportsSpeed;
      this.supportsBearing = supportsBearing;
      this.powerRequirement = powerRequirement;
      this.accuracy = accuracy;
    }

    public ProviderProperties(Criteria criteria) {
      this(
          false,
          false,
          false,
          criteria.isCostAllowed(),
          criteria.isAltitudeRequired(),
          criteria.isSpeedRequired(),
          criteria.isBearingRequired(),
          criteria.getPowerRequirement(),
          criteria.getAccuracy());
    }

    @RequiresApi(VERSION_CODES.S)
    android.location.provider.ProviderProperties getProviderProperties() {
      return (android.location.provider.ProviderProperties) Objects.requireNonNull(properties);
    }

    Object getLegacyProviderProperties() {
      try {
        return ReflectionHelpers.callConstructor(
            Class.forName("com.android.internal.location.ProviderProperties"),
            ClassParameter.from(boolean.class, requiresNetwork),
            ClassParameter.from(boolean.class, requiresSatellite),
            ClassParameter.from(boolean.class, requiresCell),
            ClassParameter.from(boolean.class, hasMonetaryCost),
            ClassParameter.from(boolean.class, supportsAltitude),
            ClassParameter.from(boolean.class, supportsSpeed),
            ClassParameter.from(boolean.class, supportsBearing),
            ClassParameter.from(int.class, powerRequirement),
            ClassParameter.from(int.class, accuracy));
      } catch (ClassNotFoundException c) {
        throw new RuntimeException("Unable to load old ProviderProperties class", c);
      }
    }

    public boolean hasNetworkRequirement() {
      if (properties != null) {
        return ((android.location.provider.ProviderProperties) properties).hasNetworkRequirement();
      } else {
        return requiresNetwork;
      }
    }

    public boolean hasSatelliteRequirement() {
      if (properties != null) {
        return ((android.location.provider.ProviderProperties) properties)
            .hasSatelliteRequirement();
      } else {
        return requiresSatellite;
      }
    }

    public boolean isRequiresCell() {
      if (properties != null) {
        return ((android.location.provider.ProviderProperties) properties).hasCellRequirement();
      } else {
        return requiresCell;
      }
    }

    public boolean isHasMonetaryCost() {
      if (properties != null) {
        return ((android.location.provider.ProviderProperties) properties).hasMonetaryCost();
      } else {
        return hasMonetaryCost;
      }
    }

    public boolean hasAltitudeSupport() {
      if (properties != null) {
        return ((android.location.provider.ProviderProperties) properties).hasAltitudeSupport();
      } else {
        return supportsAltitude;
      }
    }

    public boolean hasSpeedSupport() {
      if (properties != null) {
        return ((android.location.provider.ProviderProperties) properties).hasSpeedSupport();
      } else {
        return supportsSpeed;
      }
    }

    public boolean hasBearingSupport() {
      if (properties != null) {
        return ((android.location.provider.ProviderProperties) properties).hasBearingSupport();
      } else {
        return supportsBearing;
      }
    }

    public int getPowerUsage() {
      if (properties != null) {
        return ((android.location.provider.ProviderProperties) properties).getPowerUsage();
      } else {
        return powerRequirement;
      }
    }

    public int getAccuracy() {
      if (properties != null) {
        return ((android.location.provider.ProviderProperties) properties).getAccuracy();
      } else {
        return accuracy;
      }
    }

    boolean meetsCriteria(Criteria criteria) {
      if (criteria.getAccuracy() != Criteria.NO_REQUIREMENT
          && criteria.getAccuracy() < getAccuracy()) {
        return false;
      }
      if (criteria.getPowerRequirement() != Criteria.NO_REQUIREMENT
          && criteria.getPowerRequirement() < getPowerUsage()) {
        return false;
      }
      if (criteria.isAltitudeRequired() && !hasAltitudeSupport()) {
        return false;
      }
      if (criteria.isSpeedRequired() && !hasSpeedSupport()) {
        return false;
      }
      if (criteria.isBearingRequired() && !hasBearingSupport()) {
        return false;
      }
      if (!criteria.isCostAllowed() && hasMonetaryCost) {
        return false;
      }
      return true;
    }
  }

  @GuardedBy("ShadowLocationManager.class")
  @Nullable
  private static Constructor<LocationProvider> locationProviderConstructor;

  @RealObject private LocationManager realLocationManager;

  @GuardedBy("providers")
  private final HashSet<ProviderEntry> providers = new HashSet<>();

  @GuardedBy("gpsStatusListeners")
  private final HashSet<GpsStatus.Listener> gpsStatusListeners = new HashSet<>();

  @GuardedBy("gnssStatusTransports")
  private final CopyOnWriteArrayList<GnssStatusCallbackTransport> gnssStatusTransports =
      new CopyOnWriteArrayList<>();

  @GuardedBy("nmeaMessageTransports")
  private final CopyOnWriteArrayList<OnNmeaMessageListenerTransport> nmeaMessageTransports =
      new CopyOnWriteArrayList<>();

  @GuardedBy("gnssMeasurementTransports")
  private final CopyOnWriteArrayList<GnssMeasurementsEventCallbackTransport>
      gnssMeasurementTransports = new CopyOnWriteArrayList<>();

  @GuardedBy("gnssAntennaInfoTransports")
  private final CopyOnWriteArrayList<GnssAntennaInfoListenerTransport> gnssAntennaInfoTransports =
      new CopyOnWriteArrayList<>();

  @Nullable private String gnssHardwareModelName;

  private int gnssYearOfHardware;

  private int gnssBatchSize;

  public ShadowLocationManager() {
    // create default providers
    providers.add(
        new ProviderEntry(
            GPS_PROVIDER,
            new ProviderProperties(
                true,
                true,
                false,
                false,
                true,
                true,
                true,
                Criteria.POWER_HIGH,
                Criteria.ACCURACY_FINE)));
    providers.add(
        new ProviderEntry(
            NETWORK_PROVIDER,
            new ProviderProperties(
                false,
                false,
                false,
                false,
                true,
                true,
                true,
                Criteria.POWER_LOW,
                Criteria.ACCURACY_COARSE)));
    providers.add(
        new ProviderEntry(
            PASSIVE_PROVIDER,
            new ProviderProperties(
                false,
                false,
                false,
                false,
                false,
                false,
                false,
                Criteria.POWER_LOW,
                Criteria.ACCURACY_COARSE)));
  }

  @Implementation
  protected List<String> getAllProviders() {
    ArrayList<String> allProviders = new ArrayList<>();
    for (ProviderEntry providerEntry : getProviderEntries()) {
      allProviders.add(providerEntry.getName());
    }
    return allProviders;
  }

  @Implementation
  @Nullable
  protected LocationProvider getProvider(String name) {
    if (RuntimeEnvironment.getApiLevel() < VERSION_CODES.KITKAT) {
      // jelly bean has no way to properly construct a LocationProvider, we give up
      return null;
    }

    ProviderEntry providerEntry = getProviderEntry(name);
    if (providerEntry == null) {
      return null;
    }

    ProviderProperties properties = providerEntry.getProperties();
    if (properties == null) {
      return null;
    }

    try {
      synchronized (ShadowLocationManager.class) {
        if (locationProviderConstructor == null) {
          if (RuntimeEnvironment.getApiLevel() >= VERSION_CODES.S) {
            locationProviderConstructor =
                LocationProvider.class.getConstructor(
                    String.class, android.location.provider.ProviderProperties.class);
          } else {
            locationProviderConstructor =
                LocationProvider.class.getConstructor(
                    String.class,
                    Class.forName("com.android.internal.location.ProviderProperties"));
          }
          locationProviderConstructor.setAccessible(true);
        }

        if (RuntimeEnvironment.getApiLevel() >= VERSION_CODES.S) {
          return locationProviderConstructor.newInstance(name, properties.getProviderProperties());
        } else {
          return locationProviderConstructor.newInstance(
              name, properties.getLegacyProviderProperties());
        }
      }
    } catch (ReflectiveOperationException e) {
      throw new LinkageError(e.getMessage(), e);
    }
  }

  @Implementation
  protected List<String> getProviders(boolean enabledOnly) {
    return getProviders(null, enabledOnly);
  }

  @Implementation
  protected List<String> getProviders(@Nullable Criteria criteria, boolean enabled) {
    ArrayList<String> matchingProviders = new ArrayList<>();
    for (ProviderEntry providerEntry : getProviderEntries()) {
      if (enabled && !isProviderEnabled(providerEntry.getName())) {
        continue;
      }
      if (criteria != null && !providerEntry.meetsCriteria(criteria)) {
        continue;
      }
      matchingProviders.add(providerEntry.getName());
    }
    return matchingProviders;
  }

  @Implementation
  @Nullable
  protected String getBestProvider(Criteria criteria, boolean enabled) {
    List<String> providers = getProviders(criteria, enabled);
    if (providers.isEmpty()) {
      providers = getProviders(null, enabled);
    }

    if (!providers.isEmpty()) {
      if (providers.contains(GPS_PROVIDER)) {
        return GPS_PROVIDER;
      } else if (providers.contains(NETWORK_PROVIDER)) {
        return NETWORK_PROVIDER;
      } else {
        return providers.get(0);
      }
    }

    return null;
  }

  @Implementation(minSdk = VERSION_CODES.S)
  @Nullable
  protected Object getProviderProperties(Object providerStr) {
    String provider = (String) providerStr;
    if (provider == null) {
      throw new IllegalArgumentException();
    }

    ProviderEntry providerEntry = getProviderEntry(provider);
    if (providerEntry == null) {
      return null;
    }

    ProviderProperties properties = providerEntry.getProperties();
    if (properties == null) {
      return null;
    }

    return properties.getProviderProperties();
  }

  @Implementation(minSdk = VERSION_CODES.S)
  protected boolean hasProvider(String provider) {
    if (provider == null) {
      throw new IllegalArgumentException();
    }

    return getProviderEntry(provider) != null;
  }

  @Implementation
  protected boolean isProviderEnabled(String provider) {
    if (RuntimeEnvironment.getApiLevel() >= VERSION_CODES.P) {
      if (!isLocationEnabled()) {
        return false;
      }
    }

    ProviderEntry entry = getProviderEntry(provider);
    return entry != null && entry.isEnabled();
  }

  /** Completely removes a provider. */
  public void removeProvider(String name) {
    removeProviderEntry(name);
  }

  /**
   * Sets the properties of the given provider. The provider will be created if it doesn't exist
   * already. This overload functions for all Android SDK levels.
   */
  public void setProviderProperties(String name, @Nullable ProviderProperties properties) {
    getOrCreateProviderEntry(Objects.requireNonNull(name)).setProperties(properties);
  }

  /**
   * Sets the given provider enabled or disabled. The provider will be created if it doesn't exist
   * already. On P and above, location must also be enabled via {@link #setLocationEnabled(boolean)}
   * in order for a provider to be considered enabled.
   */
  public void setProviderEnabled(String name, boolean enabled) {
    getOrCreateProviderEntry(name).setEnabled(enabled);
  }

  // @SystemApi
  @Implementation(minSdk = VERSION_CODES.P)
  protected boolean isLocationEnabledForUser(UserHandle userHandle) {
    return isLocationEnabled();
  }

  @Implementation(minSdk = P)
  protected boolean isLocationEnabled() {
    return getLocationMode() != LOCATION_MODE_OFF;
  }

  // @SystemApi
  @Implementation(minSdk = VERSION_CODES.P)
  protected void setLocationEnabledForUser(boolean enabled, UserHandle userHandle) {
    setLocationModeInternal(enabled ? LOCATION_MODE_HIGH_ACCURACY : LOCATION_MODE_OFF);
  }

  /**
   * On P and above, turns location on or off. On pre-P devices, sets the location mode to {@link
   * android.provider.Settings.Secure#LOCATION_MODE_HIGH_ACCURACY} or {@link
   * android.provider.Settings.Secure#LOCATION_MODE_OFF}.
   */
  public void setLocationEnabled(boolean enabled) {
    setLocationEnabledForUser(enabled, Process.myUserHandle());
  }

  private int getLocationMode() {
    return Secure.getInt(getContext().getContentResolver(), LOCATION_MODE, LOCATION_MODE_OFF);
  }

  /**
   * On pre-P devices, sets the device location mode. For P and above, use {@link
   * #setLocationEnabled(boolean)} and {@link #setProviderEnabled(String, boolean)} in combination
   * to achieve the desired effect.
   */
  public void setLocationMode(int locationMode) {
    if (RuntimeEnvironment.getApiLevel() >= VERSION_CODES.P) {
      throw new AssertionError(
          "Tests may not set location mode directly on P and above. Instead, use"
              + " setLocationEnabled() and setProviderEnabled() in combination to achieve the"
              + " desired result.");
    }

    setLocationModeInternal(locationMode);
  }

  private void setLocationModeInternal(int locationMode) {
    Secure.putInt(getContext().getContentResolver(), LOCATION_MODE, locationMode);
  }

  @Implementation
  @Nullable
  protected Location getLastKnownLocation(String provider) {
    ProviderEntry providerEntry = getProviderEntry(provider);
    if (providerEntry == null) {
      return null;
    }

    return providerEntry.getLastLocation();
  }

  /**
   * @deprecated Use {@link #simulateLocation(Location)} to update the last location for a provider.
   */
  @Deprecated
  public void setLastKnownLocation(String provider, @Nullable Location location) {
    getOrCreateProviderEntry(provider).setLastLocation(location);
  }

  @RequiresApi(api = VERSION_CODES.R)
  @Implementation(minSdk = VERSION_CODES.R)
  protected void getCurrentLocation(
      String provider,
      @Nullable CancellationSignal cancellationSignal,
      Executor executor,
      Consumer<Location> consumer) {
    getCurrentLocationInternal(
        provider, LocationRequest.create(), cancellationSignal, executor, consumer);
  }

  @RequiresApi(api = VERSION_CODES.S)
  @Implementation(minSdk = VERSION_CODES.S)
  protected void getCurrentLocation(
      String provider,
      LocationRequest request,
      @Nullable CancellationSignal cancellationSignal,
      Executor executor,
      Consumer<Location> consumer) {
    getCurrentLocationInternal(provider, request, cancellationSignal, executor, consumer);
  }

  @RequiresApi(api = VERSION_CODES.R)
  private void getCurrentLocationInternal(
      String provider,
      LocationRequest request,
      @Nullable CancellationSignal cancellationSignal,
      Executor executor,
      Consumer<Location> consumer) {
    if (cancellationSignal != null) {
      cancellationSignal.throwIfCanceled();
    }

    final Location location = getLastKnownLocation(provider);
    if (location != null) {
      long locationAgeMs =
          SystemClock.elapsedRealtime() - NANOSECONDS.toMillis(location.getElapsedRealtimeNanos());
      if (locationAgeMs < MAX_CURRENT_LOCATION_AGE_MS) {
        executor.execute(() -> consumer.accept(location));
        return;
      }
    }

    CurrentLocationTransport listener = new CurrentLocationTransport(executor, consumer);
    requestLocationUpdatesInternal(
        provider, new RoboLocationRequest(request), Runnable::run, listener);

    if (cancellationSignal != null) {
      cancellationSignal.setOnCancelListener(listener::cancel);
    }

    listener.startTimeout(GET_CURRENT_LOCATION_TIMEOUT_MS);
  }

  @Implementation
  protected void requestSingleUpdate(
      String provider, LocationListener listener, @Nullable Looper looper) {
    if (looper == null) {
      looper = Looper.myLooper();
      if (looper == null) {
        // forces appropriate exception
        new Handler();
      }
    }
    requestLocationUpdatesInternal(
        provider,
        new RoboLocationRequest(provider, 0, 0, true),
        new HandlerExecutor(new Handler(looper)),
        listener);
  }

  @Implementation
  protected void requestSingleUpdate(
      Criteria criteria, LocationListener listener, @Nullable Looper looper) {
    String bestProvider = getBestProvider(criteria, true);
    if (bestProvider == null) {
      throw new IllegalArgumentException("no providers found for criteria");
    }
    if (looper == null) {
      looper = Looper.myLooper();
      if (looper == null) {
        // forces appropriate exception
        new Handler();
      }
    }
    requestLocationUpdatesInternal(
        bestProvider,
        new RoboLocationRequest(bestProvider, 0, 0, true),
        new HandlerExecutor(new Handler(looper)),
        listener);
  }

  @Implementation
  protected void requestSingleUpdate(String provider, PendingIntent pendingIntent) {
    requestLocationUpdatesInternal(
        provider, new RoboLocationRequest(provider, 0, 0, true), pendingIntent);
  }

  @Implementation
  protected void requestSingleUpdate(Criteria criteria, PendingIntent pendingIntent) {
    String bestProvider = getBestProvider(criteria, true);
    if (bestProvider == null) {
      throw new IllegalArgumentException("no providers found for criteria");
    }
    requestLocationUpdatesInternal(
        bestProvider, new RoboLocationRequest(bestProvider, 0, 0, true), pendingIntent);
  }

  @Implementation
  protected void requestLocationUpdates(
      String provider, long minTime, float minDistance, LocationListener listener) {
    requestLocationUpdatesInternal(
        provider,
        new RoboLocationRequest(provider, minTime, minDistance, false),
        new HandlerExecutor(new Handler()),
        listener);
  }

  @Implementation
  protected void requestLocationUpdates(
      String provider,
      long minTime,
      float minDistance,
      LocationListener listener,
      @Nullable Looper looper) {
    if (looper == null) {
      looper = Looper.myLooper();
      if (looper == null) {
        // forces appropriate exception
        new Handler();
      }
    }
    requestLocationUpdatesInternal(
        provider,
        new RoboLocationRequest(provider, minTime, minDistance, false),
        new HandlerExecutor(new Handler(looper)),
        listener);
  }

  @Implementation(minSdk = VERSION_CODES.R)
  protected void requestLocationUpdates(
      String provider,
      long minTime,
      float minDistance,
      Executor executor,
      LocationListener listener) {
    requestLocationUpdatesInternal(
        provider,
        new RoboLocationRequest(provider, minTime, minDistance, false),
        executor,
        listener);
  }

  @Implementation
  protected void requestLocationUpdates(
      long minTime,
      float minDistance,
      Criteria criteria,
      LocationListener listener,
      @Nullable Looper looper) {
    String bestProvider = getBestProvider(criteria, true);
    if (bestProvider == null) {
      throw new IllegalArgumentException("no providers found for criteria");
    }
    if (looper == null) {
      looper = Looper.myLooper();
      if (looper == null) {
        // forces appropriate exception
        new Handler();
      }
    }
    requestLocationUpdatesInternal(
        bestProvider,
        new RoboLocationRequest(bestProvider, minTime, minDistance, false),
        new HandlerExecutor(new Handler(looper)),
        listener);
  }

  @Implementation(minSdk = VERSION_CODES.R)
  protected void requestLocationUpdates(
      long minTime,
      float minDistance,
      Criteria criteria,
      Executor executor,
      LocationListener listener) {
    String bestProvider = getBestProvider(criteria, true);
    if (bestProvider == null) {
      throw new IllegalArgumentException("no providers found for criteria");
    }
    requestLocationUpdatesInternal(
        bestProvider,
        new RoboLocationRequest(bestProvider, minTime, minDistance, false),
        executor,
        listener);
  }

  @Implementation
  protected void requestLocationUpdates(
      String provider, long minTime, float minDistance, PendingIntent pendingIntent) {
    requestLocationUpdatesInternal(
        provider, new RoboLocationRequest(provider, minTime, minDistance, false), pendingIntent);
  }

  @Implementation
  protected void requestLocationUpdates(
      long minTime, float minDistance, Criteria criteria, PendingIntent pendingIntent) {
    String bestProvider = getBestProvider(criteria, true);
    if (bestProvider == null) {
      throw new IllegalArgumentException("no providers found for criteria");
    }
    requestLocationUpdatesInternal(
        bestProvider,
        new RoboLocationRequest(bestProvider, minTime, minDistance, false),
        pendingIntent);
  }

  @Implementation(minSdk = VERSION_CODES.R)
  protected void requestLocationUpdates(
      @Nullable LocationRequest request, Executor executor, LocationListener listener) {
    if (request == null) {
      request = LocationRequest.create();
    }
    requestLocationUpdatesInternal(
        request.getProvider(), new RoboLocationRequest(request), executor, listener);
  }

  @Implementation(minSdk = VERSION_CODES.KITKAT)
  protected void requestLocationUpdates(
      @Nullable LocationRequest request, LocationListener listener, Looper looper) {
    if (request == null) {
      request = LocationRequest.create();
    }
    if (looper == null) {
      looper = Looper.myLooper();
      if (looper == null) {
        // forces appropriate exception
        new Handler();
      }
    }
    requestLocationUpdatesInternal(
        request.getProvider(),
        new RoboLocationRequest(request),
        new HandlerExecutor(new Handler(looper)),
        listener);
  }

  @Implementation(minSdk = VERSION_CODES.KITKAT)
  protected void requestLocationUpdates(
      @Nullable LocationRequest request, PendingIntent pendingIntent) {
    if (request == null) {
      request = LocationRequest.create();
    }
    requestLocationUpdatesInternal(
        request.getProvider(), new RoboLocationRequest(request), pendingIntent);
  }

  @Implementation(minSdk = VERSION_CODES.S)
  protected void requestLocationUpdates(
      String provider, LocationRequest request, Executor executor, LocationListener listener) {
    requestLocationUpdatesInternal(provider, new RoboLocationRequest(request), executor, listener);
  }

  @Implementation(minSdk = VERSION_CODES.S)
  protected void requestLocationUpdates(
      String provider, LocationRequest request, PendingIntent pendingIntent) {
    requestLocationUpdatesInternal(provider, new RoboLocationRequest(request), pendingIntent);
  }

  private void requestLocationUpdatesInternal(
      String provider, RoboLocationRequest request, Executor executor, LocationListener listener) {
    if (provider == null || request == null || executor == null || listener == null) {
      throw new IllegalArgumentException();
    }
    getOrCreateProviderEntry(provider).addListener(listener, request, executor);
  }

  private void requestLocationUpdatesInternal(
      String provider, RoboLocationRequest request, PendingIntent pendingIntent) {
    if (provider == null || request == null || pendingIntent == null) {
      throw new IllegalArgumentException();
    }
    getOrCreateProviderEntry(provider).addListener(pendingIntent, request);
  }

  @Implementation
  protected void removeUpdates(LocationListener listener) {
    removeUpdatesInternal(listener);
  }

  @Implementation
  protected void removeUpdates(PendingIntent pendingIntent) {
    removeUpdatesInternal(pendingIntent);
  }

  private void removeUpdatesInternal(Object key) {
    for (ProviderEntry providerEntry : getProviderEntries()) {
      providerEntry.removeListener(key);
    }
  }

  @Implementation(minSdk = VERSION_CODES.S)
  protected void requestFlush(String provider, LocationListener listener, int requestCode) {
    ProviderEntry entry = getProviderEntry(provider);
    if (entry == null) {
      throw new IllegalArgumentException("unknown provider \"" + provider + "\"");
    }

    entry.requestFlush(listener, requestCode);
  }

  @Implementation(minSdk = VERSION_CODES.S)
  protected void requestFlush(String provider, PendingIntent pendingIntent, int requestCode) {
    ProviderEntry entry = getProviderEntry(provider);
    if (entry == null) {
      throw new IllegalArgumentException("unknown provider \"" + provider + "\"");
    }

    entry.requestFlush(pendingIntent, requestCode);
  }

  /**
   * Returns the list of {@link LocationRequest} currently registered under the given provider.
   * Clients compiled against the public Android SDK should only use this method on S+, clients
   * compiled against the system Android SDK may only use this method on Kitkat+.
   *
   * <p>Prior to Android S {@link LocationRequest} equality is not well defined, so prefer using
   * {@link #getLegacyLocationRequests(String)} instead if equality is required for testing.
   */
  @RequiresApi(VERSION_CODES.KITKAT)
  public List<LocationRequest> getLocationRequests(String provider) {
    ProviderEntry providerEntry = getProviderEntry(provider);
    if (providerEntry == null) {
      return ImmutableList.of();
    }

    return ImmutableList.copyOf(
        Iterables.transform(
            providerEntry.getTransports(),
            transport -> transport.getRequest().getLocationRequest()));
  }

  /**
   * Returns the list of {@link RoboLocationRequest} currently registered under the given provider.
   * Since {@link LocationRequest} was not publicly visible prior to S, and did not exist prior to
   * Kitkat, {@link RoboLocationRequest} allows querying the location requests prior to those
   * platforms, and also implements proper equality comparisons for testing.
   */
  public List<RoboLocationRequest> getLegacyLocationRequests(String provider) {
    ProviderEntry providerEntry = getProviderEntry(provider);
    if (providerEntry == null) {
      return ImmutableList.of();
    }

    return ImmutableList.copyOf(
        Iterables.transform(providerEntry.getTransports(), LocationTransport::getRequest));
  }

  @Implementation(minSdk = VERSION_CODES.P)
  protected boolean injectLocation(Location location) {
    return false;
  }

  @Implementation(minSdk = VERSION_CODES.O)
  protected int getGnssBatchSize() {
    return gnssBatchSize;
  }

  /**
   * Sets the GNSS hardware batch size. Values greater than 0 enables hardware GNSS batching APIs.
   */
  public void setGnssBatchSize(int gnssBatchSize) {
    this.gnssBatchSize = gnssBatchSize;
  }

  @Implementation(minSdk = VERSION_CODES.O)
  protected boolean registerGnssBatchedLocationCallback(
      Object periodNanos, Object wakeOnFifoFull, Object callback, Object handler) {
    getOrCreateProviderEntry(GPS_PROVIDER)
        .setLegacyBatchedListener(
            callback,
            new HandlerExecutor((Handler) handler),
            gnssBatchSize,
            (Boolean) wakeOnFifoFull);
    return true;
  }

  @Implementation(minSdk = VERSION_CODES.O)
  protected void flushGnssBatch() {
    ProviderEntry e = getProviderEntry(GPS_PROVIDER);
    if (e != null) {
      e.flushLegacyBatch();
    }
  }

  @Implementation(minSdk = VERSION_CODES.O)
  protected boolean unregisterGnssBatchedLocationCallback(Object callback) {
    ProviderEntry e = getProviderEntry(GPS_PROVIDER);
    if (e != null) {
      e.clearLegacyBatchedListener();
    }
    return true;
  }

  @Implementation(minSdk = VERSION_CODES.P)
  @Nullable
  protected String getGnssHardwareModelName() {
    return gnssHardwareModelName;
  }

  /**
   * Sets the GNSS hardware model name returned by {@link
   * LocationManager#getGnssHardwareModelName()}.
   */
  public void setGnssHardwareModelName(@Nullable String gnssHardwareModelName) {
    this.gnssHardwareModelName = gnssHardwareModelName;
  }

  @Implementation(minSdk = VERSION_CODES.P)
  protected int getGnssYearOfHardware() {
    return gnssYearOfHardware;
  }

  /** Sets the GNSS year of hardware returned by {@link LocationManager#getGnssYearOfHardware()}. */
  public void setGnssYearOfHardware(int gnssYearOfHardware) {
    this.gnssYearOfHardware = gnssYearOfHardware;
  }

  @Implementation
  protected boolean addGpsStatusListener(GpsStatus.Listener listener) {
    if (RuntimeEnvironment.getApiLevel() > VERSION_CODES.R) {
      throw new UnsupportedOperationException(
          "GpsStatus APIs not supported, please use GnssStatus APIs instead");
    }

    synchronized (gpsStatusListeners) {
      gpsStatusListeners.add(listener);
    }

    return true;
  }

  @Implementation
  protected void removeGpsStatusListener(GpsStatus.Listener listener) {
    if (RuntimeEnvironment.getApiLevel() > VERSION_CODES.R) {
      throw new UnsupportedOperationException(
          "GpsStatus APIs not supported, please use GnssStatus APIs instead");
    }

    synchronized (gpsStatusListeners) {
      gpsStatusListeners.remove(listener);
    }
  }

  /** Returns the list of currently registered {@link GpsStatus.Listener}s. */
  public List<GpsStatus.Listener> getGpsStatusListeners() {
    synchronized (gpsStatusListeners) {
      return new ArrayList<>(gpsStatusListeners);
    }
  }

  @Implementation(minSdk = VERSION_CODES.N)
  protected boolean registerGnssStatusCallback(GnssStatus.Callback callback, Handler handler) {
    if (handler == null) {
      handler = new Handler();
    }

    return registerGnssStatusCallback(new HandlerExecutor(handler), callback);
  }

  @Implementation(minSdk = VERSION_CODES.R)
  protected boolean registerGnssStatusCallback(Executor executor, GnssStatus.Callback listener) {
    synchronized (gnssStatusTransports) {
      Iterables.removeIf(gnssStatusTransports, transport -> transport.getListener() == listener);
      gnssStatusTransports.add(new GnssStatusCallbackTransport(executor, listener));
    }

    return true;
  }

  @Implementation(minSdk = VERSION_CODES.N)
  protected void unregisterGnssStatusCallback(GnssStatus.Callback listener) {
    synchronized (gnssStatusTransports) {
      Iterables.removeIf(gnssStatusTransports, transport -> transport.getListener() == listener);
    }
  }

  /** Simulates a GNSS status started event. */
  @RequiresApi(VERSION_CODES.N)
  public void simulateGnssStatusStarted() {
    List<GnssStatusCallbackTransport> transports;
    synchronized (gnssStatusTransports) {
      transports = gnssStatusTransports;
    }

    for (GnssStatusCallbackTransport transport : transports) {
      transport.onStarted();
    }
  }

  /** Simulates a GNSS status first fix event. */
  @RequiresApi(VERSION_CODES.N)
  public void simulateGnssStatusFirstFix(int ttff) {
    List<GnssStatusCallbackTransport> transports;
    synchronized (gnssStatusTransports) {
      transports = gnssStatusTransports;
    }

    for (GnssStatusCallbackTransport transport : transports) {
      transport.onFirstFix(ttff);
    }
  }

  /** Simulates a GNSS status event. */
  @RequiresApi(VERSION_CODES.N)
  public void simulateGnssStatus(GnssStatus status) {
    List<GnssStatusCallbackTransport> transports;
    synchronized (gnssStatusTransports) {
      transports = gnssStatusTransports;
    }

    for (GnssStatusCallbackTransport transport : transports) {
      transport.onSatelliteStatusChanged(status);
    }
  }

  /**
   * @deprecated Use {@link #simulateGnssStatus(GnssStatus)} instead.
   */
  @Deprecated
  @RequiresApi(VERSION_CODES.N)
  public void sendGnssStatus(GnssStatus status) {
    simulateGnssStatus(status);
  }

  /** Simulates a GNSS status stopped event. */
  @RequiresApi(VERSION_CODES.N)
  public void simulateGnssStatusStopped() {
    List<GnssStatusCallbackTransport> transports;
    synchronized (gnssStatusTransports) {
      transports = gnssStatusTransports;
    }

    for (GnssStatusCallbackTransport transport : transports) {
      transport.onStopped();
    }
  }

  @Implementation(minSdk = VERSION_CODES.N)
  protected boolean addNmeaListener(OnNmeaMessageListener listener, Handler handler) {
    if (handler == null) {
      handler = new Handler();
    }

    return addNmeaListener(new HandlerExecutor(handler), listener);
  }

  @Implementation(minSdk = VERSION_CODES.R)
  protected boolean addNmeaListener(Executor executor, OnNmeaMessageListener listener) {
    synchronized (nmeaMessageTransports) {
      Iterables.removeIf(nmeaMessageTransports, transport -> transport.getListener() == listener);
      nmeaMessageTransports.add(new OnNmeaMessageListenerTransport(executor, listener));
    }

    return true;
  }

  @Implementation(minSdk = VERSION_CODES.N)
  protected void removeNmeaListener(OnNmeaMessageListener listener) {
    synchronized (nmeaMessageTransports) {
      Iterables.removeIf(nmeaMessageTransports, transport -> transport.getListener() == listener);
    }
  }

  /** Simulates a NMEA message. */
  @RequiresApi(api = VERSION_CODES.N)
  public void simulateNmeaMessage(String message, long timestamp) {
    List<OnNmeaMessageListenerTransport> transports;
    synchronized (nmeaMessageTransports) {
      transports = nmeaMessageTransports;
    }

    for (OnNmeaMessageListenerTransport transport : transports) {
      transport.onNmeaMessage(message, timestamp);
    }
  }

  /**
   * @deprecated Use {@link #simulateNmeaMessage(String, long)} instead.
   */
  @Deprecated
  @RequiresApi(api = VERSION_CODES.N)
  public void sendNmeaMessage(String message, long timestamp) {
    simulateNmeaMessage(message, timestamp);
  }

  @Implementation(minSdk = VERSION_CODES.N)
  protected boolean registerGnssMeasurementsCallback(
      GnssMeasurementsEvent.Callback listener, Handler handler) {
    if (RuntimeEnvironment.getApiLevel() >= VERSION_CODES.R) {
      if (handler == null) {
        handler = new Handler();
      }

      return registerGnssMeasurementsCallback(new HandlerExecutor(handler), listener);
    } else {
      return registerGnssMeasurementsCallback(Runnable::run, listener);
    }
  }

  @Implementation(minSdk = VERSION_CODES.R)
  @RequiresApi(api = VERSION_CODES.R)
  protected boolean registerGnssMeasurementsCallback(
      Object request, Object executor, Object callback) {
    return registerGnssMeasurementsCallback(
        (Executor) executor, (GnssMeasurementsEvent.Callback) callback);
  }

  @Implementation(minSdk = VERSION_CODES.R)
  protected boolean registerGnssMeasurementsCallback(
      Executor executor, GnssMeasurementsEvent.Callback listener) {
    synchronized (gnssMeasurementTransports) {
      Iterables.removeIf(
          gnssMeasurementTransports, transport -> transport.getListener() == listener);
      gnssMeasurementTransports.add(new GnssMeasurementsEventCallbackTransport(executor, listener));
    }

    return true;
  }

  @Implementation(minSdk = VERSION_CODES.N)
  protected void unregisterGnssMeasurementsCallback(GnssMeasurementsEvent.Callback listener) {
    synchronized (gnssMeasurementTransports) {
      Iterables.removeIf(
          gnssMeasurementTransports, transport -> transport.getListener() == listener);
    }
  }

  /** Simulates a GNSS measurements event. */
  @RequiresApi(api = VERSION_CODES.N)
  public void simulateGnssMeasurementsEvent(GnssMeasurementsEvent event) {
    List<GnssMeasurementsEventCallbackTransport> transports;
    synchronized (gnssMeasurementTransports) {
      transports = gnssMeasurementTransports;
    }

    for (GnssMeasurementsEventCallbackTransport transport : transports) {
      transport.onGnssMeasurementsReceived(event);
    }
  }

  /**
   * @deprecated Use {@link #simulateGnssMeasurementsEvent(GnssMeasurementsEvent)} instead.
   */
  @Deprecated
  @RequiresApi(api = VERSION_CODES.N)
  public void sendGnssMeasurementsEvent(GnssMeasurementsEvent event) {
    simulateGnssMeasurementsEvent(event);
  }

  /** Simulates a GNSS measurements status change. */
  @RequiresApi(api = VERSION_CODES.N)
  public void simulateGnssMeasurementsStatus(int status) {
    List<GnssMeasurementsEventCallbackTransport> transports;
    synchronized (gnssMeasurementTransports) {
      transports = gnssMeasurementTransports;
    }

    for (GnssMeasurementsEventCallbackTransport transport : transports) {
      transport.onStatusChanged(status);
    }
  }

  @Implementation(minSdk = VERSION_CODES.R)
  protected Object registerAntennaInfoListener(Object executor, Object listener) {
    synchronized (gnssAntennaInfoTransports) {
      Iterables.removeIf(
          gnssAntennaInfoTransports, transport -> transport.getListener() == listener);
      gnssAntennaInfoTransports.add(
          new GnssAntennaInfoListenerTransport(
              (Executor) executor, (GnssAntennaInfo.Listener) listener));
    }
    return true;
  }

  @Implementation(minSdk = VERSION_CODES.R)
  protected void unregisterAntennaInfoListener(Object listener) {
    synchronized (gnssAntennaInfoTransports) {
      Iterables.removeIf(
          gnssAntennaInfoTransports, transport -> transport.getListener() == listener);
    }
  }

  /** Simulates a GNSS antenna info event. */
  @RequiresApi(api = VERSION_CODES.R)
  public void simulateGnssAntennaInfo(List<GnssAntennaInfo> antennaInfos) {
    List<GnssAntennaInfoListenerTransport> transports;
    synchronized (gnssAntennaInfoTransports) {
      transports = gnssAntennaInfoTransports;
    }

    for (GnssAntennaInfoListenerTransport transport : transports) {
      transport.onGnssAntennaInfoReceived(new ArrayList<>(antennaInfos));
    }
  }

  /**
   * @deprecated Use {@link #simulateGnssAntennaInfo(List)} instead.
   */
  @Deprecated
  @RequiresApi(api = VERSION_CODES.R)
  public void sendGnssAntennaInfo(List<GnssAntennaInfo> antennaInfos) {
    simulateGnssAntennaInfo(antennaInfos);
  }

  /**
   * A convenience function equivalent to invoking {@link #simulateLocation(String, Location)} with
   * the provider of the given location.
   */
  public void simulateLocation(Location location) {
    simulateLocation(location.getProvider(), location);
  }

  /**
   * Delivers to the given provider (which will be created if necessary) a new location which will
   * be delivered to appropriate listeners and updates state accordingly. Delivery will ignore the
   * enabled/disabled state of providers, unlike location on a real device.
   *
   * <p>The location will also be delivered to the passive provider.
   */
  public void simulateLocation(String provider, Location... locations) {
    ProviderEntry providerEntry = getOrCreateProviderEntry(provider);
    if (!PASSIVE_PROVIDER.equals(providerEntry.getName())) {
      providerEntry.simulateLocation(locations);
    }

    ProviderEntry passiveProviderEntry = getProviderEntry(PASSIVE_PROVIDER);
    if (passiveProviderEntry != null) {
      passiveProviderEntry.simulateLocation(locations);
    }
  }

  /**
   * @deprecated Do not test listeners, instead use {@link #simulateLocation(Location)} and test the
   *     results of those listeners being invoked.
   */
  @Deprecated
  public List<LocationListener> getRequestLocationUpdateListeners() {
    return getLocationUpdateListeners();
  }

  /**
   * @deprecated Do not test listeners, instead use {@link #simulateLocation(Location)} and test the
   *     results of those listeners being invoked.
   */
  @Deprecated
  public List<LocationListener> getLocationUpdateListeners() {
    HashSet<LocationListener> listeners = new HashSet<>();
    for (ProviderEntry providerEntry : getProviderEntries()) {
      Iterables.addAll(
          listeners,
          Iterables.transform(
              Iterables.filter(providerEntry.getTransports(), LocationListenerTransport.class),
              LocationTransport::getKey));
    }
    return new ArrayList<>(listeners);
  }

  /**
   * @deprecated Do not test listeners, instead use {@link #simulateLocation(Location)} and test the
   *     results of those listeners being invoked.
   */
  @Deprecated
  public List<LocationListener> getLocationUpdateListeners(String provider) {
    ProviderEntry providerEntry = getProviderEntry(provider);
    if (providerEntry == null) {
      return Collections.emptyList();
    }

    HashSet<LocationListener> listeners = new HashSet<>();
    Iterables.addAll(
        listeners,
        Iterables.transform(
            Iterables.filter(providerEntry.getTransports(), LocationListenerTransport.class),
            LocationTransport::getKey));
    return new ArrayList<>(listeners);
  }

  /**
   * @deprecated Do not test pending intents, instead use {@link #simulateLocation(Location)} and
   *     test the results of those pending intent being invoked.
   */
  @Deprecated
  public List<PendingIntent> getLocationUpdatePendingIntents() {
    HashSet<PendingIntent> listeners = new HashSet<>();
    for (ProviderEntry providerEntry : getProviderEntries()) {
      Iterables.addAll(
          listeners,
          Iterables.transform(
              Iterables.filter(providerEntry.getTransports(), LocationPendingIntentTransport.class),
              LocationTransport::getKey));
    }
    return new ArrayList<>(listeners);
  }

  /**
   * Retrieves a list of all currently registered pending intents for the given provider.
   *
   * @deprecated Do not test pending intents, instead use {@link #simulateLocation(Location)} and
   *     test the results of those pending intent being invoked.
   */
  @Deprecated
  public List<PendingIntent> getLocationUpdatePendingIntents(String provider) {
    ProviderEntry providerEntry = getProviderEntry(provider);
    if (providerEntry == null) {
      return Collections.emptyList();
    }

    HashSet<PendingIntent> listeners = new HashSet<>();
    Iterables.addAll(
        listeners,
        Iterables.transform(
            Iterables.filter(providerEntry.getTransports(), LocationPendingIntentTransport.class),
            LocationTransport::getKey));
    return new ArrayList<>(listeners);
  }

  private Context getContext() {
    return ReflectionHelpers.getField(realLocationManager, "mContext");
  }

  private ProviderEntry getOrCreateProviderEntry(String name) {
    if (name == null) {
      throw new IllegalArgumentException("cannot use a null provider");
    }

    synchronized (providers) {
      ProviderEntry providerEntry = getProviderEntry(name);
      if (providerEntry == null) {
        providerEntry = new ProviderEntry(name, null);
        providers.add(providerEntry);
      }
      return providerEntry;
    }
  }

  @Nullable
  private ProviderEntry getProviderEntry(String name) {
    if (name == null) {
      return null;
    }

    synchronized (providers) {
      for (ProviderEntry providerEntry : providers) {
        if (name.equals(providerEntry.getName())) {
          return providerEntry;
        }
      }
    }

    return null;
  }

  private Set<ProviderEntry> getProviderEntries() {
    synchronized (providers) {
      return providers;
    }
  }

  private void removeProviderEntry(String name) {
    synchronized (providers) {
      providers.remove(getProviderEntry(name));
    }
  }

  // provider enabled logic is complicated due to many changes over different versions of android. a
  // brief explanation of how the logic works in this shadow (which is subtly different and more
  // complicated from how the logic works in real android):
  //
  // 1) prior to P, the source of truth for whether a provider is enabled must be the
  //    LOCATION_PROVIDERS_ALLOWED setting, so that direct writes into that setting are respected.
  //    changes to the network and gps providers must change LOCATION_MODE appropriately as well.
  // 2) for P, providers are considered enabled if the LOCATION_MODE setting is not off AND they are
  //    enabled via LOCATION_PROVIDERS_ALLOWED. direct writes into LOCATION_PROVIDERS_ALLOWED should
  //    be respected (if the LOCATION_MODE is not off). changes to LOCATION_MODE will change the
  //    state of the network and gps providers.
  // 3) for Q/R, providers are considered enabled if the LOCATION_MODE settings is not off AND they
  //    are enabled, but the store for the enabled state may not be LOCATION_PROVIDERS_ALLOWED, as
  //    writes into LOCATION_PROVIDERS_ALLOWED should not be respected. LOCATION_PROVIDERS_ALLOWED
  //    should still be updated so that provider state changes can be listened to via that setting.
  //    changes to LOCATION_MODE should not change the state of the network and gps provider.
  // 5) the passive provider is always special-cased at all API levels - it's state is controlled
  //    programmatically, and should never be determined by LOCATION_PROVIDERS_ALLOWED.
  private final class ProviderEntry {

    private final String name;

    @GuardedBy("this")
    private final CopyOnWriteArrayList<LocationTransport<?>> locationTransports =
        new CopyOnWriteArrayList<>();

    @GuardedBy("this")
    @Nullable
    private LegacyBatchedTransport legacyBatchedTransport;

    @GuardedBy("this")
    @Nullable
    private ProviderProperties properties;

    @GuardedBy("this")
    private boolean enabled;

    @GuardedBy("this")
    @Nullable
    private Location lastLocation;

    ProviderEntry(String name, @Nullable ProviderProperties properties) {
      this.name = name;

      this.properties = properties;

      switch (name) {
        case PASSIVE_PROVIDER:
          // passive provider always starts enabled
          enabled = true;
          break;
        case GPS_PROVIDER:
          enabled = ShadowSecure.INITIAL_GPS_PROVIDER_STATE;
          break;
        case NETWORK_PROVIDER:
          enabled = ShadowSecure.INITIAL_NETWORK_PROVIDER_STATE;
          break;
        default:
          enabled = false;
          break;
      }
    }

    public String getName() {
      return name;
    }

    public synchronized List<LocationTransport<?>> getTransports() {
      return locationTransports;
    }

    @Nullable
    public synchronized ProviderProperties getProperties() {
      return properties;
    }

    public synchronized void setProperties(@Nullable ProviderProperties properties) {
      this.properties = properties;
    }

    public boolean isEnabled() {
      if (PASSIVE_PROVIDER.equals(name) || RuntimeEnvironment.getApiLevel() >= VERSION_CODES.Q) {
        synchronized (this) {
          return enabled;
        }
      } else {
        String allowedProviders =
            Secure.getString(getContext().getContentResolver(), LOCATION_PROVIDERS_ALLOWED);
        if (TextUtils.isEmpty(allowedProviders)) {
          return false;
        } else {
          return Arrays.asList(allowedProviders.split(",")).contains(name);
        }
      }
    }

    public void setEnabled(boolean enabled) {
      List<LocationTransport<?>> transports;
      synchronized (this) {
        if (PASSIVE_PROVIDER.equals(name)) {
          // the passive provider cannot be disabled, but the passive provider didn't exist in
          // previous versions of this shadow. for backwards compatibility, we let the passive
          // provider be disabled. this also help emulate the situation where an app only has COARSE
          // permissions, which this shadow normally can't emulate.
          this.enabled = enabled;
          return;
        }

        int oldLocationMode = getLocationMode();
        int newLocationMode = oldLocationMode;
        if (RuntimeEnvironment.getApiLevel() < VERSION_CODES.P) {
          if (GPS_PROVIDER.equals(name)) {
            if (enabled) {
              switch (oldLocationMode) {
                case LOCATION_MODE_OFF:
                  newLocationMode = LOCATION_MODE_SENSORS_ONLY;
                  break;
                case LOCATION_MODE_BATTERY_SAVING:
                  newLocationMode = LOCATION_MODE_HIGH_ACCURACY;
                  break;
                default:
                  break;
              }
            } else {
              switch (oldLocationMode) {
                case LOCATION_MODE_SENSORS_ONLY:
                  newLocationMode = LOCATION_MODE_OFF;
                  break;
                case LOCATION_MODE_HIGH_ACCURACY:
                  newLocationMode = LOCATION_MODE_BATTERY_SAVING;
                  break;
                default:
                  break;
              }
            }
          } else if (NETWORK_PROVIDER.equals(name)) {
            if (enabled) {
              switch (oldLocationMode) {
                case LOCATION_MODE_OFF:
                  newLocationMode = LOCATION_MODE_BATTERY_SAVING;
                  break;
                case LOCATION_MODE_SENSORS_ONLY:
                  newLocationMode = LOCATION_MODE_HIGH_ACCURACY;
                  break;
                default:
                  break;
              }
            } else {
              switch (oldLocationMode) {
                case LOCATION_MODE_BATTERY_SAVING:
                  newLocationMode = LOCATION_MODE_OFF;
                  break;
                case LOCATION_MODE_HIGH_ACCURACY:
                  newLocationMode = LOCATION_MODE_SENSORS_ONLY;
                  break;
                default:
                  break;
              }
            }
          }
        }

        if (newLocationMode != oldLocationMode) {
          // this sets LOCATION_MODE and LOCATION_PROVIDERS_ALLOWED
          setLocationModeInternal(newLocationMode);
        } else if (RuntimeEnvironment.getApiLevel() >= VERSION_CODES.Q) {
          if (enabled == this.enabled) {
            return;
          }

          this.enabled = enabled;
          // set LOCATION_PROVIDERS_ALLOWED directly, without setting LOCATION_MODE. do this even
          // though LOCATION_PROVIDERS_ALLOWED is not the source of truth - we keep it up to date,
          // but ignore any direct writes to it
          ShadowSettings.ShadowSecure.updateEnabledProviders(
              getContext().getContentResolver(), name, enabled);
        } else {
          if (enabled == this.enabled) {
            return;
          }

          this.enabled = enabled;
          // set LOCATION_PROVIDERS_ALLOWED directly, without setting LOCATION_MODE
          ShadowSettings.ShadowSecure.updateEnabledProviders(
              getContext().getContentResolver(), name, enabled);
        }

        transports = locationTransports;
      }

      for (LocationTransport<?> transport : transports) {
        if (!transport.invokeOnProviderEnabled(name, enabled)) {
          synchronized (this) {
            Iterables.removeIf(locationTransports, current -> current == transport);
          }
        }
      }
    }

    @Nullable
    public synchronized Location getLastLocation() {
      return lastLocation;
    }

    public synchronized void setLastLocation(@Nullable Location location) {
      lastLocation = location;
    }

    public void simulateLocation(Location... locations) {
      List<LocationTransport<?>> transports;
      LegacyBatchedTransport batchedTransport;
      synchronized (this) {
        lastLocation = new Location(locations[locations.length - 1]);
        transports = locationTransports;
        batchedTransport = legacyBatchedTransport;
      }

      if (batchedTransport != null) {
        batchedTransport.invokeOnLocations(locations);
      }

      for (LocationTransport<?> transport : transports) {
        if (!transport.invokeOnLocations(locations)) {
          synchronized (this) {
            Iterables.removeIf(locationTransports, current -> current == transport);
          }
        }
      }
    }

    public synchronized boolean meetsCriteria(Criteria criteria) {
      if (PASSIVE_PROVIDER.equals(name)) {
        return false;
      }

      if (properties == null) {
        return false;
      }
      return properties.meetsCriteria(criteria);
    }

    public void addListener(
        LocationListener listener, RoboLocationRequest request, Executor executor) {
      addListenerInternal(new LocationListenerTransport(listener, request, executor));
    }

    public void addListener(PendingIntent pendingIntent, RoboLocationRequest request) {
      addListenerInternal(new LocationPendingIntentTransport(getContext(), pendingIntent, request));
    }

    public void setLegacyBatchedListener(
        Object callback, Executor executor, int batchSize, boolean flushOnFifoFull) {
      synchronized (this) {
        legacyBatchedTransport =
            new LegacyBatchedTransport(callback, executor, batchSize, flushOnFifoFull);
      }
    }

    public void flushLegacyBatch() {
      LegacyBatchedTransport batchedTransport;
      synchronized (this) {
        batchedTransport = legacyBatchedTransport;
      }

      if (batchedTransport != null) {
        batchedTransport.invokeFlush();
      }
    }

    public void clearLegacyBatchedListener() {
      synchronized (this) {
        legacyBatchedTransport = null;
      }
    }

    private void addListenerInternal(LocationTransport<?> transport) {
      boolean invokeOnProviderEnabled;
      synchronized (this) {
        Iterables.removeIf(locationTransports, current -> current.getKey() == transport.getKey());
        locationTransports.add(transport);
        invokeOnProviderEnabled = !enabled;
      }

      if (invokeOnProviderEnabled) {
        if (!transport.invokeOnProviderEnabled(name, false)) {
          synchronized (this) {
            Iterables.removeIf(locationTransports, current -> current == transport);
          }
        }
      }
    }

    public synchronized void removeListener(Object key) {
      Iterables.removeIf(locationTransports, transport -> transport.getKey() == key);
    }

    public void requestFlush(Object key, int requestCode) {
      LocationTransport<?> transport;
      synchronized (this) {
        transport = Iterables.tryFind(locationTransports, t -> t.getKey() == key).orNull();
      }

      if (transport == null) {
        throw new IllegalArgumentException("unregistered listener cannot be flushed");
      }

      if (!transport.invokeOnFlush(requestCode)) {
        synchronized (this) {
          Iterables.removeIf(locationTransports, current -> current == transport);
        }
      }
    }

    @Override
    public boolean equals(Object o) {
      if (o instanceof ProviderEntry) {
        ProviderEntry that = (ProviderEntry) o;
        return Objects.equals(name, that.name);
      }

      return false;
    }

    @Override
    public int hashCode() {
      return Objects.hashCode(name);
    }
  }

  /**
   * LocationRequest doesn't exist prior to Kitkat, and is not public prior to S, so a new class is
   * required to represent it prior to those platforms.
   */
  public static final class RoboLocationRequest {
    @Nullable private final Object locationRequest;

    // all these parameters are meaningless if locationRequest is set
    private final long intervalMillis;
    private final float minUpdateDistanceMeters;
    private final boolean singleShot;

    @RequiresApi(VERSION_CODES.KITKAT)
    public RoboLocationRequest(LocationRequest locationRequest) {
      this.locationRequest = Objects.requireNonNull(locationRequest);
      intervalMillis = 0;
      minUpdateDistanceMeters = 0;
      singleShot = false;
    }

    public RoboLocationRequest(
        String provider, long intervalMillis, float minUpdateDistanceMeters, boolean singleShot) {
      if (RuntimeEnvironment.getApiLevel() >= VERSION_CODES.KITKAT) {
        locationRequest =
            LocationRequest.createFromDeprecatedProvider(
                provider, intervalMillis, minUpdateDistanceMeters, singleShot);
      } else {
        locationRequest = null;
      }

      this.intervalMillis = intervalMillis;
      this.minUpdateDistanceMeters = minUpdateDistanceMeters;
      this.singleShot = singleShot;
    }

    @RequiresApi(VERSION_CODES.KITKAT)
    public LocationRequest getLocationRequest() {
      return (LocationRequest) Objects.requireNonNull(locationRequest);
    }

    public long getIntervalMillis() {
      if (locationRequest != null) {
        return ((LocationRequest) locationRequest).getInterval();
      } else {
        return intervalMillis;
      }
    }

    public float getMinUpdateDistanceMeters() {
      if (locationRequest != null) {
        return ((LocationRequest) locationRequest).getSmallestDisplacement();
      } else {
        return minUpdateDistanceMeters;
      }
    }

    public boolean isSingleShot() {
      if (locationRequest != null) {
        return ((LocationRequest) locationRequest).getNumUpdates() == 1;
      } else {
        return singleShot;
      }
    }

    long getMinUpdateIntervalMillis() {
      if (locationRequest != null) {
        return ((LocationRequest) locationRequest).getFastestInterval();
      } else {
        return intervalMillis;
      }
    }

    int getMaxUpdates() {
      if (locationRequest != null) {
        return ((LocationRequest) locationRequest).getNumUpdates();
      } else {
        return singleShot ? 1 : Integer.MAX_VALUE;
      }
    }

    @Override
    public boolean equals(Object o) {
      if (o instanceof RoboLocationRequest) {
        RoboLocationRequest that = (RoboLocationRequest) o;

        // location request equality is not well-defined prior to S
        if (RuntimeEnvironment.getApiLevel() >= VERSION_CODES.S) {
          return Objects.equals(locationRequest, that.locationRequest);
        } else {
          if (intervalMillis != that.intervalMillis
              || singleShot != that.singleShot
              || Float.compare(that.minUpdateDistanceMeters, minUpdateDistanceMeters) != 0
              || (locationRequest == null) != (that.locationRequest == null)) {
            return false;
          }

          if (locationRequest != null) {
            LocationRequest lr = (LocationRequest) locationRequest;
            LocationRequest thatLr = (LocationRequest) that.locationRequest;

            if (lr.getQuality() != thatLr.getQuality()
                || lr.getInterval() != thatLr.getInterval()
                || lr.getFastestInterval() != thatLr.getFastestInterval()
                || lr.getExpireAt() != thatLr.getExpireAt()
                || lr.getNumUpdates() != thatLr.getNumUpdates()
                || lr.getSmallestDisplacement() != thatLr.getSmallestDisplacement()
                || lr.getHideFromAppOps() != thatLr.getHideFromAppOps()
                || !Objects.equals(lr.getProvider(), thatLr.getProvider())) {
              return false;
            }

            // allow null worksource to match empty worksource
            WorkSource workSource =
                lr.getWorkSource() == null ? new WorkSource() : lr.getWorkSource();
            WorkSource thatWorkSource =
                thatLr.getWorkSource() == null ? new WorkSource() : thatLr.getWorkSource();
            if (!workSource.equals(thatWorkSource)) {
              return false;
            }

            if (RuntimeEnvironment.getApiLevel() >= VERSION_CODES.Q) {
              if (lr.isLowPowerMode() != thatLr.isLowPowerMode()
                  || lr.isLocationSettingsIgnored() != thatLr.isLocationSettingsIgnored()) {
                return false;
              }
            }
          }

          return true;
        }
      }

      return false;
    }

    @Override
    public int hashCode() {
      if (locationRequest != null) {
        return locationRequest.hashCode();
      } else {
        return Objects.hash(intervalMillis, singleShot, minUpdateDistanceMeters);
      }
    }

    @Override
    public String toString() {
      if (locationRequest != null) {
        return locationRequest.toString();
      } else {
        return "Request[interval="
            + intervalMillis
            + ", minUpdateDistance="
            + minUpdateDistanceMeters
            + ", singleShot="
            + singleShot
            + "]";
      }
    }
  }

  private abstract static class LocationTransport<KeyT> {

    private final KeyT key;
    private final RoboLocationRequest request;

    private Location lastDeliveredLocation;
    private int numDeliveries;

    LocationTransport(KeyT key, RoboLocationRequest request) {
      if (key == null) {
        throw new IllegalArgumentException();
      }

      this.key = key;
      this.request = request;
    }

    public KeyT getKey() {
      return key;
    }

    public RoboLocationRequest getRequest() {
      return request;
    }

    // return false if this listener should be removed by this invocation
    public boolean invokeOnLocations(Location... locations) {
      ArrayList<Location> deliverableLocations = new ArrayList<>(locations.length);
      for (Location location : locations) {
        if (lastDeliveredLocation != null) {
          if (location.getTime() - lastDeliveredLocation.getTime()
              < request.getMinUpdateIntervalMillis()) {
            Log.w(TAG, "location rejected for simulated delivery - too fast");
            continue;
          }
          if (distanceBetween(location, lastDeliveredLocation)
              < request.getMinUpdateDistanceMeters()) {
            Log.w(TAG, "location rejected for simulated delivery - too close");
            continue;
          }
        }

        deliverableLocations.add(new Location(location));
        lastDeliveredLocation = new Location(location);
      }

      if (deliverableLocations.isEmpty()) {
        return true;
      }

      boolean needsRemoval = false;

      numDeliveries += deliverableLocations.size();
      if (numDeliveries >= request.getMaxUpdates()) {
        needsRemoval = true;
      }

      try {
        if (deliverableLocations.size() == 1) {
          onLocation(deliverableLocations.get(0));
        } else {
          onLocations(deliverableLocations);
        }
      } catch (CanceledException e) {
        needsRemoval = true;
      }

      return !needsRemoval;
    }

    // return false if this listener should be removed by this invocation
    public boolean invokeOnProviderEnabled(String provider, boolean enabled) {
      try {
        onProviderEnabled(provider, enabled);
        return true;
      } catch (CanceledException e) {
        return false;
      }
    }

    // return false if this listener should be removed by this invocation
    public boolean invokeOnFlush(int requestCode) {
      try {
        onFlushComplete(requestCode);
        return true;
      } catch (CanceledException e) {
        return false;
      }
    }

    abstract void onLocation(Location location) throws CanceledException;

    abstract void onLocations(List<Location> locations) throws CanceledException;

    abstract void onProviderEnabled(String provider, boolean enabled) throws CanceledException;

    abstract void onFlushComplete(int requestCode) throws CanceledException;
  }

  private static final class LocationListenerTransport extends LocationTransport<LocationListener> {

    private final Executor executor;

    LocationListenerTransport(
        LocationListener key, RoboLocationRequest request, Executor executor) {
      super(key, request);
      this.executor = executor;
    }

    @Override
    void onLocation(Location location) {
      executor.execute(() -> getKey().onLocationChanged(location));
    }

    @Override
    void onLocations(List<Location> locations) {
      executor.execute(
          () -> {
            if (RuntimeEnvironment.getApiLevel() >= VERSION_CODES.S) {
              getKey().onLocationChanged(locations);
            } else {
              for (Location location : locations) {
                getKey().onLocationChanged(location);
              }
            }
          });
    }

    @Override
    void onProviderEnabled(String provider, boolean enabled) {
      executor.execute(
          () -> {
            if (enabled) {
              getKey().onProviderEnabled(provider);
            } else {
              getKey().onProviderDisabled(provider);
            }
          });
    }

    @Override
    void onFlushComplete(int requestCode) {
      executor.execute(() -> getKey().onFlushComplete(requestCode));
    }
  }

  private static final class LocationPendingIntentTransport
      extends LocationTransport<PendingIntent> {

    private final Context context;

    LocationPendingIntentTransport(
        Context context, PendingIntent key, RoboLocationRequest request) {
      super(key, request);
      this.context = context;
    }

    @Override
    void onLocation(Location location) throws CanceledException {
      Intent intent = new Intent();
      intent.putExtra(LocationManager.KEY_LOCATION_CHANGED, new Location(location));
      getKey().send(context, 0, intent);
    }

    @Override
    void onLocations(List<Location> locations) throws CanceledException {
      if (RuntimeEnvironment.getApiLevel() >= VERSION_CODES.S) {
        Intent intent = new Intent();
        intent.putExtra(LocationManager.KEY_LOCATION_CHANGED, locations.get(locations.size() - 1));
        intent.putExtra(LocationManager.KEY_LOCATIONS, locations.toArray(new Location[0]));
        getKey().send(context, 0, intent);
      } else {
        for (Location location : locations) {
          onLocation(location);
        }
      }
    }

    @Override
    void onProviderEnabled(String provider, boolean enabled) throws CanceledException {
      Intent intent = new Intent();
      intent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
      getKey().send(context, 0, intent);
    }

    @Override
    void onFlushComplete(int requestCode) throws CanceledException {
      Intent intent = new Intent();
      intent.putExtra(LocationManager.KEY_FLUSH_COMPLETE, requestCode);
      getKey().send(context, 0, intent);
    }
  }

  private static final class LegacyBatchedTransport {

    private final android.location.BatchedLocationCallback callback;
    private final Executor executor;
    private final int batchSize;
    private final boolean flushOnFifoFull;

    private ArrayList<Location> batch = new ArrayList<>();

    LegacyBatchedTransport(
        Object callback, Executor executor, int batchSize, boolean flushOnFifoFull) {
      this.callback = (android.location.BatchedLocationCallback) callback;
      this.executor = executor;
      this.batchSize = batchSize;
      this.flushOnFifoFull = flushOnFifoFull;
    }

    public void invokeFlush() {
      ArrayList<Location> delivery = batch;
      batch = new ArrayList<>();
      executor.execute(
          () -> {
            callback.onLocationBatch(delivery);
            if (!delivery.isEmpty()) {
              callback.onLocationBatch(new ArrayList<>());
            }
          });
    }

    public void invokeOnLocations(Location... locations) {
      for (Location location : locations) {
        batch.add(new Location(location));
        if (batch.size() >= batchSize) {
          if (!flushOnFifoFull) {
            batch.remove(0);
          } else {
            ArrayList<Location> delivery = batch;
            batch = new ArrayList<>();
            executor.execute(() -> callback.onLocationBatch(delivery));
          }
        }
      }
    }
  }

  /**
   * Returns the distance between the two locations in meters. Adapted from:
   * http://stackoverflow.com/questions/837872/calculate-distance-in-meters-when-you-know-longitude-and-latitude-in-java
   */
  static float distanceBetween(Location location1, Location location2) {
    double earthRadius = 3958.75;
    double latDifference = Math.toRadians(location2.getLatitude() - location1.getLatitude());
    double lonDifference = Math.toRadians(location2.getLongitude() - location1.getLongitude());
    double a =
        Math.sin(latDifference / 2) * Math.sin(latDifference / 2)
            + Math.cos(Math.toRadians(location1.getLatitude()))
                * Math.cos(Math.toRadians(location2.getLatitude()))
                * Math.sin(lonDifference / 2)
                * Math.sin(lonDifference / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double dist = Math.abs(earthRadius * c);

    int meterConversion = 1609;

    return (float) (dist * meterConversion);
  }

  @Resetter
  public static synchronized void reset() {
    locationProviderConstructor = null;
  }

  @RequiresApi(api = VERSION_CODES.N)
  private final class CurrentLocationTransport implements LocationListener {

    private final Executor executor;
    private final Consumer<Location> consumer;
    private final Handler timeoutHandler;

    @GuardedBy("this")
    private boolean triggered;

    @Nullable Runnable timeoutRunnable;

    CurrentLocationTransport(Executor executor, Consumer<Location> consumer) {
      this.executor = executor;
      this.consumer = consumer;
      timeoutHandler = new Handler(Looper.getMainLooper());
    }

    public void cancel() {
      synchronized (this) {
        if (triggered) {
          return;
        }
        triggered = true;
      }

      cleanup();
    }

    public void startTimeout(long timeoutMs) {
      synchronized (this) {
        if (triggered) {
          return;
        }

        timeoutRunnable =
            () -> {
              timeoutRunnable = null;
              onLocationChanged((Location) null);
            };
        timeoutHandler.postDelayed(timeoutRunnable, timeoutMs);
      }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {}

    @Override
    public void onProviderEnabled(String provider) {}

    @Override
    public void onProviderDisabled(String provider) {
      onLocationChanged((Location) null);
    }

    @Override
    public void onLocationChanged(@Nullable Location location) {
      synchronized (this) {
        if (triggered) {
          return;
        }
        triggered = true;
      }

      executor.execute(() -> consumer.accept(location));

      cleanup();
    }

    private void cleanup() {
      removeUpdates(this);
      if (timeoutRunnable != null) {
        timeoutHandler.removeCallbacks(timeoutRunnable);
        timeoutRunnable = null;
      }
    }
  }

  private static final class GnssStatusCallbackTransport {

    private final Executor executor;
    private final GnssStatus.Callback listener;

    GnssStatusCallbackTransport(Executor executor, GnssStatus.Callback listener) {
      this.executor = Objects.requireNonNull(executor);
      this.listener = Objects.requireNonNull(listener);
    }

    GnssStatus.Callback getListener() {
      return listener;
    }

    @RequiresApi(api = VERSION_CODES.N)
    public void onStarted() {
      executor.execute(listener::onStarted);
    }

    @RequiresApi(api = VERSION_CODES.N)
    public void onFirstFix(int ttff) {
      executor.execute(() -> listener.onFirstFix(ttff));
    }

    @RequiresApi(api = VERSION_CODES.N)
    public void onSatelliteStatusChanged(GnssStatus status) {
      executor.execute(() -> listener.onSatelliteStatusChanged(status));
    }

    @RequiresApi(api = VERSION_CODES.N)
    public void onStopped() {
      executor.execute(listener::onStopped);
    }
  }

  private static final class OnNmeaMessageListenerTransport {

    private final Executor executor;
    private final OnNmeaMessageListener listener;

    OnNmeaMessageListenerTransport(Executor executor, OnNmeaMessageListener listener) {
      this.executor = Objects.requireNonNull(executor);
      this.listener = Objects.requireNonNull(listener);
    }

    OnNmeaMessageListener getListener() {
      return listener;
    }

    @RequiresApi(api = VERSION_CODES.N)
    public void onNmeaMessage(String message, long timestamp) {
      executor.execute(() -> listener.onNmeaMessage(message, timestamp));
    }
  }

  private static final class GnssMeasurementsEventCallbackTransport {

    private final Executor executor;
    private final GnssMeasurementsEvent.Callback listener;

    GnssMeasurementsEventCallbackTransport(
        Executor executor, GnssMeasurementsEvent.Callback listener) {
      this.executor = Objects.requireNonNull(executor);
      this.listener = Objects.requireNonNull(listener);
    }

    GnssMeasurementsEvent.Callback getListener() {
      return listener;
    }

    @RequiresApi(api = VERSION_CODES.N)
    public void onStatusChanged(int status) {
      executor.execute(() -> listener.onStatusChanged(status));
    }

    @RequiresApi(api = VERSION_CODES.N)
    public void onGnssMeasurementsReceived(GnssMeasurementsEvent event) {
      executor.execute(() -> listener.onGnssMeasurementsReceived(event));
    }
  }

  private static final class GnssAntennaInfoListenerTransport {

    private final Executor executor;
    private final GnssAntennaInfo.Listener listener;

    GnssAntennaInfoListenerTransport(Executor executor, GnssAntennaInfo.Listener listener) {
      this.executor = Objects.requireNonNull(executor);
      this.listener = Objects.requireNonNull(listener);
    }

    GnssAntennaInfo.Listener getListener() {
      return listener;
    }

    @RequiresApi(api = VERSION_CODES.R)
    public void onGnssAntennaInfoReceived(List<GnssAntennaInfo> antennaInfos) {
      executor.execute(() -> listener.onGnssAntennaInfoReceived(antennaInfos));
    }
  }

  private static final class HandlerExecutor implements Executor {
    private final Handler handler;

    HandlerExecutor(Handler handler) {
      this.handler = Objects.requireNonNull(handler);
    }

    @Override
    public void execute(Runnable command) {
      if (!handler.post(command)) {
        throw new RejectedExecutionException(handler + " is shutting down");
      }
    }
  }
}