summaryrefslogtreecommitdiff
path: root/tests/tests/content/src/android/content/pm/cts/PackageManagerTest.java
blob: 7ffe9e919250e1a7541ee8d1548fbcc4a7dab8e0 (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
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
/*
 * Copyright (C) 2008 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 android.content.pm.cts;

import static android.Manifest.permission.DELETE_PACKAGES;
import static android.Manifest.permission.GET_INTENT_SENDER_INTENT;
import static android.Manifest.permission.INSTALL_TEST_ONLY_PACKAGE;
import static android.Manifest.permission.WRITE_SECURE_SETTINGS;
import static android.content.Context.RECEIVER_EXPORTED;
import static android.content.Intent.FLAG_EXCLUDE_STOPPED_PACKAGES;
import static android.content.pm.ApplicationInfo.FLAG_HAS_CODE;
import static android.content.pm.ApplicationInfo.FLAG_INSTALLED;
import static android.content.pm.ApplicationInfo.FLAG_SYSTEM;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
import static android.content.pm.PackageManager.DONT_KILL_APP;
import static android.content.pm.PackageManager.GET_ACTIVITIES;
import static android.content.pm.PackageManager.GET_META_DATA;
import static android.content.pm.PackageManager.GET_PERMISSIONS;
import static android.content.pm.PackageManager.GET_PROVIDERS;
import static android.content.pm.PackageManager.GET_RECEIVERS;
import static android.content.pm.PackageManager.GET_SERVICES;
import static android.content.pm.PackageManager.MATCH_APEX;
import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
import static android.content.pm.PackageManager.MATCH_HIDDEN_UNTIL_INSTALLED_COMPONENTS;
import static android.content.pm.PackageManager.MATCH_INSTANT;
import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
import static android.content.pm.cts.PackageManagerShellCommandIncrementalTest.parsePackageDump;
import static android.os.UserHandle.CURRENT;
import static android.os.UserHandle.USER_CURRENT;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
import static org.testng.Assert.assertThrows;

import android.annotation.NonNull;
import android.app.Activity;
import android.app.ActivityOptions;
import android.app.ActivityThread;
import android.app.Instrumentation;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.content.cts.MockActivity;
import android.content.cts.MockContentProvider;
import android.content.cts.MockReceiver;
import android.content.cts.MockService;
import android.content.cts.R;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.ComponentInfo;
import android.content.pm.IPackageManager;
import android.content.pm.InstrumentationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageItemInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.ComponentEnabledSetting;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PermissionGroupInfo;
import android.content.pm.PermissionInfo;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.content.pm.SharedLibraryInfo;
import android.content.pm.Signature;
import android.content.pm.cts.util.AbandonAllPackageSessionsRule;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.platform.test.annotations.AppModeFull;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.content.FileProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ServiceTestRule;

import com.android.compatibility.common.util.PollingCheck;
import com.android.compatibility.common.util.SystemUtil;
import com.android.compatibility.common.util.TestUtils;
import com.android.internal.security.VerityUtils;

import com.google.common.truth.Expect;

import junit.framework.AssertionFailedError;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * This test is based on the declarations in AndroidManifest.xml. We create mock declarations
 * in AndroidManifest.xml just for test of PackageManager, and there are no corresponding parts
 * of these declarations in test project.
 */
@AppModeFull // TODO(Instant) Figure out which APIs should work.
@RunWith(AndroidJUnit4.class)
public class PackageManagerTest {
    private static final String TAG = "PackageManagerTest";

    private Context mContext;
    private PackageManager mPackageManager;
    private Instrumentation mInstrumentation;
    private static final String PACKAGE_NAME = "android.content.cts";
    private static final String STUB_PACKAGE_NAME = "com.android.cts.stub";
    private static final String APPLICATION_NAME = "android.content.cts.MockApplication";
    private static final String ACTIVITY_ACTION_NAME = "android.intent.action.PMTEST";
    private static final String MAIN_ACTION_NAME = "android.intent.action.MAIN";
    private static final String SERVICE_ACTION_NAME =
            "android.content.pm.cts.activity.PMTEST_SERVICE";
    private static final String RECEIVER_ACTION_NAME =
            "android.content.pm.cts.PackageManagerTest.PMTEST_RECEIVER";
    private static final String GRANTED_PERMISSION_NAME = "android.permission.INTERNET";
    private static final String NOT_GRANTED_PERMISSION_NAME = "android.permission.HARDWARE_TEST";
    private static final String ACTIVITY_NAME = "android.content.pm.cts.TestPmActivity";
    private static final String SERVICE_NAME = "android.content.pm.cts.TestPmService";
    private static final String RECEIVER_NAME = "android.content.pm.cts.PmTestReceiver";
    private static final String INSTRUMENT_NAME = "android.content.pm.cts.TestPmInstrumentation";
    private static final String CALL_ABROAD_PERMISSION_NAME =
            "android.content.cts.CALL_ABROAD_PERMISSION";
    private static final String PROVIDER_NAME = "android.content.cts.MockContentProvider";
    private static final String PERMISSIONGROUP_NAME = "android.permission-group.COST_MONEY";
    private static final String PERMISSION_TREE_ROOT =
            "android.content.cts.permission.TEST_DYNAMIC";
    // Number of activities/activity-alias in AndroidManifest
    private static final int NUM_OF_ACTIVITIES_IN_MANIFEST = 21;
    public static final long TIMEOUT_MS = TimeUnit.SECONDS.toMillis(10);

    private static final String SHIM_APEX_PACKAGE_NAME = "com.android.apex.cts.shim";

    private static final int[] PACKAGE_INFO_MATCH_FLAGS = {MATCH_UNINSTALLED_PACKAGES,
            MATCH_DISABLED_COMPONENTS, MATCH_SYSTEM_ONLY, MATCH_FACTORY_ONLY, MATCH_INSTANT,
            MATCH_APEX, MATCH_HIDDEN_UNTIL_INSTALLED_COMPONENTS};

    private static final String SAMPLE_APK_BASE = "/data/local/tmp/cts/content/";
    private static final String EMPTY_APP_APK = SAMPLE_APK_BASE
            + "CtsContentEmptyTestApp.apk";
    private static final String LONG_PACKAGE_NAME_APK = SAMPLE_APK_BASE
            + "CtsContentLongPackageNameTestApp.apk";
    private static final String LONG_SHARED_USER_ID_APK = SAMPLE_APK_BASE
            + "CtsContentLongSharedUserIdTestApp.apk";
    private static final String MAX_PACKAGE_NAME_APK = SAMPLE_APK_BASE
            + "CtsContentMaxPackageNameTestApp.apk";
    private static final String MAX_SHARED_USER_ID_APK = SAMPLE_APK_BASE
            + "CtsContentMaxSharedUserIdTestApp.apk";
    private static final String LONG_LABEL_NAME_APK = SAMPLE_APK_BASE
            + "CtsContentLongLabelNameTestApp.apk";
    private static final String LONG_USES_PERMISSION_NAME_APK = SAMPLE_APK_BASE
            + "CtsContentLongUsesPermissionNameTestApp.apk";
    private static final String EMPTY_APP_PACKAGE_NAME = "android.content.cts.emptytestapp";
    private static final String EMPTY_APP_MAX_PACKAGE_NAME = "android.content.cts.emptytestapp27j"
            + "EBRNRG3ozwBsGr1sVIM9U0bVTI2TdyIyeRkZgW4JrJefwNIBAmCg4AzqXiCvG6JjqA0uTCWSFu2YqAVxVd"
            + "iRKAay19k5VFlSaM7QW9uhvlrLQqsTW01ofFzxNDbp2QfIFHZR6rebKzKBz6byQFM0DYQnYMwFWXjWkMPN"
            + "dqkRLykoFLyBup53G68k2n8w";
    private static final String EMPTY_APP_LONG_USES_PERMISSION_PACKAGE_NAME =
            EMPTY_APP_PACKAGE_NAME + ".longusespermission";
    private static final String SHELL_PACKAGE_NAME = "com.android.shell";
    private static final String HELLO_WORLD_PACKAGE_NAME = "com.example.helloworld";
    private static final String HELLO_WORLD_APK = SAMPLE_APK_BASE + "HelloWorld5.apk";
    private static final String HELLO_WORLD_LOTS_OF_FLAGS_APK =
            SAMPLE_APK_BASE + "HelloWorldLotsOfFlags.apk";
    private static final String MOCK_LAUNCHER_PACKAGE_NAME = "android.content.cts.mocklauncherapp";
    private static final String MOCK_LAUNCHER_APK = SAMPLE_APK_BASE
            + "CtsContentMockLauncherTestApp.apk";
    private static final String NON_EXISTENT_PACKAGE_NAME = "android.content.cts.nonexistent.pkg";
    private static final String STUB_PACKAGE_APK = SAMPLE_APK_BASE
            + "CtsSyncAccountAccessStubs.apk";
    private static final String STUB_PACKAGE_SPLIT =
            SAMPLE_APK_BASE + "CtsSyncAccountAccessStubs_mdpi-v4.apk";

    private static final int MAX_SAFE_LABEL_LENGTH = 1000;

    // For intent resolution tests
    private static final String NON_EXISTENT_ACTION_NAME = "android.intent.action.cts.NON_EXISTENT";
    private static final String INTENT_RESOLUTION_TEST_PKG_NAME =
            "android.content.cts.IntentResolutionTest";
    private static final String RESOLUTION_TEST_ACTION_NAME =
            "android.intent.action.RESOLUTION_TEST";
    private static final String SELECTOR_ACTION_NAME = "android.intent.action.SELECTORTEST";
    private static final String FILE_PROVIDER_AUTHORITY = "android.content.cts.fileprovider";

    private static final ComponentName ACTIVITY_COMPONENT = new ComponentName(
            PACKAGE_NAME, ACTIVITY_NAME);
    private static final ComponentName SERVICE_COMPONENT = new ComponentName(
            PACKAGE_NAME, SERVICE_NAME);
    private static final ComponentName STUB_ACTIVITY_COMPONENT = ComponentName.createRelative(
            STUB_PACKAGE_NAME, ".StubActivity");
    private static final ComponentName STUB_SERVICE_COMPONENT = ComponentName.createRelative(
            STUB_PACKAGE_NAME, ".StubService");
    private static final ComponentName RESET_ENABLED_SETTING_ACTIVITY_COMPONENT =
            ComponentName.createRelative(MOCK_LAUNCHER_PACKAGE_NAME, ".MockActivity");
    private static final ComponentName RESET_ENABLED_SETTING_RECEIVER_COMPONENT =
            ComponentName.createRelative(MOCK_LAUNCHER_PACKAGE_NAME, ".MockReceiver");
    private static final ComponentName RESET_ENABLED_SETTING_SERVICE_COMPONENT =
            ComponentName.createRelative(MOCK_LAUNCHER_PACKAGE_NAME, ".MockService");
    private static final ComponentName RESET_ENABLED_SETTING_PROVIDER_COMPONENT =
            ComponentName.createRelative(MOCK_LAUNCHER_PACKAGE_NAME, ".MockProvider");

    private final ServiceTestRule mServiceTestRule = new ServiceTestRule();

    @Rule
    public AbandonAllPackageSessionsRule mAbandonSessionsRule = new AbandonAllPackageSessionsRule();

    @Rule public final Expect expect = Expect.create();

    @Before
    public void setup() throws Exception {
        mInstrumentation = InstrumentationRegistry.getInstrumentation();
        mContext = mInstrumentation.getContext();
        mPackageManager = mContext.getPackageManager();
    }

    @After
    public void tearDown() throws Exception {
        uninstallPackage(EMPTY_APP_PACKAGE_NAME);
        uninstallPackage(EMPTY_APP_MAX_PACKAGE_NAME);
        uninstallPackage(HELLO_WORLD_PACKAGE_NAME);
        uninstallPackage(MOCK_LAUNCHER_PACKAGE_NAME);
        uninstallPackage(EMPTY_APP_LONG_USES_PERMISSION_PACKAGE_NAME);
    }

    @Test
    public void testQuery() throws NameNotFoundException {
        // Test query Intent Activity related methods

        Intent activityIntent = new Intent(ACTIVITY_ACTION_NAME);
        String cmpActivityName = "android.content.pm.cts.TestPmCompare";
        // List with different activities and the filter doesn't work,
        List<ResolveInfo> listWithDiff = mPackageManager.queryIntentActivityOptions(
                new ComponentName(PACKAGE_NAME, cmpActivityName), null, activityIntent,
                PackageManager.ResolveInfoFlags.of(0));
        checkActivityInfoName(ACTIVITY_NAME, listWithDiff);

        // List with the same activities to make filter work
        List<ResolveInfo> listInSame = mPackageManager.queryIntentActivityOptions(
                new ComponentName(PACKAGE_NAME, ACTIVITY_NAME), null, activityIntent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, listInSame.size());

        // Test queryIntentActivities
        List<ResolveInfo> intentActivities =
                mPackageManager.queryIntentActivities(activityIntent,
                        PackageManager.ResolveInfoFlags.of(0));
        assertTrue(intentActivities.size() > 0);
        checkActivityInfoName(ACTIVITY_NAME, intentActivities);

        // End of Test query Intent Activity related methods

        // Test queryInstrumentation
        String targetPackage = "android";
        List<InstrumentationInfo> instrumentations = mPackageManager.queryInstrumentation(
                targetPackage, 0);
        checkInstrumentationInfoName(INSTRUMENT_NAME, instrumentations);

        // Test queryIntentServices
        Intent serviceIntent = new Intent(SERVICE_ACTION_NAME);
        List<ResolveInfo> services = mPackageManager.queryIntentServices(serviceIntent,
                PackageManager.ResolveInfoFlags.of(0));
        checkServiceInfoName(SERVICE_NAME, services);

        // Test queryBroadcastReceivers
        Intent broadcastIntent = new Intent(RECEIVER_ACTION_NAME);
        List<ResolveInfo> broadcastReceivers =
                mPackageManager.queryBroadcastReceivers(broadcastIntent,
                        PackageManager.ResolveInfoFlags.of(0));
        checkActivityInfoName(RECEIVER_NAME, broadcastReceivers);

        // Test queryPermissionsByGroup, queryContentProviders
        String testPermissionsGroup = "android.permission-group.COST_MONEY";
        List<PermissionInfo> permissions = mPackageManager.queryPermissionsByGroup(
                testPermissionsGroup, PackageManager.GET_META_DATA);
        checkPermissionInfoName(CALL_ABROAD_PERMISSION_NAME, permissions);

        ApplicationInfo appInfo = mPackageManager.getApplicationInfo(PACKAGE_NAME,
                PackageManager.ApplicationInfoFlags.of(0));
        List<ProviderInfo> providers = mPackageManager.queryContentProviders(PACKAGE_NAME,
                appInfo.uid, PackageManager.ComponentInfoFlags.of(0));
        checkProviderInfoName(PROVIDER_NAME, providers);
    }

    @Test
    public void testStoppedPackagesQuery() throws NameNotFoundException {
        installPackage(HELLO_WORLD_APK);

        final Intent intent = new Intent(ACTIVITY_ACTION_NAME);
        intent.addFlags(FLAG_EXCLUDE_STOPPED_PACKAGES);

        // Stopped after install.
        {
            final List<ResolveInfo> matches = mPackageManager.queryIntentActivities(intent,
                    PackageManager.ResolveInfoFlags.of(0));
            assertFalse(containsActivityInfoName("com.example.helloworld.MainActivity", matches));
        }

        SystemUtil.runShellCommand("am start -W "
                + "--user current "
                + "-a android.intent.action.MAIN "
                + "-c android.intent.category.LAUNCHER "
                + HELLO_WORLD_PACKAGE_NAME + "/.MainActivity");

        // Started.
        {
            final List<ResolveInfo> matches = mPackageManager.queryIntentActivities(intent,
                    PackageManager.ResolveInfoFlags.of(0));
            assertTrue(containsActivityInfoName("com.example.helloworld.MainActivity", matches));
        }

        assertEquals("", SystemUtil.runShellCommand("am force-stop " + HELLO_WORLD_PACKAGE_NAME));

        // Force stopped.
        {
            final List<ResolveInfo> matches = mPackageManager.queryIntentActivities(intent,
                    PackageManager.ResolveInfoFlags.of(0));
            assertFalse(containsActivityInfoName("com.example.helloworld.MainActivity", matches));
        }
    }

    // Disable the test due to feature revert
    private void testEnforceIntentToMatchIntentFilter() {
        Intent intent = new Intent();
        List<ResolveInfo> results;

        /* Implicit intent tests */

        intent.setPackage(INTENT_RESOLUTION_TEST_PKG_NAME);

        // Implicit intents with matching intent filter
        intent.setAction(RESOLUTION_TEST_ACTION_NAME);
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        results = mPackageManager.queryIntentServices(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        results = mPackageManager.queryBroadcastReceivers(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());

        // Implicit intents with non-matching intent filter
        intent.setAction(NON_EXISTENT_ACTION_NAME);
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());
        results = mPackageManager.queryIntentServices(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());
        results = mPackageManager.queryBroadcastReceivers(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());

        /* Explicit intent tests */

        intent = new Intent();
        ComponentName comp;

        // Explicit intents with matching intent filter
        intent.setAction(RESOLUTION_TEST_ACTION_NAME);
        comp = new ComponentName(INTENT_RESOLUTION_TEST_PKG_NAME, ACTIVITY_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        comp = new ComponentName(INTENT_RESOLUTION_TEST_PKG_NAME, SERVICE_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryIntentServices(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        comp = new ComponentName(INTENT_RESOLUTION_TEST_PKG_NAME, RECEIVER_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryBroadcastReceivers(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());

        // Explicit intents with non-matching intent filter on target T+
        intent.setAction(NON_EXISTENT_ACTION_NAME);
        comp = new ComponentName(INTENT_RESOLUTION_TEST_PKG_NAME, ACTIVITY_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());
        comp = new ComponentName(INTENT_RESOLUTION_TEST_PKG_NAME, SERVICE_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryIntentServices(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());
        comp = new ComponentName(INTENT_RESOLUTION_TEST_PKG_NAME, RECEIVER_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryBroadcastReceivers(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());

        // More comprehensive intent matching tests on target T+
        intent = new Intent();
        comp = new ComponentName(INTENT_RESOLUTION_TEST_PKG_NAME, ACTIVITY_NAME);
        intent.setComponent(comp);
        intent.setAction(RESOLUTION_TEST_ACTION_NAME + "2");
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());
        intent.setType("*/*");
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());
        intent.setData(Uri.parse("http://example.com"));
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());
        intent.setDataAndType(Uri.parse("http://example.com"), "*/*");
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        File file = new File(mContext.getFilesDir(), "test.txt");
        try {
            file.createNewFile();
        } catch (IOException e) {
            fail(e.getMessage());
        }
        Uri uri = FileProvider.getUriForFile(mContext, FILE_PROVIDER_AUTHORITY, file);
        intent.setData(uri);
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        file.delete();
        intent.addCategory(Intent.CATEGORY_APP_BROWSER);
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());

        // Explicit intents with non-matching intent filter on target < T
        final String api30Pkg = INTENT_RESOLUTION_TEST_PKG_NAME + "Api30";
        intent.setAction(NON_EXISTENT_ACTION_NAME);
        comp = new ComponentName(api30Pkg, ACTIVITY_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        comp = new ComponentName(api30Pkg, SERVICE_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryIntentServices(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        comp = new ComponentName(api30Pkg, RECEIVER_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryBroadcastReceivers(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());

        // Explicit intents with non-matching intent filter on our own package
        intent.setAction(NON_EXISTENT_ACTION_NAME);
        comp = new ComponentName(PACKAGE_NAME, ACTIVITY_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        comp = new ComponentName(PACKAGE_NAME, SERVICE_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryIntentServices(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        comp = new ComponentName(PACKAGE_NAME, RECEIVER_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryBroadcastReceivers(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());

        /* Intent selector tests */

        Intent selector = new Intent();
        selector.setPackage(INTENT_RESOLUTION_TEST_PKG_NAME);
        intent = new Intent();
        intent.setSelector(selector);

        // Matching intent and matching selector
        selector.setAction(SELECTOR_ACTION_NAME);
        intent.setAction(RESOLUTION_TEST_ACTION_NAME);
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        results = mPackageManager.queryIntentServices(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        results = mPackageManager.queryBroadcastReceivers(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());

        // Matching intent and non-matching selector
        selector.setAction(NON_EXISTENT_ACTION_NAME);
        intent.setAction(RESOLUTION_TEST_ACTION_NAME);
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());
        results = mPackageManager.queryIntentServices(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());
        results = mPackageManager.queryBroadcastReceivers(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());

        // Non-matching intent and matching selector
        selector.setAction(SELECTOR_ACTION_NAME);
        intent.setAction(NON_EXISTENT_ACTION_NAME);
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());
        results = mPackageManager.queryIntentServices(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());
        results = mPackageManager.queryBroadcastReceivers(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());

        /* Pending Intent tests */

        mInstrumentation.getUiAutomation().adoptShellPermissionIdentity(GET_INTENT_SENDER_INTENT);
        var authority = INTENT_RESOLUTION_TEST_PKG_NAME + ".provider";
        Bundle b = mContext.getContentResolver().call(authority, "", null, null);
        assertNotNull(b);
        PendingIntent pi = b.getParcelable("pendingIntent", PendingIntent.class);
        assertNotNull(pi);
        intent = pi.getIntent();
        // It should be a non-matching intent, which cannot be resolved in our package
        results = mPackageManager.queryIntentActivities(intent,
            PackageManager.ResolveInfoFlags.of(0));
        assertEquals(0, results.size());
        // However, querying on behalf of the pending intent creator should work properly
        results = pi.queryIntentComponents(0);
        assertEquals(1, results.size());
        mInstrumentation.getUiAutomation().dropShellPermissionIdentity();

        intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setComponent(
                new ComponentName("android", "com.android.internal.app.ResolverActivity"));
        try {
            mContext.startActivity(intent);
        } catch (ActivityNotFoundException ignore) {

        }
    }

    @Test
    public void testRevertEnforceIntentToMatchIntentFilter() {
        Intent intent = new Intent();
        List<ResolveInfo> results;
        ComponentName comp;

        /* Component explicit intent tests */

        // Explicit intents with non-matching intent filter on target T+
        intent.setAction(NON_EXISTENT_ACTION_NAME);
        comp = new ComponentName(INTENT_RESOLUTION_TEST_PKG_NAME, ACTIVITY_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        comp = new ComponentName(INTENT_RESOLUTION_TEST_PKG_NAME, SERVICE_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryIntentServices(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        comp = new ComponentName(INTENT_RESOLUTION_TEST_PKG_NAME, RECEIVER_NAME);
        intent.setComponent(comp);
        results = mPackageManager.queryBroadcastReceivers(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());

        /* Intent selector tests */

        Intent selector = new Intent();
        selector.setPackage(INTENT_RESOLUTION_TEST_PKG_NAME);
        intent = new Intent();
        intent.setSelector(selector);

        // Non-matching intent and matching selector
        selector.setAction(SELECTOR_ACTION_NAME);
        intent.setAction(NON_EXISTENT_ACTION_NAME);
        results = mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        results = mPackageManager.queryIntentServices(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
        results = mPackageManager.queryBroadcastReceivers(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(1, results.size());
    }

    private boolean containsActivityInfoName(String expectedName, List<ResolveInfo> resolves) {
        Iterator<ResolveInfo> infoIterator = resolves.iterator();
        String current;
        while (infoIterator.hasNext()) {
            current = infoIterator.next().activityInfo.name;
            if (current.equals(expectedName)) {
                return true;
            }
        }
        return false;
    }
    private void checkActivityInfoName(String expectedName, List<ResolveInfo> resolves) {
        assertTrue(containsActivityInfoName(expectedName, resolves));
    }

    private void checkServiceInfoName(String expectedName, List<ResolveInfo> resolves) {
        boolean isContained = false;
        Iterator<ResolveInfo> infoIterator = resolves.iterator();
        String current;
        while (infoIterator.hasNext()) {
            current = infoIterator.next().serviceInfo.name;
            if (current.equals(expectedName)) {
                isContained = true;
                break;
            }
        }
        assertTrue(isContained);
    }

    private void checkPermissionInfoName(String expectedName, List<PermissionInfo> permissions) {
        List<String> names = new ArrayList<String>();
        for (PermissionInfo permission : permissions) {
            names.add(permission.name);
        }
        boolean isContained = names.contains(expectedName);
        assertTrue("Permission " + expectedName + " not present in " + names, isContained);
    }

    private void checkProviderInfoName(String expectedName, List<ProviderInfo> providers) {
        boolean isContained = false;
        Iterator<ProviderInfo> infoIterator = providers.iterator();
        String current;
        while (infoIterator.hasNext()) {
            current = infoIterator.next().name;
            if (current.equals(expectedName)) {
                isContained = true;
                break;
            }
        }
        assertTrue(isContained);
    }

    private void checkInstrumentationInfoName(String expectedName,
            List<InstrumentationInfo> instrumentations) {
        boolean isContained = false;
        Iterator<InstrumentationInfo> infoIterator = instrumentations.iterator();
        String current;
        while (infoIterator.hasNext()) {
            current = infoIterator.next().name;
            if (current.equals(expectedName)) {
                isContained = true;
                break;
            }
        }
        assertTrue(isContained);
    }

    @Test
    public void testGetInfo() throws NameNotFoundException {
        // Test getApplicationInfo, getText
        ApplicationInfo appInfo = mPackageManager.getApplicationInfo(PACKAGE_NAME,
                PackageManager.ApplicationInfoFlags.of(0));
        int discriptionRes = R.string.hello_android;
        String expectedDisciptionRes = "Hello, Android!";
        CharSequence appText = mPackageManager.getText(PACKAGE_NAME, discriptionRes, appInfo);
        assertEquals(expectedDisciptionRes, appText);
        ComponentName activityName = new ComponentName(PACKAGE_NAME, ACTIVITY_NAME);
        ComponentName serviceName = new ComponentName(PACKAGE_NAME, SERVICE_NAME);
        ComponentName receiverName = new ComponentName(PACKAGE_NAME, RECEIVER_NAME);
        ComponentName instrName = new ComponentName(PACKAGE_NAME, INSTRUMENT_NAME);

        // Test getPackageInfo
        PackageInfo packageInfo = mPackageManager.getPackageInfo(PACKAGE_NAME,
                PackageManager.PackageInfoFlags.of(PackageManager.GET_INSTRUMENTATION));
        assertEquals(PACKAGE_NAME, packageInfo.packageName);

        // Test getApplicationInfo, getApplicationLabel
        String appLabel = "Android TestCase";
        assertEquals(appLabel, mPackageManager.getApplicationLabel(appInfo));
        assertEquals(PACKAGE_NAME, appInfo.processName);

        // Test getServiceInfo
        assertEquals(SERVICE_NAME, mPackageManager.getServiceInfo(serviceName,
                PackageManager.ComponentInfoFlags.of(PackageManager.GET_META_DATA)).name);

        // Test getReceiverInfo
        assertEquals(RECEIVER_NAME, mPackageManager.getReceiverInfo(receiverName,
                PackageManager.ComponentInfoFlags.of(0)).name);

        // Test getPackageArchiveInfo
        final String apkRoute = mContext.getPackageCodePath();
        final String apkName = mContext.getPackageName();
        assertEquals(apkName, mPackageManager.getPackageArchiveInfo(apkRoute,
                PackageManager.PackageInfoFlags.of(0)).packageName);

        // Test getPackagesForUid, getNameForUid
        checkPackagesNameForUid(PACKAGE_NAME, mPackageManager.getPackagesForUid(appInfo.uid));
        assertEquals(PACKAGE_NAME, mPackageManager.getNameForUid(appInfo.uid));

        // Test getActivityInfo
        assertEquals(ACTIVITY_NAME, mPackageManager.getActivityInfo(activityName,
                PackageManager.ComponentInfoFlags.of(0)).name);

        // Test getPackageGids
        assertTrue(mPackageManager.getPackageGids(PACKAGE_NAME).length > 0);

        // Test getPermissionInfo
        assertEquals(GRANTED_PERMISSION_NAME,
                mPackageManager.getPermissionInfo(GRANTED_PERMISSION_NAME, 0).name);

        // Test getPermissionGroupInfo
        assertEquals(PERMISSIONGROUP_NAME, mPackageManager.getPermissionGroupInfo(
                PERMISSIONGROUP_NAME, 0).name);

        // Test getAllPermissionGroups
        List<PermissionGroupInfo> permissionGroups = mPackageManager.getAllPermissionGroups(0);
        checkPermissionGroupInfoName(PERMISSIONGROUP_NAME, permissionGroups);

        // Test getInstalledApplications
        assertTrue(mPackageManager.getInstalledApplications(
                PackageManager.ApplicationInfoFlags.of(PackageManager.GET_META_DATA)).size() > 0);

        // Test getInstalledPacakge
        assertTrue(mPackageManager.getInstalledPackages(
                PackageManager.PackageInfoFlags.of(0)).size() > 0);

        // Test getInstrumentationInfo
        assertEquals(INSTRUMENT_NAME, mPackageManager.getInstrumentationInfo(instrName, 0).name);

        // Test getSystemSharedLibraryNames, in javadoc, String array and null
        // are all OK as return value.
        mPackageManager.getSystemSharedLibraryNames();

        // Test getLaunchIntentForPackage, Intent of activity
        // android.content.pm.cts.TestPmCompare is set to match the condition
        // to make sure the return of this method is not null.
        assertEquals(MAIN_ACTION_NAME, mPackageManager.getLaunchIntentForPackage(PACKAGE_NAME)
                .getAction());

        // Test isSafeMode. Because the test case will not run in safe mode, so
        // the return will be false.
        assertFalse(mPackageManager.isSafeMode());

        // Test getTargetSdkVersion
        int expectedTargetSdk = mPackageManager.getApplicationInfo(PACKAGE_NAME,
                PackageManager.ApplicationInfoFlags.of(0)).targetSdkVersion;
        assertEquals(expectedTargetSdk, mPackageManager.getTargetSdkVersion(PACKAGE_NAME));
        assertThrows(PackageManager.NameNotFoundException.class,
                () -> mPackageManager.getTargetSdkVersion(
                        "android.content.cts.non_existent_package"));
    }

    private void checkPackagesNameForUid(String expectedName, String[] uid) {
        boolean isContained = false;
        for (int i = 0; i < uid.length; i++) {
            if (uid[i].equals(expectedName)) {
                isContained = true;
                break;
            }
        }
        assertTrue(isContained);
    }

    private void checkPermissionGroupInfoName(String expectedName,
            List<PermissionGroupInfo> permissionGroups) {
        boolean isContained = false;
        Iterator<PermissionGroupInfo> infoIterator = permissionGroups.iterator();
        String current;
        while (infoIterator.hasNext()) {
            current = infoIterator.next().name;
            if (current.equals(expectedName)) {
                isContained = true;
                break;
            }
        }
        assertTrue(isContained);
    }


    /**
     * Simple test for {@link PackageManager#getPreferredActivities(List, List, String)} that tests
     * calling it has no effect. The method is essentially a no-op because no preferred activities
     * can be added.
     *
     * @see PackageManager#addPreferredActivity(IntentFilter, int, ComponentName[], ComponentName)
     */
    @Test
    public void testGetPreferredActivities() {
        assertNoPreferredActivities();
    }

    /**
     * Helper method to test that {@link PackageManager#getPreferredActivities(List, List, String)}
     * returns empty lists.
     */
    private void assertNoPreferredActivities() {
        List<ComponentName> outActivities = new ArrayList<ComponentName>();
        List<IntentFilter> outFilters = new ArrayList<IntentFilter>();
        mPackageManager.getPreferredActivities(outFilters, outActivities, PACKAGE_NAME);
        assertEquals(0, outActivities.size());
        assertEquals(0, outFilters.size());
    }

    /**
     * Test that calling {@link PackageManager#addPreferredActivity(IntentFilter, int,
     * ComponentName[], ComponentName)} throws a {@link SecurityException}.
     * <p/>
     * The method is protected by the {@link android.permission.SET_PREFERRED_APPLICATIONS}
     * signature permission. Even though this app declares that permission, it still should not be
     * able to call this method because it is not signed with the platform certificate.
     */
    @Test
    public void testAddPreferredActivity() {
        IntentFilter intentFilter = new IntentFilter(ACTIVITY_ACTION_NAME);
        ComponentName[] componentName = {new ComponentName(PACKAGE_NAME, ACTIVITY_NAME)};
        try {
            mPackageManager.addPreferredActivity(intentFilter, IntentFilter.MATCH_CATEGORY_HOST,
                    componentName, componentName[0]);
            fail("addPreferredActivity unexpectedly succeeded");
        } catch (SecurityException e) {
            // expected
        }
        assertNoPreferredActivities();
    }

    /**
     * Test that calling {@link PackageManager#clearPackagePreferredActivities(String)} has no
     * effect.
     */
    @Test
    public void testClearPackagePreferredActivities() {
        // just ensure no unexpected exceptions are thrown, nothing else to do
        mPackageManager.clearPackagePreferredActivities(PACKAGE_NAME);
    }

    private void checkComponentName(String expectedName, List<ComponentName> componentNames) {
        boolean isContained = false;
        Iterator<ComponentName> nameIterator = componentNames.iterator();
        String current;
        while (nameIterator.hasNext()) {
            current = nameIterator.next().getClassName();
            if (current.equals(expectedName)) {
                isContained = true;
                break;
            }
        }
        assertTrue(isContained);
    }

    private void checkIntentFilterAction(String expectedName, List<IntentFilter> intentFilters) {
        boolean isContained = false;
        Iterator<IntentFilter> filterIterator = intentFilters.iterator();
        IntentFilter currentFilter;
        String currentAction;
        while (filterIterator.hasNext()) {
            currentFilter = filterIterator.next();
            for (int i = 0; i < currentFilter.countActions(); i++) {
                currentAction = currentFilter.getAction(i);
                if (currentAction.equals(expectedName)) {
                    isContained = true;
                    break;
                }
            }
        }
        assertTrue(isContained);
    }

    @Test
    public void testAccessEnabledSetting() {
        mPackageManager.setApplicationEnabledSetting(PACKAGE_NAME,
                COMPONENT_ENABLED_STATE_ENABLED, DONT_KILL_APP);
        assertEquals(COMPONENT_ENABLED_STATE_ENABLED,
                mPackageManager.getApplicationEnabledSetting(PACKAGE_NAME));

        ComponentName componentName = new ComponentName(PACKAGE_NAME, ACTIVITY_NAME);
        mPackageManager.setComponentEnabledSetting(componentName,
                COMPONENT_ENABLED_STATE_ENABLED, DONT_KILL_APP);
        assertEquals(COMPONENT_ENABLED_STATE_ENABLED,
                mPackageManager.getComponentEnabledSetting(componentName));
    }

    @Test
    public void testGetApplicationEnabledSetting_notFound() {
        try {
            mPackageManager.getApplicationEnabledSetting("this.package.does.not.exist");
            fail("Exception expected");
        } catch (IllegalArgumentException expected) {
        }
    }

    @Test
    public void testGetIcon() throws NameNotFoundException {
        assertNotNull(mPackageManager.getApplicationIcon(PACKAGE_NAME));
        assertNotNull(mPackageManager.getApplicationIcon(mPackageManager.getApplicationInfo(
                PACKAGE_NAME, 0)));
        assertNotNull(mPackageManager
                .getActivityIcon(new ComponentName(PACKAGE_NAME, ACTIVITY_NAME)));
        assertNotNull(mPackageManager.getActivityIcon(new Intent(MAIN_ACTION_NAME)));

        assertNotNull(mPackageManager.getDefaultActivityIcon());
        assertTrue(mPackageManager.isDefaultApplicationIcon(
                mPackageManager.getDefaultActivityIcon()));
        assertTrue(mPackageManager.isDefaultApplicationIcon(mPackageManager.getDefaultActivityIcon()
                .getConstantState().newDrawable()));

        assertFalse(mPackageManager.isDefaultApplicationIcon(mPackageManager.getActivityIcon(
                new ComponentName(PACKAGE_NAME, ACTIVITY_NAME))));

        // getDrawable is called by ComponentInfo.loadIcon() which called by getActivityIcon()
        // method of PackageMaganer. Here is just assurance for its functionality.
        int iconRes = R.drawable.start;
        ApplicationInfo appInfo = mPackageManager.getApplicationInfo(PACKAGE_NAME,
                PackageManager.ApplicationInfoFlags.of(0));
        assertNotNull(mPackageManager.getDrawable(PACKAGE_NAME, iconRes, appInfo));
    }

    @Test
    public void testCheckSignaturesMatch_byPackageName() {
        // Compare the signature of this package to another package installed by this test suite
        // (see AndroidTest.xml). Their signatures must match.
        assertEquals(PackageManager.SIGNATURE_MATCH, mPackageManager.checkSignatures(PACKAGE_NAME,
                "com.android.cts.stub"));
        // This package's signature should match its own signature.
        assertEquals(PackageManager.SIGNATURE_MATCH, mPackageManager.checkSignatures(PACKAGE_NAME,
                PACKAGE_NAME));
    }

    @Test
    public void testCheckSignaturesMatch_byUid() throws NameNotFoundException {
        // Compare the signature of this package to another package installed by this test suite
        // (see AndroidTest.xml). Their signatures must match.
        int uid1 = mPackageManager.getPackageInfo(PACKAGE_NAME,
                PackageManager.PackageInfoFlags.of(0)).applicationInfo.uid;
        int uid2 = mPackageManager.getPackageInfo("com.android.cts.stub",
                PackageManager.PackageInfoFlags.of(0)).applicationInfo.uid;
        assertEquals(PackageManager.SIGNATURE_MATCH, mPackageManager.checkSignatures(uid1, uid2));

        // A UID's signature should match its own signature.
        assertEquals(PackageManager.SIGNATURE_MATCH, mPackageManager.checkSignatures(uid1, uid1));
    }

    @Test
    public void testCheckSignaturesNoMatch_byPackageName() {
        // This test package's signature shouldn't match the system's signature.
        assertEquals(PackageManager.SIGNATURE_NO_MATCH, mPackageManager.checkSignatures(
                PACKAGE_NAME, "android"));
    }

    @Test
    public void testCheckSignaturesNoMatch_byUid() throws NameNotFoundException {
        // This test package's signature shouldn't match the system's signature.
        int uid1 = mPackageManager.getPackageInfo(PACKAGE_NAME,
                PackageManager.PackageInfoFlags.of(0)).applicationInfo.uid;
        int uid2 = mPackageManager.getPackageInfo("android",
                PackageManager.PackageInfoFlags.of(0)).applicationInfo.uid;
        assertEquals(PackageManager.SIGNATURE_NO_MATCH,
                mPackageManager.checkSignatures(uid1, uid2));
    }

    @Test
    public void testCheckSignaturesUnknownPackage() {
        assertEquals(PackageManager.SIGNATURE_UNKNOWN_PACKAGE, mPackageManager.checkSignatures(
                PACKAGE_NAME, "this.package.does.not.exist"));
    }

    @Test
    public void testCheckPermissionGranted() {
        assertEquals(PackageManager.PERMISSION_GRANTED,
                mPackageManager.checkPermission(GRANTED_PERMISSION_NAME, PACKAGE_NAME));
    }

    @Test
    public void testCheckPermissionNotGranted() {
        assertEquals(PackageManager.PERMISSION_DENIED,
                mPackageManager.checkPermission(NOT_GRANTED_PERMISSION_NAME, PACKAGE_NAME));
    }

    @Test
    public void testResolveMethods() {
        // Test resolveActivity
        Intent intent = new Intent(ACTIVITY_ACTION_NAME);
        intent.setComponent(new ComponentName(PACKAGE_NAME, ACTIVITY_NAME));
        assertEquals(ACTIVITY_NAME, mPackageManager.resolveActivity(intent,
                PackageManager.ResolveInfoFlags.of(PackageManager.MATCH_DEFAULT_ONLY))
                .activityInfo.name);

        // Test resolveService
        intent = new Intent(SERVICE_ACTION_NAME);
        intent.setComponent(new ComponentName(PACKAGE_NAME, SERVICE_NAME));
        ResolveInfo resolveInfo = mPackageManager.resolveService(intent,
                PackageManager.ResolveInfoFlags.of(0));
        assertEquals(SERVICE_NAME, resolveInfo.serviceInfo.name);

        // Test resolveContentProvider
        String providerAuthorities = "ctstest";
        assertEquals(PROVIDER_NAME,
                mPackageManager.resolveContentProvider(providerAuthorities,
                        PackageManager.ComponentInfoFlags.of(0)).name);
    }

    @Test
    public void testGetResources() throws NameNotFoundException {
        ComponentName componentName = new ComponentName(PACKAGE_NAME, ACTIVITY_NAME);
        int resourceId = R.xml.pm_test;
        String xmlName = "android.content.cts:xml/pm_test";
        ApplicationInfo appInfo = mPackageManager.getApplicationInfo(PACKAGE_NAME,
                PackageManager.ApplicationInfoFlags.of(0));
        assertNotNull(mPackageManager.getXml(PACKAGE_NAME, resourceId, appInfo));
        assertEquals(xmlName, mPackageManager.getResourcesForActivity(componentName)
                .getResourceName(resourceId));
        assertEquals(xmlName, mPackageManager.getResourcesForApplication(appInfo).getResourceName(
                resourceId));
        assertEquals(xmlName, mPackageManager.getResourcesForApplication(PACKAGE_NAME)
                .getResourceName(resourceId));
    }

    @Test
    public void testGetResources_withConfig() throws NameNotFoundException {
        int resourceId = R.string.config_overridden_string;
        ApplicationInfo appInfo = mPackageManager.getApplicationInfo(PACKAGE_NAME,
                PackageManager.ApplicationInfoFlags.of(0));

        Configuration c1 = new Configuration(mContext.getResources().getConfiguration());
        c1.orientation = Configuration.ORIENTATION_PORTRAIT;
        assertEquals("default", mPackageManager.getResourcesForApplication(
                appInfo, c1).getString(resourceId));

        Configuration c2 = new Configuration(mContext.getResources().getConfiguration());
        c2.orientation = Configuration.ORIENTATION_LANDSCAPE;
        assertEquals("landscape", mPackageManager.getResourcesForApplication(
                appInfo, c2).getString(resourceId));
    }

    @Test
    public void testGetPackageArchiveInfo() {
        final String apkPath = mContext.getPackageCodePath();
        final String apkName = mContext.getPackageName();

        PackageInfo pkgInfo = mPackageManager.getPackageArchiveInfo(apkPath,
                PackageManager.PackageInfoFlags.of(PackageManager.GET_SIGNING_CERTIFICATES));
        assertEquals("getPackageArchiveInfo should return the correct package name",
                apkName, pkgInfo.packageName);
        assertNotNull("SigningInfo should have been collected when GET_SIGNING_CERTIFICATES"
                        + " flag is specified", pkgInfo.signingInfo);

        pkgInfo = mPackageManager.getPackageArchiveInfo(apkPath,
                PackageManager.PackageInfoFlags.of(PackageManager.GET_SIGNATURES));
        assertNotNull("Signatures should have been collected when GET_SIGNATURES"
                + " flag is specified", pkgInfo.signatures);

        pkgInfo = mPackageManager.getPackageArchiveInfo(apkPath,
                PackageManager.PackageInfoFlags.of(
                        PackageManager.GET_SIGNATURES | PackageManager.GET_SIGNING_CERTIFICATES));
        assertNotNull("SigningInfo should have been collected when"
                        + " GET_SIGNATURES and GET_SIGNING_CERTIFICATES flags are both specified",
                pkgInfo.signingInfo);
        assertNotNull("Signatures should have been collected when"
                + " GET_SIGNATURES and GET_SIGNING_CERTIFICATES flags are both specified",
                pkgInfo.signatures);

    }

    private void runTestGetPackageArchiveInfoSameApplicationInfo(long flags) {
        final String apkPath = mContext.getPackageCodePath();
        PackageInfo packageInfo = mPackageManager.getPackageArchiveInfo(apkPath,
                PackageManager.PackageInfoFlags.of(flags));

        ApplicationInfo applicationInfo = null;
        if (packageInfo.activities != null) {
            for (ActivityInfo ac : packageInfo.activities) {
                if (applicationInfo == null) {
                    applicationInfo = ac.applicationInfo;
                } else {
                    assertSame(applicationInfo, ac.applicationInfo);
                }
            }
        }
        if (packageInfo.receivers != null) {
            for (ActivityInfo ac : packageInfo.receivers) {
                if (applicationInfo == null) {
                    applicationInfo = ac.applicationInfo;
                } else {
                    assertSame(applicationInfo, ac.applicationInfo);
                }
            }
        }
        if (packageInfo.services != null) {
            for (ServiceInfo si : packageInfo.services) {
                if (applicationInfo == null) {
                    applicationInfo = si.applicationInfo;
                } else {
                    assertSame(applicationInfo, si.applicationInfo);
                }
            }
        }
        if (packageInfo.providers != null) {
            for (ProviderInfo pi : packageInfo.providers) {
                if (applicationInfo == null) {
                    applicationInfo = pi.applicationInfo;
                } else {
                    assertSame(applicationInfo, pi.applicationInfo);
                }
            }
        }
    }

    @Test
    public void testGetPackageArchiveInfoSameApplicationInfo() {
        runTestGetPackageArchiveInfoSameApplicationInfo(PackageManager.GET_META_DATA);
        runTestGetPackageArchiveInfoSameApplicationInfo(
                PackageManager.GET_META_DATA | PackageManager.GET_ACTIVITIES);
        runTestGetPackageArchiveInfoSameApplicationInfo(
                PackageManager.GET_META_DATA | PackageManager.GET_RECEIVERS);
        runTestGetPackageArchiveInfoSameApplicationInfo(
                PackageManager.GET_META_DATA | PackageManager.GET_SERVICES);
        runTestGetPackageArchiveInfoSameApplicationInfo(
                PackageManager.GET_META_DATA | PackageManager.GET_PROVIDERS);
        runTestGetPackageArchiveInfoSameApplicationInfo(
                PackageManager.GET_META_DATA | PackageManager.GET_ACTIVITIES
                        | PackageManager.GET_RECEIVERS);
    }

    @Test
    public void testGetNamesForUids_null() throws Exception {
        assertNull(mPackageManager.getNamesForUids(null));
    }

    @Test
    public void testGetNamesForUids_empty() throws Exception {
        assertNull(mPackageManager.getNamesForUids(new int[0]));
    }

    @Test
    public void testGetNamesForUids_valid() throws Exception {
        final int shimId =
                mPackageManager.getApplicationInfo("com.android.cts.ctsshim",
                        PackageManager.ApplicationInfoFlags.of(0)).uid;
        final int[] uids = new int[]{
                1000,
                Integer.MAX_VALUE,
                shimId,
        };
        final String[] result;
        result = mPackageManager.getNamesForUids(uids);
        assertNotNull(result);
        assertEquals(3, result.length);
        assertEquals("shared:android.uid.system", result[0]);
        assertEquals(null, result[1]);
        assertEquals("shared:com.android.cts.ctsshim", result[2]);
    }

    @Test
    public void testGetPackageUid() throws NameNotFoundException {
        int userId = mContext.getUserId();
        int expectedUid = UserHandle.getUid(userId, 1000);

        assertEquals(expectedUid, mPackageManager.getPackageUid("android",
                PackageManager.PackageInfoFlags.of(0)));

        int uid = mPackageManager.getApplicationInfo("com.android.cts.ctsshim",
                PackageManager.ApplicationInfoFlags.of(0)).uid;
        assertEquals(uid, mPackageManager.getPackageUid("com.android.cts.ctsshim",
                PackageManager.PackageInfoFlags.of(0)));
    }

    @Test
    public void testGetPackageInfo() throws NameNotFoundException {
        PackageInfo pkgInfo = mPackageManager.getPackageInfo(PACKAGE_NAME, GET_META_DATA
                | GET_PERMISSIONS | GET_ACTIVITIES | GET_PROVIDERS | GET_SERVICES | GET_RECEIVERS);
        assertTestPackageInfo(pkgInfo);
    }

    @Test
    public void testPackageSettingsFlags() throws Exception {
        assertEquals("Success\n", SystemUtil.runShellCommand(
                "pm install -t " + HELLO_WORLD_LOTS_OF_FLAGS_APK));
        final String pkgFlags = parsePackageDump(HELLO_WORLD_PACKAGE_NAME, "    pkgFlags=[");
        assertEquals(
                " DEBUGGABLE HAS_CODE ALLOW_TASK_REPARENTING ALLOW_CLEAR_USER_DATA TEST_ONLY "
                        + "VM_SAFE_MODE ALLOW_BACKUP LARGE_HEAP ]",
                pkgFlags);
        final String privatePkgFlags = parsePackageDump(HELLO_WORLD_PACKAGE_NAME,
                "    privatePkgFlags=[");
        assertEquals(
                " PRIVATE_FLAG_ACTIVITIES_RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION "
                        + "ALLOW_AUDIO_PLAYBACK_CAPTURE "
                        + "PRIVATE_FLAG_ALLOW_NATIVE_HEAP_POINTER_TAGGING ]",
                privatePkgFlags);
    }

    @Test
    public void testGetPackageInfo_notFound() {
        try {
            mPackageManager.getPackageInfo("this.package.does.not.exist",
                    PackageManager.PackageInfoFlags.of(0));
            fail("Exception expected");
        } catch (NameNotFoundException expected) {
        }
    }

    @Test
    public void testGetInstalledPackages() throws Exception {
        List<PackageInfo> pkgs = mPackageManager.getInstalledPackages(
                PackageManager.PackageInfoFlags.of(
                        GET_META_DATA | GET_PERMISSIONS | GET_ACTIVITIES | GET_PROVIDERS
                                | GET_SERVICES | GET_RECEIVERS));

        PackageInfo pkgInfo = findPackageOrFail(pkgs, PACKAGE_NAME);
        assertTestPackageInfo(pkgInfo);
    }

    /**
     * Asserts that the pkgInfo object correctly describes the {@link #PACKAGE_NAME} package.
     */
    private void assertTestPackageInfo(PackageInfo pkgInfo) {
        // Check metadata
        ApplicationInfo appInfo = pkgInfo.applicationInfo;
        assertEquals(APPLICATION_NAME, appInfo.name);
        assertEquals("Android TestCase", appInfo.loadLabel(mPackageManager));
        assertEquals(PACKAGE_NAME, appInfo.packageName);
        assertTrue(appInfo.enabled);
        // The process name defaults to the package name when not set.
        assertEquals(PACKAGE_NAME, appInfo.processName);
        assertEquals(0, appInfo.flags & FLAG_SYSTEM);
        assertEquals(FLAG_INSTALLED, appInfo.flags & FLAG_INSTALLED);
        assertEquals(FLAG_HAS_CODE, appInfo.flags & FLAG_HAS_CODE);

        // Check required permissions
        List<String> requestedPermissions = Arrays.asList(pkgInfo.requestedPermissions);
        assertThat(requestedPermissions).containsAtLeast(
                "android.permission.MANAGE_ACCOUNTS",
                "android.permission.ACCESS_NETWORK_STATE",
                "android.content.cts.permission.TEST_GRANTED");

        // Check usesPermissionFlags
        boolean requestedAccessFineLocation = false;
        boolean requestedAccessCoarseLocation = false;
        for (int i = 0; i < pkgInfo.requestedPermissions.length; i++) {
            final String name = pkgInfo.requestedPermissions[i];
            final int flags = pkgInfo.requestedPermissionsFlags[i];

            // Verify "never for location" flag
            final boolean neverForLocation = (flags
                    & PackageInfo.REQUESTED_PERMISSION_NEVER_FOR_LOCATION) != 0;
            if ("android.content.cts.permission.TEST_GRANTED".equals(name)) {
                assertTrue(name + " with flags " + flags, neverForLocation);
            } else {
                assertFalse(name + " with flags " + flags, neverForLocation);
            }

            // Verify "implicit" flag
            final boolean hasImplicitFlag =
                    (flags & PackageInfo.REQUESTED_PERMISSION_IMPLICIT) != 0;
            if ("android.permission.ACCESS_FINE_LOCATION".equals(name)) {
                assertFalse(name + " with flags " + flags, hasImplicitFlag);
                requestedAccessFineLocation = true;
            }
            if ("android.permission.ACCESS_COARSE_LOCATION".equals(name)) {
                assertTrue(name + " with flags " + flags, hasImplicitFlag);
                requestedAccessCoarseLocation = true;
            }
        }
        assertTrue("expected ACCESS_FINE_LOCATION to be requested", requestedAccessFineLocation);
        assertTrue("expected ACCESS_COARSE_LOCATION to be requested",
                requestedAccessCoarseLocation);

        // Check declared permissions
        PermissionInfo declaredPermission = (PermissionInfo) findPackageItemOrFail(
                pkgInfo.permissions, CALL_ABROAD_PERMISSION_NAME);
        assertEquals("Call abroad", declaredPermission.loadLabel(mPackageManager));
        assertEquals(PERMISSIONGROUP_NAME, declaredPermission.group);
        assertEquals(PermissionInfo.PROTECTION_NORMAL, declaredPermission.protectionLevel);

        // Check if number of activities in PackageInfo matches number of activities in manifest,
        // to make sure no synthesized activities not in the manifest are returned.
        assertEquals("Number of activities in manifest != Number of activities in PackageInfo",
                NUM_OF_ACTIVITIES_IN_MANIFEST, pkgInfo.activities.length);
        // Check activities
        ActivityInfo activity = findPackageItemOrFail(pkgInfo.activities, ACTIVITY_NAME);
        assertTrue(activity.enabled);
        assertTrue(activity.exported); // Has intent filters - export by default.
        assertEquals(PACKAGE_NAME, activity.taskAffinity);
        assertEquals(ActivityInfo.LAUNCH_SINGLE_TOP, activity.launchMode);

        // Check services
        ServiceInfo service = findPackageItemOrFail(pkgInfo.services, SERVICE_NAME);
        assertTrue(service.enabled);
        assertTrue(service.exported); // Has intent filters - export by default.
        assertEquals(PACKAGE_NAME, service.packageName);
        assertEquals(CALL_ABROAD_PERMISSION_NAME, service.permission);

        // Check ContentProviders
        ProviderInfo provider = findPackageItemOrFail(pkgInfo.providers, PROVIDER_NAME);
        assertTrue(provider.enabled);
        assertFalse(provider.exported); // Don't export by default.
        assertEquals(PACKAGE_NAME, provider.packageName);
        assertEquals("ctstest", provider.authority);

        // Check Receivers
        ActivityInfo receiver = findPackageItemOrFail(pkgInfo.receivers, RECEIVER_NAME);
        assertTrue(receiver.enabled);
        assertTrue(receiver.exported); // Has intent filters - export by default.
        assertEquals(PACKAGE_NAME, receiver.packageName);
    }

    // Tests that other packages can be queried.
    @Test
    public void testGetInstalledPackages_OtherPackages() throws Exception {
        List<PackageInfo> pkgInfos = mPackageManager.getInstalledPackages(
                PackageManager.PackageInfoFlags.of(0));

        // Check a normal package.
        PackageInfo pkgInfo = findPackageOrFail(pkgInfos, "com.android.cts.stub"); // A test package
        assertEquals(0, pkgInfo.applicationInfo.flags & FLAG_SYSTEM);

        // Check a system package.
        pkgInfo = findPackageOrFail(pkgInfos, "android");
        assertEquals(FLAG_SYSTEM, pkgInfo.applicationInfo.flags & FLAG_SYSTEM);
    }

    @Test
    public void testGetInstalledApplications() throws Exception {
        List<ApplicationInfo> apps = mPackageManager.getInstalledApplications(
                PackageManager.ApplicationInfoFlags.of(GET_META_DATA));

        ApplicationInfo app = findPackageItemOrFail(
                apps.toArray(new ApplicationInfo[]{}), APPLICATION_NAME);

        assertEquals(APPLICATION_NAME, app.name);
        assertEquals("Android TestCase", app.loadLabel(mPackageManager));
        assertEquals(PACKAGE_NAME, app.packageName);
        assertTrue(app.enabled);
        // The process name defaults to the package name when not set.
        assertEquals(PACKAGE_NAME, app.processName);
    }

    private PackageInfo findPackageOrFail(List<PackageInfo> pkgInfos, String pkgName) {
        for (PackageInfo pkgInfo : pkgInfos) {
            if (pkgName.equals(pkgInfo.packageName)) {
                return pkgInfo;
            }
        }
        fail("Package not found with name " + pkgName);
        return null;
    }

    private <T extends PackageItemInfo> T findPackageItemOrFail(T[] items, String name) {
        for (T item : items) {
            if (name.equals(item.name)) {
                return item;
            }
        }
        fail("Package item not found with name " + name);
        return null;
    }

    @Test
    public void testGetPackagesHoldingPermissions() {
        List<PackageInfo> pkgInfos = mPackageManager.getPackagesHoldingPermissions(
                new String[]{GRANTED_PERMISSION_NAME}, PackageManager.PackageInfoFlags.of(0));
        findPackageOrFail(pkgInfos, PACKAGE_NAME);

        pkgInfos = mPackageManager.getPackagesHoldingPermissions(
                new String[]{NOT_GRANTED_PERMISSION_NAME},
                PackageManager.PackageInfoFlags.of(0));
        for (PackageInfo pkgInfo : pkgInfos) {
            if (PACKAGE_NAME.equals(pkgInfo.packageName)) {
                fail("Must not return package " + PACKAGE_NAME);
            }
        }
    }

    @Test
    public void testGetPermissionInfo() throws NameNotFoundException {
        // Check a normal permission.
        String permissionName = "android.permission.INTERNET";
        PermissionInfo permissionInfo = mPackageManager.getPermissionInfo(permissionName, 0);
        assertEquals(permissionName, permissionInfo.name);
        assertEquals(PermissionInfo.PROTECTION_NORMAL, permissionInfo.getProtection());

        // Check a dangerous (runtime) permission.
        permissionName = "android.permission.RECORD_AUDIO";
        permissionInfo = mPackageManager.getPermissionInfo(permissionName, 0);
        assertEquals(permissionName, permissionInfo.name);
        assertEquals(PermissionInfo.PROTECTION_DANGEROUS, permissionInfo.getProtection());
        assertNotNull(permissionInfo.group);

        // Check a signature permission.
        permissionName = "android.permission.MODIFY_PHONE_STATE";
        permissionInfo = mPackageManager.getPermissionInfo(permissionName, 0);
        assertEquals(permissionName, permissionInfo.name);
        assertEquals(PermissionInfo.PROTECTION_SIGNATURE, permissionInfo.getProtection());

        // Check a special access (appop) permission.
        permissionName = "android.permission.SYSTEM_ALERT_WINDOW";
        permissionInfo = mPackageManager.getPermissionInfo(permissionName, 0);
        assertEquals(permissionName, permissionInfo.name);
        assertEquals(PermissionInfo.PROTECTION_SIGNATURE, permissionInfo.getProtection());
        assertEquals(PermissionInfo.PROTECTION_FLAG_APPOP,
                permissionInfo.getProtectionFlags() & PermissionInfo.PROTECTION_FLAG_APPOP);
    }

    @Test
    public void testGetPermissionInfo_notFound() {
        try {
            mPackageManager.getPermissionInfo("android.permission.nonexistent.permission", 0);
            fail("Exception expected");
        } catch (NameNotFoundException expected) {
        }
    }

    @Test
    public void testGetPermissionGroupInfo() throws NameNotFoundException {
        PermissionGroupInfo groupInfo = mPackageManager.getPermissionGroupInfo(
                PERMISSIONGROUP_NAME, 0);
        assertEquals(PERMISSIONGROUP_NAME, groupInfo.name);
        assertEquals(PACKAGE_NAME, groupInfo.packageName);
        assertFalse(TextUtils.isEmpty(groupInfo.loadDescription(mPackageManager)));
    }

    @Test
    public void testGetPermissionGroupInfo_notFound() throws NameNotFoundException {
        try {
            mPackageManager.getPermissionGroupInfo("this.group.does.not.exist", 0);
            fail("Exception expected");
        } catch (NameNotFoundException expected) {
        }
    }

    @Test
    public void testAddPermission_cantAddOutsideRoot() {
        PermissionInfo permissionInfo = new PermissionInfo();
        permissionInfo.name = "some.other.permission.tree.some-permission";
        permissionInfo.nonLocalizedLabel = "Some Permission";
        permissionInfo.protectionLevel = PermissionInfo.PROTECTION_NORMAL;
        // Remove first
        try {
            mPackageManager.removePermission(permissionInfo.name);
        } catch (SecurityException se) {
        }
        try {
            mPackageManager.addPermission(permissionInfo);
            fail("Must not add permission outside the permission tree defined in the manifest.");
        } catch (SecurityException expected) {
        }
    }

    @Test
    public void testAddPermission() throws NameNotFoundException {
        PermissionInfo permissionInfo = new PermissionInfo();
        permissionInfo.name = PERMISSION_TREE_ROOT + ".some-permission";
        permissionInfo.protectionLevel = PermissionInfo.PROTECTION_NORMAL;
        permissionInfo.nonLocalizedLabel = "Some Permission";
        // Remove first
        try {
            mPackageManager.removePermission(permissionInfo.name);
        } catch (SecurityException se) {
        }
        mPackageManager.addPermission(permissionInfo);
        PermissionInfo savedInfo = mPackageManager.getPermissionInfo(permissionInfo.name, 0);
        assertEquals(PACKAGE_NAME, savedInfo.packageName);
        assertEquals(PermissionInfo.PROTECTION_NORMAL, savedInfo.protectionLevel);
    }

    @Test
    public void testSetSystemAppHiddenUntilInstalled() throws Exception {
        String packageToManipulate = "com.android.cts.ctsshim";
        try {
            mPackageManager.getPackageInfo(packageToManipulate, MATCH_SYSTEM_ONLY);
        } catch (NameNotFoundException e) {
            Log.i(TAG, "Device doesn't have " + packageToManipulate + " installed, skipping");
            return;
        }

        try {
            SystemUtil.runWithShellPermissionIdentity(() ->
                    mPackageManager.setSystemAppState(packageToManipulate,
                            PackageManager.SYSTEM_APP_STATE_UNINSTALLED));
            SystemUtil.runWithShellPermissionIdentity(() ->
                    mPackageManager.setSystemAppState(packageToManipulate,
                            PackageManager.SYSTEM_APP_STATE_HIDDEN_UNTIL_INSTALLED_HIDDEN));

            // Setting the state to SYSTEM_APP_STATE_UNINSTALLED is an async operation in
            // PackageManagerService with no way to listen for completion, so poll until the
            // app is no longer found.
            int pollingPeriodMs = 100;
            int timeoutMs = 1000;
            long startTimeMs = SystemClock.elapsedRealtime();
            boolean isAppStillVisible = true;
            while (SystemClock.elapsedRealtime() < startTimeMs + timeoutMs) {
                try {
                    mPackageManager.getPackageInfo(packageToManipulate,
                            PackageManager.PackageInfoFlags.of(MATCH_SYSTEM_ONLY));
                } catch (NameNotFoundException e) {
                    // expected, stop polling
                    isAppStillVisible = false;
                    break;
                }
                Thread.sleep(pollingPeriodMs);
            }
            if (isAppStillVisible) {
                fail(packageToManipulate + " should not be found via getPackageInfo.");
            }
        } finally {
            SystemUtil.runWithShellPermissionIdentity(() ->
                    mPackageManager.setSystemAppState(packageToManipulate,
                            PackageManager.SYSTEM_APP_STATE_INSTALLED));
            SystemUtil.runWithShellPermissionIdentity(() ->
                    mPackageManager.setSystemAppState(packageToManipulate,
                            PackageManager.SYSTEM_APP_STATE_HIDDEN_UNTIL_INSTALLED_VISIBLE));
            try {
                mPackageManager.getPackageInfo(packageToManipulate,
                        PackageManager.PackageInfoFlags.of(MATCH_SYSTEM_ONLY));
            } catch (NameNotFoundException e) {
                fail(packageToManipulate
                        + " should be found via getPackageInfo after re-enabling.");
            }
        }
    }

    @Test
    public void testGetPackageInfo_ApexSupported_ApexPackage_MatchesApex() throws Exception {
        assumeTrue("Device doesn't support updating APEX", isUpdatingApexSupported());

        final int flags = PackageManager.MATCH_APEX
                | PackageManager.MATCH_FACTORY_ONLY
                | PackageManager.GET_SIGNING_CERTIFICATES
                | PackageManager.GET_SIGNATURES;
        PackageInfo packageInfo = mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME,
                PackageManager.PackageInfoFlags.of(flags));
        assertShimApexInfoIsCorrect(packageInfo);
    }

    @Test
    public void testGetPackageInfo_ApexSupported_ApexPackage_DoesNotMatchApex() {
        assumeTrue("Device doesn't support updating APEX", isUpdatingApexSupported());

        try {
            mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME,
                    PackageManager.PackageInfoFlags.of(0));
            fail("NameNotFoundException expected");
        } catch (NameNotFoundException expected) {
        }
    }

    @Test
    public void testGetPackageInfo_ApexNotSupported_ApexPackage_MatchesApex() {
        assumeFalse("Device supports updating APEX", isUpdatingApexSupported());

        try {
            mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME,
                    PackageManager.PackageInfoFlags.of(PackageManager.MATCH_APEX));
            fail("NameNotFoundException expected");
        } catch (NameNotFoundException expected) {
        }
    }

    @Test
    public void testGetPackageInfo_ApexNotSupported_ApexPackage_DoesNotMatchApex() {
        assumeFalse("Device supports updating APEX", isUpdatingApexSupported());

        try {
            mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME,
                    PackageManager.PackageInfoFlags.of(0));
            fail("NameNotFoundException expected");
        } catch (NameNotFoundException expected) {
        }
    }

    @Test
    public void testGetInstalledPackages_ApexSupported_MatchesApex() {
        assumeTrue("Device doesn't support updating APEX", isUpdatingApexSupported());

        final int flags = PackageManager.MATCH_APEX
                | PackageManager.MATCH_FACTORY_ONLY
                | PackageManager.GET_SIGNING_CERTIFICATES
                | PackageManager.GET_SIGNATURES;
        List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages(
                PackageManager.PackageInfoFlags.of(flags));
        List<PackageInfo> shimApex = installedPackages.stream().filter(
                packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect(
                Collectors.toList());
        assertWithMessage("More than one shim apex found").that(shimApex).hasSize(1);
        assertShimApexInfoIsCorrect(shimApex.get(0));
    }

    @Test
    public void testGetInstalledPackages_ApexSupported_DoesNotMatchApex() {
        assumeTrue("Device doesn't support updating APEX", isUpdatingApexSupported());

        List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages(
                PackageManager.PackageInfoFlags.of(0));
        List<PackageInfo> shimApex = installedPackages.stream().filter(
                packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect(
                Collectors.toList());
        assertWithMessage("Shim apex wasn't supposed to be found").that(shimApex).isEmpty();
    }

    @Test
    public void testGetInstalledPackages_ApexNotSupported_MatchesApex() {
        assumeFalse("Device supports updating APEX", isUpdatingApexSupported());

        List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages(
                PackageManager.PackageInfoFlags.of(PackageManager.MATCH_APEX));
        List<PackageInfo> shimApex = installedPackages.stream().filter(
                packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect(
                Collectors.toList());
        assertWithMessage("Shim apex wasn't supposed to be found").that(shimApex).isEmpty();
    }

    @Test
    public void testGetInstalledPackages_ApexNotSupported_DoesNotMatchApex() {
        assumeFalse("Device supports updating APEX", isUpdatingApexSupported());

        List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages(
                PackageManager.PackageInfoFlags.of(0));
        List<PackageInfo> shimApex = installedPackages.stream().filter(
                packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect(
                Collectors.toList());
        assertWithMessage("Shim apex wasn't supposed to be found").that(shimApex).isEmpty();
    }

    /**
     * Test that {@link ComponentInfo#metaData} data associated with all components in this
     * package will only be filled in if the {@link PackageManager#GET_META_DATA} flag is set.
     */
    @Test
    public void testGetInfo_noMetaData_InPackage() throws Exception {
        final PackageInfo info = mPackageManager.getPackageInfo(PACKAGE_NAME,
                PackageManager.PackageInfoFlags.of(
                        GET_ACTIVITIES | GET_SERVICES | GET_RECEIVERS | GET_PROVIDERS));

        assertThat(info.applicationInfo.metaData).isNull();
        Arrays.stream(info.activities).forEach(i -> assertThat(i.metaData).isNull());
        Arrays.stream(info.services).forEach(i -> assertThat(i.metaData).isNull());
        Arrays.stream(info.receivers).forEach(i -> assertThat(i.metaData).isNull());
        Arrays.stream(info.providers).forEach(i -> assertThat(i.metaData).isNull());
    }

    /**
     * Test that {@link ComponentInfo#metaData} data associated with this application will only be
     * filled in if the {@link PackageManager#GET_META_DATA} flag is set.
     */
    @Test
    public void testGetInfo_noMetaData_InApplication() throws Exception {
        final ApplicationInfo ai = mPackageManager.getApplicationInfo(PACKAGE_NAME,
                PackageManager.ApplicationInfoFlags.of(0));
        assertThat(ai.metaData).isNull();
    }

    /**
     * Test that {@link ComponentInfo#metaData} data associated with this activity will only be
     * filled in if the {@link PackageManager#GET_META_DATA} flag is set.
     */
    @Test
    public void testGetInfo_noMetaData_InActivity() throws Exception {
        final ComponentName componentName = new ComponentName(mContext, MockActivity.class);
        final ActivityInfo info = mPackageManager.getActivityInfo(componentName,
                PackageManager.ComponentInfoFlags.of(0));
        assertThat(info.metaData).isNull();
    }

    /**
     * Test that {@link ComponentInfo#metaData} data associated with this service will only be
     * filled in if the {@link PackageManager#GET_META_DATA} flag is set.
     */
    @Test
    public void testGetInfo_noMetaData_InService() throws Exception {
        final ComponentName componentName = new ComponentName(mContext, MockService.class);
        final ServiceInfo info = mPackageManager.getServiceInfo(componentName,
                PackageManager.ComponentInfoFlags.of(0));
        assertThat(info.metaData).isNull();
    }

    /**
     * Test that {@link ComponentInfo#metaData} data associated with this receiver will only be
     * filled in if the {@link PackageManager#GET_META_DATA} flag is set.
     */
    @Test
    public void testGetInfo_noMetaData_InBroadcastReceiver() throws Exception {
        final ComponentName componentName = new ComponentName(mContext, MockReceiver.class);
        final ActivityInfo info = mPackageManager.getReceiverInfo(componentName,
                PackageManager.ComponentInfoFlags.of(0));
        assertThat(info.metaData).isNull();
    }

    /**
     * Test that {@link ComponentInfo#metaData} data associated with this provider will only be
     * filled in if the {@link PackageManager#GET_META_DATA} flag is set.
     */
    @Test
    public void testGetInfo_noMetaData_InContentProvider() throws Exception {
        final ComponentName componentName = new ComponentName(mContext, MockContentProvider.class);
        final ProviderInfo info = mPackageManager.getProviderInfo(componentName,
                PackageManager.ComponentInfoFlags.of(0));
        assertThat(info.metaData).isNull();
    }

    /**
     * Test that {@link ComponentInfo#metaData} data associated with all components in this
     * package will not be filled in if the {@link PackageManager#GET_META_DATA} flag is not set.
     */
    @Test
    public void testGetInfo_checkMetaData_InPackage() throws Exception {
        final PackageInfo info = mPackageManager.getPackageInfo(PACKAGE_NAME,
                PackageManager.PackageInfoFlags.of(
                        GET_META_DATA | GET_ACTIVITIES | GET_SERVICES | GET_RECEIVERS
                                | GET_PROVIDERS));

        checkMetaData(new PackageItemInfo(info.applicationInfo));
        checkMetaData(new PackageItemInfo(
                findPackageItemOrFail(info.activities, "android.content.cts.MockActivity")));
        checkMetaData(new PackageItemInfo(
                findPackageItemOrFail(info.services, "android.content.cts.MockService")));
        checkMetaData(new PackageItemInfo(
                findPackageItemOrFail(info.receivers, "android.content.cts.MockReceiver")));
        checkMetaData(new PackageItemInfo(
                findPackageItemOrFail(info.providers, "android.content.cts.MockContentProvider")));
    }

    /**
     * Test that {@link ComponentInfo#metaData} data associated with this application will only be
     * filled in if the {@link PackageManager#GET_META_DATA} flag is set.
     */
    @Test
    public void testGetInfo_checkMetaData_InApplication() throws Exception {
        final ApplicationInfo ai = mPackageManager.getApplicationInfo(PACKAGE_NAME,
                PackageManager.ApplicationInfoFlags.of(GET_META_DATA));
        checkMetaData(new PackageItemInfo(ai));
    }

    /**
     * Test that {@link ComponentInfo#metaData} data associated with this activity will only be
     * filled in if the {@link PackageManager#GET_META_DATA} flag is set.
     */
    @Test
    public void testGetInfo_checkMetaData_InActivity() throws Exception {
        final ComponentName componentName = new ComponentName(mContext, MockActivity.class);
        final ActivityInfo ai = mPackageManager.getActivityInfo(componentName,
                PackageManager.ComponentInfoFlags.of(GET_META_DATA));
        checkMetaData(new PackageItemInfo(ai));
    }

    /**
     * Test that {@link ComponentInfo#metaData} data associated with this service will only be
     * filled in if the {@link PackageManager#GET_META_DATA} flag is set.
     */
    @Test
    public void testGetInfo_checkMetaData_InService() throws Exception {
        final ComponentName componentName = new ComponentName(mContext, MockService.class);
        final ServiceInfo info = mPackageManager.getServiceInfo(componentName,
                PackageManager.ComponentInfoFlags.of(GET_META_DATA));
        checkMetaData(new PackageItemInfo(info));
    }

    /**
     * Test that {@link ComponentInfo#metaData} data associated with this receiver will only be
     * filled in if the {@link PackageManager#GET_META_DATA} flag is set.
     */
    @Test
    public void testGetInfo_checkMetaData_InBroadcastReceiver() throws Exception {
        final ComponentName componentName = new ComponentName(mContext, MockReceiver.class);
        final ActivityInfo info = mPackageManager.getReceiverInfo(componentName,
                PackageManager.ComponentInfoFlags.of(GET_META_DATA));
        checkMetaData(new PackageItemInfo(info));
    }

    /**
     * Test that {@link ComponentInfo#metaData} data associated with this provider will only be
     * filled in if the {@link PackageManager#GET_META_DATA} flag is set.
     */
    @Test
    public void testGetInfo_checkMetaData_InContentProvider() throws Exception {
        final ComponentName componentName = new ComponentName(mContext, MockContentProvider.class);
        final ProviderInfo info = mPackageManager.getProviderInfo(componentName,
                PackageManager.ComponentInfoFlags.of(GET_META_DATA));
        checkMetaData(new PackageItemInfo(info));
    }

    private void checkMetaData(@NonNull PackageItemInfo ci)
            throws IOException, XmlPullParserException, NameNotFoundException {
        final Bundle metaData = ci.metaData;
        final Resources res = mPackageManager.getResourcesForApplication(ci.packageName);
        assertWithMessage("No meta-data found").that(metaData).isNotNull();

        assertThat(metaData.getString("android.content.cts.string")).isEqualTo("foo");
        assertThat(metaData.getBoolean("android.content.cts.boolean")).isTrue();
        assertThat(metaData.getInt("android.content.cts.integer")).isEqualTo(100);
        assertThat(metaData.getInt("android.content.cts.color")).isEqualTo(0xff000000);
        assertThat(metaData.getFloat("android.content.cts.float")).isEqualTo(100.1f);
        assertThat(metaData.getInt("android.content.cts.reference")).isEqualTo(R.xml.metadata);

        XmlResourceParser xml = null;
        TypedArray a = null;
        try {
            xml = ci.loadXmlMetaData(mPackageManager, "android.content.cts.reference");
            assertThat(xml).isNotNull();

            int type;
            while ((type = xml.next()) != XmlPullParser.START_TAG
                    && type != XmlPullParser.END_DOCUMENT) {
                // Seek parser to start tag.
            }
            assertThat(type).isEqualTo(XmlPullParser.START_TAG);
            assertThat(xml.getName()).isEqualTo("thedata");

            assertThat(xml.getAttributeValue(null, "rawText")).isEqualTo("some raw text");
            assertThat(xml.getAttributeIntValue(null, "rawColor", 0)).isEqualTo(0xffffff00);
            assertThat(xml.getAttributeValue(null, "rawColor")).isEqualTo("#ffffff00");

            a = res.obtainAttributes(xml, new int[]{android.R.attr.text, android.R.attr.color});
            assertThat(a.getString(0)).isEqualTo("metadata text");
            assertThat(a.getColor(1, 0)).isEqualTo(0xffff0000);
            assertThat(a.getString(1)).isEqualTo("#ffff0000");
        } finally {
            if (a != null) {
                a.recycle();
            }
            if (xml != null) {
                xml.close();
            }
        }
    }

    @Test
    public void testGetApplicationInfo_ApexSupported_MatchesApex() throws Exception {
        assumeTrue("Device doesn't support updating APEX", isUpdatingApexSupported());

        ApplicationInfo ai = mPackageManager.getApplicationInfo(
                SHIM_APEX_PACKAGE_NAME,
                PackageManager.ApplicationInfoFlags.of(PackageManager.MATCH_APEX));
        assertThat(ai.sourceDir).isEqualTo("/system/apex/com.android.apex.cts.shim.apex");
        assertThat(ai.publicSourceDir).isEqualTo(ai.sourceDir);
        assertThat(ai.flags & ApplicationInfo.FLAG_SYSTEM).isEqualTo(ApplicationInfo.FLAG_SYSTEM);
        assertThat(ai.flags & ApplicationInfo.FLAG_INSTALLED)
                .isEqualTo(ApplicationInfo.FLAG_INSTALLED);
    }

    @Test
    public void testGetApplicationInfo_icon_MatchesUseRoundIcon() throws Exception {
        installPackage(HELLO_WORLD_APK);
        final boolean useRoundIcon = mContext.getResources().getBoolean(
                mContext.getResources().getIdentifier("config_useRoundIcon", "bool", "android"));
        final ApplicationInfo info = mPackageManager.getApplicationInfo(HELLO_WORLD_PACKAGE_NAME,
                PackageManager.ApplicationInfoFlags.of(0));
        assertThat(info.icon).isEqualTo((useRoundIcon ? info.roundIconRes : info.iconRes));
    }

    private boolean isUpdatingApexSupported() {
        return SystemProperties.getBoolean("ro.apex.updatable", false);
    }

    private static void assertShimApexInfoIsCorrect(PackageInfo packageInfo) {
        assertThat(packageInfo.packageName).isEqualTo(SHIM_APEX_PACKAGE_NAME);
        assertThat(packageInfo.getLongVersionCode()).isEqualTo(1);
        assertThat(packageInfo.isApex).isTrue();
        assertThat(packageInfo.applicationInfo.sourceDir).isEqualTo(
                "/system/apex/com.android.apex.cts.shim.apex");
        assertThat(packageInfo.applicationInfo.publicSourceDir)
                .isEqualTo(packageInfo.applicationInfo.sourceDir);
        // Verify that legacy mechanism for handling signatures is supported.
        Signature[] pastSigningCertificates =
                packageInfo.signingInfo.getSigningCertificateHistory();
        assertThat(packageInfo.signatures)
                .asList().containsExactly((Object[]) pastSigningCertificates);
    }

    /**
     * Runs a test for all combinations of a set of flags
     *
     * @param flagValues Which flags to use
     * @param test       The test
     */
    public void runTestWithFlags(int[] flagValues, Consumer<Integer> test) {
        for (int i = 0; i < (1 << flagValues.length); i++) {
            int flags = 0;
            for (int j = 0; j < flagValues.length; j++) {
                if ((i & (1 << j)) != 0) {
                    flags |= flagValues[j];
                }
            }
            try {
                test.accept(flags);
            } catch (Throwable t) {
                throw new AssertionError(
                        "Test failed for flags 0x" + String.format("%08x", flags), t);
            }
        }
    }

    /**
     * Test that the MATCH_FACTORY_ONLY flag doesn't add new package names in the result of
     * getInstalledPackages.
     */
    @Test
    public void testGetInstalledPackages_WithFactoryFlag_IsSubset() {
        runTestWithFlags(PACKAGE_INFO_MATCH_FLAGS,
                this::testGetInstalledPackages_WithFactoryFlag_IsSubset);
    }

    public void testGetInstalledPackages_WithFactoryFlag_IsSubset(int flags) {
        List<PackageInfo> packageInfos = mPackageManager.getInstalledPackages(
                PackageManager.PackageInfoFlags.of(flags));
        List<PackageInfo> packageInfos2 = mPackageManager.getInstalledPackages(
                PackageManager.PackageInfoFlags.of(flags | MATCH_FACTORY_ONLY));
        Set<String> supersetNames =
                packageInfos.stream().map(pi -> pi.packageName).collect(Collectors.toSet());

        for (PackageInfo pi : packageInfos2) {
            if (!supersetNames.contains(pi.packageName)) {
                throw new AssertionError(
                        "The subset contains packages that the superset doesn't contain.");
            }
        }
    }

    /**
     * Test that the MATCH_FACTORY_ONLY flag filters out all non-system packages in the result of
     * getInstalledPackages.
     */
    @Test
    public void testGetInstalledPackages_WithFactoryFlag_ImpliesSystem() {
        runTestWithFlags(PACKAGE_INFO_MATCH_FLAGS,
                this::testGetInstalledPackages_WithFactoryFlag_ImpliesSystem);
    }

    public void testGetInstalledPackages_WithFactoryFlag_ImpliesSystem(int flags) {
        List<PackageInfo> packageInfos =
                mPackageManager.getInstalledPackages(
                        PackageManager.PackageInfoFlags.of(flags | MATCH_FACTORY_ONLY));
        for (PackageInfo pi : packageInfos) {
            if (!pi.applicationInfo.isSystemApp()) {
                throw new AssertionError(pi.packageName + " is not a system app.");
            }
        }
    }

    /**
     * Test that we con't have conflicting package names between APK and APEX.
     */
    @Test
    public void testGetInstalledPackages_WithApexFlag_ContainsNoDuplicates() {
        List<PackageInfo> packageInfos = mPackageManager.getInstalledPackages(
                PackageManager.PackageInfoFlags.of(MATCH_APEX));
        final Set<String> apexPackageNames = packageInfos.stream()
                .filter(pi -> pi.isApex).map(pi -> pi.packageName).collect(Collectors.toSet());
        final Set<String> apkPackageNames = packageInfos.stream()
                .filter(pi -> !pi.isApex).map(pi -> pi.packageName).collect(Collectors.toSet());
        for (String packageName : apkPackageNames) {
            if (apexPackageNames.contains(packageName)) {
                expect.withMessage("Conflicting APK package " + packageName + " detected").fail();
            }
        }
    }

    /**
     * Test that the MATCH_FACTORY_ONLY flag doesn't add the same package multiple times since there
     * may be multiple versions of a system package on the device.
     */
    @Test
    public void testGetInstalledPackages_WithFactoryFlag_ContainsNoDuplicates() {
        final Set<String> packageNames = new HashSet<>();
        runTestWithFlags(PACKAGE_INFO_MATCH_FLAGS,
                flags -> testGetInstalledPackages_WithFactoryFlag_ContainsNoDuplicates(flags,
                        packageNames));
    }

    public void testGetInstalledPackages_WithFactoryFlag_ContainsNoDuplicates(int flags,
            Set<String> packageNames) {
        List<PackageInfo> packageInfos =
                mPackageManager.getInstalledPackages(
                        PackageManager.PackageInfoFlags.of(flags | MATCH_FACTORY_ONLY));

        final Set<String> localPackageNames = new HashSet<>();
        for (PackageInfo pi : packageInfos) {
            final String packageName = pi.packageName;
            // Duplicate: already in local.
            // Dedup error messages: not in global.
            if (!localPackageNames.add(pi.packageName) && packageNames.add(packageName)) {
                expect.withMessage("Duplicate package " + packageName + " detected").fail();
            }
        }
    }

    @Test
    public void testInstallTestOnlyPackagePermission_onlyGrantedToShell() {
        List<PackageInfo> packages = mPackageManager.getPackagesHoldingPermissions(
                new String[]{INSTALL_TEST_ONLY_PACKAGE}, PackageManager.PackageInfoFlags.of(0));

        assertThat(packages).hasSize(1);
        assertThat(packages.get(0).packageName).isEqualTo(SHELL_PACKAGE_NAME);
    }

    @Test
    public void testInstall_withLongPackageName_fail() {
        assertThat(installPackage(LONG_PACKAGE_NAME_APK)).isFalse();
    }

    @Test
    public void testInstall_withLongSharedUserId_fail() {
        assertThat(installPackage(LONG_SHARED_USER_ID_APK)).isFalse();
    }

    @Test
    public void testInstall_withMaxPackageName_success() {
        assertThat(installPackage(MAX_PACKAGE_NAME_APK)).isTrue();
    }

    @Test
    public void testInstall_withMaxSharedUserId_success() {
        assertThat(installPackage(MAX_SHARED_USER_ID_APK)).isTrue();
    }

    @Test
    public void testInstall_withLongUsesPermissionName_fail() {
        String expectedErrorCode = "INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION";
        String expectedErrorMessage =
                "String length limit exceeded for attribute in uses-permission";

        String installResult = installPackageWithResult(LONG_USES_PERMISSION_NAME_APK);

        assertThat(installResult).contains(expectedErrorCode);
        assertThat(installResult).contains(expectedErrorMessage);
    }

    private String installPackageWithResult(String apkPath) {
        return SystemUtil.runShellCommand("pm install -t " + apkPath);
    }

    private boolean installPackage(String apkPath) {
        return SystemUtil.runShellCommand(
                "pm install -t " + apkPath).equals("Success\n");
    }

    private boolean addSplitDontKill(String packageName, String splitPath) {
        return SystemUtil.runShellCommand(
                "pm install-streaming -p " + packageName + " --dont-kill -t " + splitPath).equals(
                "Success\n");
    }

    private void uninstallPackage(String packageName) {
        SystemUtil.runShellCommand("pm uninstall " + packageName);
    }

    @Test
    public void testGetLaunchIntentSenderForPackage() throws Exception {
        final Instrumentation.ActivityMonitor monitor = new Instrumentation.ActivityMonitor(
                LauncherMockActivity.class.getName(), null /* result */, false /* block */);
        mInstrumentation.addMonitor(monitor);

        try {
            final IntentSender intentSender = mPackageManager.getLaunchIntentSenderForPackage(
                    PACKAGE_NAME);
            assertThat(intentSender.getCreatorPackage()).isEqualTo(PACKAGE_NAME);
            assertThat(intentSender.getCreatorUid()).isEqualTo(mContext.getApplicationInfo().uid);

            sendIntent(intentSender);
            final Activity activity = monitor.waitForActivityWithTimeout(TIMEOUT_MS);
            assertThat(activity).isNotNull();
            activity.finish();
        } finally {
            mInstrumentation.removeMonitor(monitor);
        }
    }

    @Test(expected = IntentSender.SendIntentException.class)
    public void testGetLaunchIntentSenderForPackage_noMainActivity() throws Exception {
        assertThat(installPackage(EMPTY_APP_APK)).isTrue();
        final PackageInfo packageInfo = mPackageManager.getPackageInfo(EMPTY_APP_PACKAGE_NAME,
                PackageManager.PackageInfoFlags.of(0));
        assertThat(packageInfo.packageName).isEqualTo(EMPTY_APP_PACKAGE_NAME);
        final Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setPackage(EMPTY_APP_PACKAGE_NAME);
        assertThat(mPackageManager.queryIntentActivities(intent,
                PackageManager.ResolveInfoFlags.of(0))).isEmpty();

        final IntentSender intentSender = mPackageManager.getLaunchIntentSenderForPackage(
                EMPTY_APP_PACKAGE_NAME);
        assertThat(intentSender.getCreatorPackage()).isEqualTo(PACKAGE_NAME);
        assertThat(intentSender.getCreatorUid()).isEqualTo(mContext.getApplicationInfo().uid);

        sendIntent(intentSender);
    }

    @Test(expected = IntentSender.SendIntentException.class)
    public void testGetLaunchIntentSenderForPackage_packageNotExist() throws Exception {
        try {
            mPackageManager.getPackageInfo(EMPTY_APP_PACKAGE_NAME,
                    PackageManager.PackageInfoFlags.of(0));
            fail(EMPTY_APP_PACKAGE_NAME + " should not exist in the device");
        } catch (NameNotFoundException e) {
        }
        final IntentSender intentSender = mPackageManager.getLaunchIntentSenderForPackage(
                EMPTY_APP_PACKAGE_NAME);
        assertThat(intentSender.getCreatorPackage()).isEqualTo(PACKAGE_NAME);
        assertThat(intentSender.getCreatorUid()).isEqualTo(mContext.getApplicationInfo().uid);

        sendIntent(intentSender);
    }

    @Test
    public void testDefaultHomeActivity_doesntChange_whenInstallAnotherLauncher() throws Exception {
        final Intent homeIntent = new Intent(Intent.ACTION_MAIN)
                .addCategory(Intent.CATEGORY_HOME);
        final String currentHomeActivity =
                mPackageManager.resolveActivity(homeIntent,
                        PackageManager.ResolveInfoFlags.of(0)).activityInfo.name;

        // Install another launcher app.
        assertThat(installPackage(MOCK_LAUNCHER_APK)).isTrue();

        // There is an async operation to re-set the default home activity in Role with no way
        // to listen for completion once a package installed, so poll until the default home
        // activity is set.
        PollingCheck.waitFor(() -> currentHomeActivity.equals(
                mPackageManager.resolveActivity(homeIntent,
                        PackageManager.ResolveInfoFlags.of(0)).activityInfo.name));
        final List<String> homeApps =
                mPackageManager.queryIntentActivities(homeIntent,
                                PackageManager.ResolveInfoFlags.of(0)).stream()
                        .map(i -> i.activityInfo.packageName).collect(Collectors.toList());
        assertThat(homeApps.contains(MOCK_LAUNCHER_PACKAGE_NAME)).isTrue();
    }

    @Test
    public void setComponentEnabledSetting_nonExistentPackage_withoutPermission() {
        final ComponentName componentName = ComponentName.createRelative(
                NON_EXISTENT_PACKAGE_NAME, "ClassName");
        assertThrows(SecurityException.class, () -> mPackageManager.setComponentEnabledSetting(
                componentName, COMPONENT_ENABLED_STATE_ENABLED, 0 /* flags */));
    }

    @Test
    public void setComponentEnabledSetting_nonExistentPackage_hasPermission() {
        final ComponentName componentName = ComponentName.createRelative(
                NON_EXISTENT_PACKAGE_NAME, "ClassName");
        mInstrumentation.getUiAutomation().adoptShellPermissionIdentity(
                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);

        try {
            assertThrows(IllegalArgumentException.class,
                    () -> mPackageManager.setComponentEnabledSetting(componentName,
                            COMPONENT_ENABLED_STATE_ENABLED, 0 /* flags */));
        } finally {
            mInstrumentation.getUiAutomation().dropShellPermissionIdentity();
        }
    }

    @Test
    public void loadApplicationLabel_withLongLabelName_truncated() throws Exception {
        assertThat(installPackage(LONG_LABEL_NAME_APK)).isTrue();
        final ApplicationInfo info = mPackageManager.getApplicationInfo(
                EMPTY_APP_PACKAGE_NAME, PackageManager.ApplicationInfoFlags.of(0));
        final CharSequence resLabel = mPackageManager.getText(
                EMPTY_APP_PACKAGE_NAME, info.labelRes, info);

        assertThat(resLabel.length()).isGreaterThan(MAX_SAFE_LABEL_LENGTH);
        assertThat(info.loadLabel(mPackageManager).length()).isEqualTo(MAX_SAFE_LABEL_LENGTH);
    }

    @Test
    public void loadComponentLabel_withLongLabelName_truncated() throws Exception {
        assertThat(installPackage(LONG_LABEL_NAME_APK)).isTrue();
        final ComponentName componentName = ComponentName.createRelative(
                EMPTY_APP_PACKAGE_NAME, ".MockActivity");
        final ApplicationInfo appInfo = mPackageManager.getApplicationInfo(
                EMPTY_APP_PACKAGE_NAME, PackageManager.ApplicationInfoFlags.of(0));
        final ActivityInfo activityInfo = mPackageManager.getActivityInfo(
                componentName, PackageManager.ComponentInfoFlags.of(0));
        final CharSequence resLabel = mPackageManager.getText(
                EMPTY_APP_PACKAGE_NAME, activityInfo.labelRes, appInfo);

        assertThat(resLabel.length()).isGreaterThan(MAX_SAFE_LABEL_LENGTH);
        assertThat(activityInfo.loadLabel(mPackageManager).length())
                .isEqualTo(MAX_SAFE_LABEL_LENGTH);
    }

    @Test
    public void setComponentEnabledSettings_withDuplicatedComponent() {
        final List<ComponentEnabledSetting> enabledSettings = List.of(
                new ComponentEnabledSetting(
                        ACTIVITY_COMPONENT, COMPONENT_ENABLED_STATE_DISABLED, DONT_KILL_APP),
                new ComponentEnabledSetting(
                        ACTIVITY_COMPONENT, COMPONENT_ENABLED_STATE_DISABLED, DONT_KILL_APP));

        assertThrows(IllegalArgumentException.class,
                () -> mPackageManager.setComponentEnabledSettings(enabledSettings));
    }

    @Test
    public void setComponentEnabledSettings_flagDontKillAppConflict() {
        final List<ComponentEnabledSetting> enabledSettings = List.of(
                new ComponentEnabledSetting(
                        ACTIVITY_COMPONENT, COMPONENT_ENABLED_STATE_DISABLED, DONT_KILL_APP),
                new ComponentEnabledSetting(
                        SERVICE_COMPONENT, COMPONENT_ENABLED_STATE_DISABLED, 0));

        assertThrows(IllegalArgumentException.class,
                () -> mPackageManager.setComponentEnabledSettings(enabledSettings));
    }

    @Test
    public void setComponentEnabledSettings_disableSelfAndStubApp_withoutPermission() {
        final List<ComponentEnabledSetting> enabledSettings = List.of(
                new ComponentEnabledSetting(
                        ACTIVITY_COMPONENT, COMPONENT_ENABLED_STATE_DISABLED, DONT_KILL_APP),
                new ComponentEnabledSetting(
                        STUB_ACTIVITY_COMPONENT, COMPONENT_ENABLED_STATE_DISABLED, 0));

        assertThrows(SecurityException.class,
                () -> mPackageManager.setComponentEnabledSettings(enabledSettings));
    }

    @Test
    public void setComponentEnabledSettings_disableSelf() throws Exception {
        final int activityState = mPackageManager.getComponentEnabledSetting(ACTIVITY_COMPONENT);
        final int serviceState = mPackageManager.getComponentEnabledSetting(SERVICE_COMPONENT);
        assertThat(activityState).isAnyOf(
                COMPONENT_ENABLED_STATE_DEFAULT, COMPONENT_ENABLED_STATE_ENABLED);
        assertThat(serviceState).isAnyOf(
                COMPONENT_ENABLED_STATE_DEFAULT, COMPONENT_ENABLED_STATE_ENABLED);

        try {
            final List<ComponentEnabledSetting> enabledSettings = List.of(
                    new ComponentEnabledSetting(
                            ACTIVITY_COMPONENT, COMPONENT_ENABLED_STATE_DISABLED, DONT_KILL_APP),
                    new ComponentEnabledSetting(
                            SERVICE_COMPONENT, COMPONENT_ENABLED_STATE_DISABLED, DONT_KILL_APP));
            setComponentEnabledSettingsAndWaitForBroadcasts(enabledSettings);
        } finally {
            final List<ComponentEnabledSetting> enabledSettings = List.of(
                    new ComponentEnabledSetting(ACTIVITY_COMPONENT, activityState, DONT_KILL_APP),
                    new ComponentEnabledSetting(SERVICE_COMPONENT, serviceState, DONT_KILL_APP));
            setComponentEnabledSettingsAndWaitForBroadcasts(enabledSettings);
        }
    }

    @Test
    public void setComponentEnabledSettings_disableSelfAndStubApp_killStubApp()
            throws Exception {
        final int activityState = mPackageManager.getComponentEnabledSetting(ACTIVITY_COMPONENT);
        final int stubState = mPackageManager.getComponentEnabledSetting(STUB_ACTIVITY_COMPONENT);
        assertThat(activityState).isAnyOf(
                COMPONENT_ENABLED_STATE_DEFAULT, COMPONENT_ENABLED_STATE_ENABLED);
        assertThat(stubState).isAnyOf(
                COMPONENT_ENABLED_STATE_DEFAULT, COMPONENT_ENABLED_STATE_ENABLED);

        final Intent intent = new Intent();
        intent.setComponent(STUB_SERVICE_COMPONENT);
        final AtomicBoolean killed = new AtomicBoolean();
        mServiceTestRule.bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                killed.set(true);
            }
        }, Context.BIND_AUTO_CREATE);
        mInstrumentation.getUiAutomation().adoptShellPermissionIdentity(
                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);

        try {
            final List<ComponentEnabledSetting> enabledSettings = List.of(
                    new ComponentEnabledSetting(
                            ACTIVITY_COMPONENT, COMPONENT_ENABLED_STATE_DISABLED, DONT_KILL_APP),
                    new ComponentEnabledSetting(
                            STUB_ACTIVITY_COMPONENT, COMPONENT_ENABLED_STATE_DISABLED, 0));
            setComponentEnabledSettingsAndWaitForBroadcasts(enabledSettings);
            TestUtils.waitUntil("Waiting for the process " + STUB_PACKAGE_NAME
                    + " to die", () -> killed.get());
        } finally {
            final List<ComponentEnabledSetting> enabledSettings = List.of(
                    new ComponentEnabledSetting(ACTIVITY_COMPONENT, activityState, DONT_KILL_APP),
                    new ComponentEnabledSetting(STUB_ACTIVITY_COMPONENT, stubState, 0));
            setComponentEnabledSettingsAndWaitForBroadcasts(enabledSettings);
            mInstrumentation.getUiAutomation().dropShellPermissionIdentity();
        }
    }

    @Test
    public void setComponentEnabledSettings_noStateChanged_noBroadcastReceived() {
        final int activityState = mPackageManager.getComponentEnabledSetting(ACTIVITY_COMPONENT);
        final int serviceState = mPackageManager.getComponentEnabledSetting(SERVICE_COMPONENT);
        final List<ComponentEnabledSetting> enabledSettings = List.of(
                new ComponentEnabledSetting(ACTIVITY_COMPONENT, activityState, DONT_KILL_APP),
                new ComponentEnabledSetting(SERVICE_COMPONENT, serviceState, DONT_KILL_APP));

        assertThrows(TimeoutException.class,
                () -> setComponentEnabledSettingsAndWaitForBroadcasts(enabledSettings));
    }

    @Test
    public void setComponentEnabledSetting_disableMultiplePackagesNoKill() throws Exception {
        final int activityState = mPackageManager.getComponentEnabledSetting(ACTIVITY_COMPONENT);
        final int serviceState = mPackageManager.getComponentEnabledSetting(SERVICE_COMPONENT);
        assertThat(installPackage(MOCK_LAUNCHER_APK)).isTrue();
        final List<ComponentEnabledSetting> settings = List.of(
                new ComponentEnabledSetting(RESET_ENABLED_SETTING_ACTIVITY_COMPONENT,
                        COMPONENT_ENABLED_STATE_DISABLED, DONT_KILL_APP),
                new ComponentEnabledSetting(RESET_ENABLED_SETTING_RECEIVER_COMPONENT,
                        COMPONENT_ENABLED_STATE_DISABLED, DONT_KILL_APP),
                new ComponentEnabledSetting(RESET_ENABLED_SETTING_SERVICE_COMPONENT,
                        COMPONENT_ENABLED_STATE_DISABLED, DONT_KILL_APP),
                new ComponentEnabledSetting(RESET_ENABLED_SETTING_PROVIDER_COMPONENT,
                        COMPONENT_ENABLED_STATE_DISABLED, DONT_KILL_APP),
                new ComponentEnabledSetting(
                        ACTIVITY_COMPONENT, COMPONENT_ENABLED_STATE_DISABLED, DONT_KILL_APP),
                new ComponentEnabledSetting(
                        SERVICE_COMPONENT, COMPONENT_ENABLED_STATE_DISABLED, DONT_KILL_APP));

        try {
            mInstrumentation.getUiAutomation().adoptShellPermissionIdentity(
                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
            setComponentEnabledSettingsAndWaitForBroadcasts(settings);
        } finally {
            final List<ComponentEnabledSetting> enabledSettings = List.of(
                    new ComponentEnabledSetting(ACTIVITY_COMPONENT, activityState, DONT_KILL_APP),
                    new ComponentEnabledSetting(SERVICE_COMPONENT, serviceState, DONT_KILL_APP));
            setComponentEnabledSettingsAndWaitForBroadcasts(enabledSettings);
            mInstrumentation.getUiAutomation().dropShellPermissionIdentity();
        }
    }

    @Test
    public void clearApplicationUserData_resetComponentEnabledSettings() throws Exception {
        assertThat(installPackage(MOCK_LAUNCHER_APK)).isTrue();
        final List<ComponentEnabledSetting> settings = List.of(
                new ComponentEnabledSetting(RESET_ENABLED_SETTING_ACTIVITY_COMPONENT,
                        COMPONENT_ENABLED_STATE_ENABLED, 0 /* flags */),
                new ComponentEnabledSetting(RESET_ENABLED_SETTING_RECEIVER_COMPONENT,
                        COMPONENT_ENABLED_STATE_ENABLED, 0 /* flags */),
                new ComponentEnabledSetting(RESET_ENABLED_SETTING_SERVICE_COMPONENT,
                        COMPONENT_ENABLED_STATE_ENABLED, 0 /* flags */),
                new ComponentEnabledSetting(RESET_ENABLED_SETTING_PROVIDER_COMPONENT,
                        COMPONENT_ENABLED_STATE_ENABLED, 0 /* flags */));

        try {
            mInstrumentation.getUiAutomation().adoptShellPermissionIdentity(
                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
            // update component enabled settings
            setComponentEnabledSettingsAndWaitForBroadcasts(settings);

            clearApplicationUserData(MOCK_LAUNCHER_PACKAGE_NAME);

            assertThat(mPackageManager
                    .getComponentEnabledSetting(RESET_ENABLED_SETTING_ACTIVITY_COMPONENT))
                    .isEqualTo(COMPONENT_ENABLED_STATE_DEFAULT);
            assertThat(mPackageManager
                    .getComponentEnabledSetting(RESET_ENABLED_SETTING_RECEIVER_COMPONENT))
                    .isEqualTo(COMPONENT_ENABLED_STATE_DEFAULT);
            assertThat(mPackageManager
                    .getComponentEnabledSetting(RESET_ENABLED_SETTING_SERVICE_COMPONENT))
                    .isEqualTo(COMPONENT_ENABLED_STATE_DEFAULT);
            assertThat(mPackageManager
                    .getComponentEnabledSetting(RESET_ENABLED_SETTING_PROVIDER_COMPONENT))
                    .isEqualTo(COMPONENT_ENABLED_STATE_DEFAULT);
        } finally {
            mInstrumentation.getUiAutomation().dropShellPermissionIdentity();
        }
    }

    private void setComponentEnabledSettingsAndWaitForBroadcasts(
            List<ComponentEnabledSetting> enabledSettings)
            throws InterruptedException, TimeoutException {
        final List<ComponentName> componentsToWait = enabledSettings.stream()
                .map(enabledSetting -> enabledSetting.getComponentName())
                .collect(Collectors.toList());
        final IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
        filter.addDataScheme("package");
        final CountDownLatch latch = new CountDownLatch(1 /* count */);
        final BroadcastReceiver br = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                final String packageName = intent.getData() != null
                        ? intent.getData().getSchemeSpecificPart() : null;
                final String[] receivedComponents = intent.getStringArrayExtra(
                        Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
                if (packageName == null || receivedComponents == null) {
                    return;
                }
                for (String componentString : receivedComponents) {
                    componentsToWait.remove(new ComponentName(packageName, componentString));
                }
                if (componentsToWait.isEmpty()) {
                    latch.countDown();
                }
            }
        };
        mContext.registerReceiver(br, filter, RECEIVER_EXPORTED);
        try {
            mPackageManager.setComponentEnabledSettings(enabledSettings);
            if (!latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
                throw new TimeoutException("Package changed broadcasts for " + componentsToWait
                        + " not received in " + TIMEOUT_MS + "ms");
            }
            for (ComponentEnabledSetting enabledSetting : enabledSettings) {
                assertThat(mPackageManager.getComponentEnabledSetting(
                        enabledSetting.getComponentName()))
                        .isEqualTo(enabledSetting.getEnabledState());
            }
        } finally {
            mContext.unregisterReceiver(br);
        }
    }

    private void clearApplicationUserData(String packageName) {
        final StringBuilder cmd = new StringBuilder("pm clear --user ");
        cmd.append(UserHandle.myUserId()).append(" ");
        cmd.append(packageName);
        SystemUtil.runShellCommand(cmd.toString());
    }

    @Test
    public void testPrebuiltSharedLibraries_existOnDevice() {
        final List<SharedLibraryInfo> infos =
                mPackageManager.getSharedLibraries(PackageManager.PackageInfoFlags.of(0)).stream()
                        .filter(info -> info.isBuiltin() && !info.isNative())
                        .collect(Collectors.toList());
        assertThat(infos).isNotEmpty();

        final List<SharedLibraryInfo> fileNotExistInfos = infos.stream()
                .filter(info -> !(new File(info.getPath()).exists())).collect(
                        Collectors.toList());
        assertThat(fileNotExistInfos).isEmpty();
    }

    @Test
    public void testInstallUpdate_applicationIsKilled() throws Exception {
        final Intent intent = new Intent();
        intent.setComponent(STUB_SERVICE_COMPONENT);
        final AtomicBoolean killed = new AtomicBoolean();
        mServiceTestRule.bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                killed.set(true);
            }
        }, Context.BIND_AUTO_CREATE);

        installPackage(STUB_PACKAGE_APK);
        // The application should be killed after updating.
        TestUtils.waitUntil("Waiting for the process " + STUB_PACKAGE_NAME + " to die",
                10 /* timeoutSecond */, () -> killed.get());
    }

    @Test
    public void testInstallUpdate_dontKill_applicationIsNotKilled() throws Exception {
        installPackage(STUB_PACKAGE_APK);

        final Intent intent = new Intent();
        intent.setComponent(STUB_SERVICE_COMPONENT);
        final AtomicBoolean killed = new AtomicBoolean();
        mServiceTestRule.bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                killed.set(true);
            }
        }, Context.BIND_AUTO_CREATE);

        addSplitDontKill(STUB_PACKAGE_NAME, STUB_PACKAGE_SPLIT);
        // The application shouldn't be killed after updating with --dont-kill.
        assertThrows(AssertionFailedError.class,
                () -> TestUtils.waitUntil(
                        "Waiting for the process " + STUB_PACKAGE_NAME + " to die",
                        10 /* timeoutSecond */, () -> killed.get()));
    }

    @Test
    public void testPackageInfoFlags() {
        final long rawFlags = PackageManager.GET_ACTIVITIES | PackageManager.GET_GIDS
                | PackageManager.GET_CONFIGURATIONS;
        assertEquals(rawFlags, PackageManager.PackageInfoFlags.of(rawFlags).getValue());
    }

    @Test
    public void testApplicationInfoFlags() {
        final long rawFlags = PackageManager.GET_SHARED_LIBRARY_FILES
                | PackageManager.MATCH_UNINSTALLED_PACKAGES;
        assertEquals(rawFlags, PackageManager.ApplicationInfoFlags.of(rawFlags).getValue());
    }

    @Test
    public void testResolveInfoFlags() {
        final long rawFlags = PackageManager.MATCH_DIRECT_BOOT_AWARE
                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
                | PackageManager.MATCH_SYSTEM_ONLY;
        assertEquals(rawFlags, PackageManager.ResolveInfoFlags.of(rawFlags).getValue());
    }

    @Test
    public void testComponentInfoFlags() {
        final long rawFlags = PackageManager.GET_META_DATA;
        assertEquals(rawFlags, PackageManager.ComponentInfoFlags.of(rawFlags).getValue());
    }

    @Test
    public void testDeleteDexopt_withoutShellIdentity() throws Exception {
        assertThat(runCommand("pm delete-dexopt " + PACKAGE_NAME))
                .contains(SecurityException.class.getName());
    }

    @Test
    public void testSettingAndReserveCopyVerityProtected() throws Exception {
        File systemDir = new File(Environment.getDataDirectory(), "system");
        File settings = new File(systemDir, "packages.xml");
        File settingsReserveCopy = new File(systemDir, "packages.xml.reservecopy");

        // Primary.
        assertTrue(settings.exists());
        // Reserve copy.
        assertTrue(settingsReserveCopy.exists());
        // Temporary backup.
        assertFalse(new File(systemDir, "packages-backup.xml").exists());

        assumeTrue(VerityUtils.isFsVeritySupported());
        assertTrue(VerityUtils.hasFsverity(settings.getAbsolutePath()));
        assertTrue(VerityUtils.hasFsverity(settingsReserveCopy.getAbsolutePath()));
    }

    private static String runCommand(String cmd) throws Exception {
        final Process process = Runtime.getRuntime().exec(cmd);
        final StringBuilder output = new StringBuilder();
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(process.getInputStream()));
        reader.lines().forEach(line -> output.append(line));
        reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        reader.lines().forEach(line -> output.append(line));
        process.waitFor();
        return output.toString();
    }

    @Test
    public void testNewAppInstalledNotificationEnabled() {
        SystemUtil.runWithShellPermissionIdentity(mInstrumentation.getUiAutomation(), () -> {
            Settings.Global.putString(mContext.getContentResolver(),
                    Settings.Global.SHOW_NEW_APP_INSTALLED_NOTIFICATION_ENABLED, "1" /* true */);
        }, WRITE_SECURE_SETTINGS);

        assertEquals(true, mPackageManager.shouldShowNewAppInstalledNotification());

    }

    @Test
    public void testCanUserUninstall_setToTrue_returnsTrue() throws RemoteException {
        SystemUtil.runWithShellPermissionIdentity(mInstrumentation.getUiAutomation(), () -> {
            IPackageManager iPm = ActivityThread.getPackageManager();
            iPm.setBlockUninstallForUser(PACKAGE_NAME, true, USER_CURRENT);
        }, DELETE_PACKAGES);

        assertEquals(true, mPackageManager.canUserUninstall(PACKAGE_NAME, CURRENT));
    }

    private void sendIntent(IntentSender intentSender) throws IntentSender.SendIntentException {
        intentSender.sendIntent(mContext, 0 /* code */, null /* intent */,
                null /* onFinished */, null /* handler */, null /* requiredPermission */,
                ActivityOptions.makeBasic().setPendingIntentBackgroundActivityStartMode(
                        ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED).toBundle());
    }
}