summaryrefslogtreecommitdiff
path: root/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/ClientTest.java
blob: 04603b3f9ed8cabeac9ea69bea3e9ba2d1618813 (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
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.cts.ephemeralapp1;

import static android.media.AudioFormat.CHANNEL_IN_MONO;
import static android.media.AudioFormat.ENCODING_PCM_16BIT;
import static android.media.MediaRecorder.AudioSource.MIC;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertThrows;

import android.Manifest;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.SearchManager;
import android.app.SearchableInfo;
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.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.pm.ChangedPackages;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.location.Criteria;
import android.location.LocationManager;
import android.media.AudioRecord;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import android.platform.test.annotations.AsbSecurityTest;

import com.android.cts.util.TestResult;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

@RunWith(AndroidJUnit4.class)
public class ClientTest {
    /** Action to start normal test activities */
    private static final String ACTION_START_NORMAL =
            "com.android.cts.ephemeraltest.START_NORMAL";
    /** Action to start normal, exposed test activities */
    private static final String ACTION_START_EXPOSED =
            "com.android.cts.ephemeraltest.START_EXPOSED";
    /** Action to start ephemeral test activities */
    private static final String ACTION_START_EPHEMERAL =
            "com.android.cts.ephemeraltest.START_EPHEMERAL";
    /** Action to start private ephemeral test activities */
    private static final String ACTION_START_EPHEMERAL_PRIVATE =
            "com.android.cts.ephemeraltest.START_EPHEMERAL_PRIVATE";
    private static final String ACTION_START_EPHEMERAL_ACTIVITY =
            "com.android.cts.ephemeraltest.START_OTHER_EPHEMERAL";
    /** Action to query for test activities */
    private static final String ACTION_QUERY =
            "com.android.cts.ephemeraltest.QUERY";
    private static final String EXTRA_ACTIVITY_NAME =
            "com.android.cts.ephemeraltest.EXTRA_ACTIVITY_NAME";
    private static final String EXTRA_ACTIVITY_RESULT =
            "com.android.cts.ephemeraltest.EXTRA_ACTIVITY_RESULT";

    private BroadcastReceiver mReceiver;
    private PhoneStateListener mPhoneStateListener;
    private final SynchronousQueue<TestResult> mResultQueue = new SynchronousQueue<>();

    @Before
    public void setUp() throws Exception {
        final IntentFilter filter =
                new IntentFilter("com.android.cts.ephemeraltest.START_ACTIVITY");
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        mReceiver = new ActivityBroadcastReceiver(mResultQueue);
        InstrumentationRegistry.getContext()
                .registerReceiver(mReceiver, filter, Context.RECEIVER_VISIBLE_TO_INSTANT_APPS);
    }

    @After
    public void tearDown() throws Exception {
        InstrumentationRegistry.getContext().unregisterReceiver(mReceiver);
    }

    @Test
    public void testQuery() throws Exception {
        // query normal activities
        {
            final Intent queryIntent = new Intent(ACTION_QUERY);
            final List<ResolveInfo> resolveInfo = InstrumentationRegistry.getContext()
                    .getPackageManager().queryIntentActivities(queryIntent, 0 /*flags*/);
            if (resolveInfo == null || resolveInfo.size() == 0) {
                fail("didn't resolve any intents");
            }
            assertThat(resolveInfo.size(), is(2));
            assertThat(resolveInfo.get(0).activityInfo.packageName,
                    is("com.android.cts.ephemeralapp1"));
            assertThat(resolveInfo.get(0).activityInfo.name,
                    is("com.android.cts.ephemeralapp1.EphemeralActivity"));
            assertThat(resolveInfo.get(0).isInstantAppAvailable,
                    is(true));
            assertThat(resolveInfo.get(1).activityInfo.packageName,
                    is("com.android.cts.normalapp"));
            assertThat(resolveInfo.get(1).activityInfo.name,
                    is("com.android.cts.normalapp.ExposedActivity"));
            assertThat(resolveInfo.get(1).isInstantAppAvailable,
                    is(false));
        }

        // query normal activities; directed package
        {
            final Intent queryIntent = new Intent(ACTION_QUERY);
            final List<ResolveInfo> resolveInfo = InstrumentationRegistry.getContext()
                    .getPackageManager().queryIntentActivities(queryIntent, 0 /*flags*/);
            if (resolveInfo == null || resolveInfo.size() == 0) {
                fail("didn't resolve any intents");
            }
            assertThat(resolveInfo.size(), is(2));
            assertThat(resolveInfo.get(0).activityInfo.packageName,
                    is("com.android.cts.ephemeralapp1"));
            assertThat(resolveInfo.get(0).activityInfo.name,
                    is("com.android.cts.ephemeralapp1.EphemeralActivity"));
            assertThat(resolveInfo.get(0).isInstantAppAvailable,
                    is(true));
            assertThat(resolveInfo.get(1).activityInfo.packageName,
                    is("com.android.cts.normalapp"));
            assertThat(resolveInfo.get(1).activityInfo.name,
                    is("com.android.cts.normalapp.ExposedActivity"));
            assertThat(resolveInfo.get(1).isInstantAppAvailable,
                    is(false));
        }

        // query normal activities; directed component
        {
            final Intent queryIntent = new Intent(ACTION_QUERY);
            final List<ResolveInfo> resolveInfo = InstrumentationRegistry.getContext()
                    .getPackageManager().queryIntentActivities(queryIntent, 0 /*flags*/);
            if (resolveInfo == null || resolveInfo.size() == 0) {
                fail("didn't resolve any intents");
            }
            assertThat(resolveInfo.size(), is(2));
            assertThat(resolveInfo.get(0).activityInfo.packageName,
                    is("com.android.cts.ephemeralapp1"));
            assertThat(resolveInfo.get(0).activityInfo.name,
                    is("com.android.cts.ephemeralapp1.EphemeralActivity"));
            assertThat(resolveInfo.get(0).isInstantAppAvailable,
                    is(true));
            assertThat(resolveInfo.get(1).activityInfo.packageName,
                    is("com.android.cts.normalapp"));
            assertThat(resolveInfo.get(1).activityInfo.name,
                    is("com.android.cts.normalapp.ExposedActivity"));
            assertThat(resolveInfo.get(1).isInstantAppAvailable,
                    is(false));
        }

        // query own ephemeral application activities with a web URI
        {
            final Intent queryIntent = new Intent(Intent.ACTION_VIEW);
            queryIntent.addCategory(Intent.CATEGORY_BROWSABLE);
            queryIntent.setData(Uri.parse("https://cts.google.com/ephemeral"));
            final List<ResolveInfo> resolveInfo = InstrumentationRegistry.getContext()
                    .getPackageManager().queryIntentActivities(
                            queryIntent, PackageManager.GET_RESOLVED_FILTER);
            if (resolveInfo == null || resolveInfo.size() == 0) {
                fail("didn't resolve any intents");
            }
            for (ResolveInfo info: resolveInfo) {
                assertThat(info.filter, is(notNullValue()));
                if (handlesAllWebData(info.filter)) {
                    continue;
                }
                assertThat(info.activityInfo.packageName,
                        is("com.android.cts.ephemeralapp1"));
                assertThat(info.activityInfo.name,
                        is("com.android.cts.ephemeralapp1.EphemeralActivity"));
                assertThat(info.isInstantAppAvailable,
                        is(true));
            }
        }

        // query other ephemeral application activities with a web URI
        {
            final Intent queryIntent = new Intent(Intent.ACTION_VIEW);
            queryIntent.addCategory(Intent.CATEGORY_BROWSABLE);
            queryIntent.setData(Uri.parse("https://cts.google.com/other"));
            final List<ResolveInfo> resolveInfo = InstrumentationRegistry.getContext()
                    .getPackageManager().queryIntentActivities(
                            queryIntent, PackageManager.GET_RESOLVED_FILTER);
            if (resolveInfo == null || resolveInfo.size() == 0) {
                fail("didn't resolve any intents");
            }
            for (ResolveInfo info: resolveInfo) {
                assertThat(info.filter, is(notNullValue()));
                if (handlesAllWebData(info.filter)) {
                    continue;
                }
                fail("resolution should have only matched browsers");
            }
        }

        // query services
        {
            final Intent queryIntent = new Intent(ACTION_QUERY);
            final List<ResolveInfo> resolveInfo = InstrumentationRegistry
                    .getContext().getPackageManager().queryIntentServices(queryIntent, 0 /*flags*/);
            if (resolveInfo == null || resolveInfo.size() == 0) {
                fail("didn't resolve any intents");
            }
            assertThat(resolveInfo.size(), is(2));
            assertThat(resolveInfo.get(0).serviceInfo.packageName,
                    is("com.android.cts.ephemeralapp1"));
            assertThat(resolveInfo.get(0).serviceInfo.name,
                    is("com.android.cts.ephemeralapp1.EphemeralService"));
            assertThat(resolveInfo.get(1).serviceInfo.packageName,
                    is("com.android.cts.normalapp"));
            assertThat(resolveInfo.get(1).serviceInfo.name,
                    is("com.android.cts.normalapp.ExposedService"));
            assertThat(resolveInfo.get(1).isInstantAppAvailable,
                    is(false));
        }

        // query services; directed package
        {
            final Intent queryIntent = new Intent(ACTION_QUERY);
            queryIntent.setPackage("com.android.cts.ephemeralapp1");
            final List<ResolveInfo> resolveInfo = InstrumentationRegistry
                    .getContext().getPackageManager().queryIntentServices(queryIntent, 0 /*flags*/);
            if (resolveInfo == null || resolveInfo.size() == 0) {
                fail("didn't resolve any intents");
            }
            assertThat(resolveInfo.size(), is(1));
            assertThat(resolveInfo.get(0).serviceInfo.packageName,
                    is("com.android.cts.ephemeralapp1"));
            assertThat(resolveInfo.get(0).serviceInfo.name,
                    is("com.android.cts.ephemeralapp1.EphemeralService"));
        }

        // query services; directed component
        {
            final Intent queryIntent = new Intent(ACTION_QUERY);
            queryIntent.setComponent(
                    new ComponentName("com.android.cts.ephemeralapp1",
                            "com.android.cts.ephemeralapp1.EphemeralService"));
            final List<ResolveInfo> resolveInfo = InstrumentationRegistry
                    .getContext().getPackageManager().queryIntentServices(queryIntent, 0 /*flags*/);
            if (resolveInfo == null || resolveInfo.size() == 0) {
                fail("didn't resolve any intents");
            }
            assertThat(resolveInfo.size(), is(1));
            assertThat(resolveInfo.get(0).serviceInfo.packageName,
                    is("com.android.cts.ephemeralapp1"));
            assertThat(resolveInfo.get(0).serviceInfo.name,
                    is("com.android.cts.ephemeralapp1.EphemeralService"));
        }

        // query instant application provider
        {
            final Intent queryIntent = new Intent(ACTION_QUERY);
            final List<ResolveInfo> resolveInfo = InstrumentationRegistry
                    .getContext().getPackageManager().queryIntentContentProviders(
                            queryIntent, 0 /*flags*/);
            if (resolveInfo == null || resolveInfo.size() == 0) {
                fail("didn't resolve any intents");
            }
            assertThat(resolveInfo.size(), is(2));
            assertThat(resolveInfo.get(0).providerInfo.packageName,
                    is("com.android.cts.ephemeralapp1"));
            assertThat(resolveInfo.get(0).providerInfo.name,
                    is("com.android.cts.ephemeralapp1.EphemeralProvider"));
            assertThat(resolveInfo.get(1).providerInfo.packageName,
                    is("com.android.cts.normalapp"));
            assertThat(resolveInfo.get(1).providerInfo.name,
                    is("com.android.cts.normalapp.ExposedProvider"));
            assertThat(resolveInfo.get(1).isInstantAppAvailable,
                    is(false));
        }

        // query instant application provider ; directed package
        {
            final Intent queryIntent = new Intent(ACTION_QUERY);
            queryIntent.setPackage("com.android.cts.ephemeralapp1");
            final List<ResolveInfo> resolveInfo = InstrumentationRegistry
                    .getContext().getPackageManager().queryIntentContentProviders(
                            queryIntent, 0 /*flags*/);
            if (resolveInfo == null || resolveInfo.size() == 0) {
                fail("didn't resolve any intents");
            }
            assertThat(resolveInfo.size(), is(1));
            assertThat(resolveInfo.get(0).providerInfo.packageName,
                    is("com.android.cts.ephemeralapp1"));
            assertThat(resolveInfo.get(0).providerInfo.name,
                    is("com.android.cts.ephemeralapp1.EphemeralProvider"));
        }

        // query instant application provider ; directed component
        {
            final Intent queryIntent = new Intent(ACTION_QUERY);
            queryIntent.setComponent(
                    new ComponentName("com.android.cts.ephemeralapp1",
                            "com.android.cts.ephemeralapp1.EphemeralProvider"));
            final List<ResolveInfo> resolveInfo = InstrumentationRegistry
                    .getContext().getPackageManager().queryIntentContentProviders(
                            queryIntent, 0 /*flags*/);
            if (resolveInfo == null || resolveInfo.size() == 0) {
                fail("didn't resolve any intents");
            }
            assertThat(resolveInfo.size(), is(1));
            assertThat(resolveInfo.get(0).providerInfo.packageName,
                    is("com.android.cts.ephemeralapp1"));
            assertThat(resolveInfo.get(0).providerInfo.name,
                    is("com.android.cts.ephemeralapp1.EphemeralProvider"));
        }

        // resolve normal provider
        {
            final ProviderInfo providerInfo = InstrumentationRegistry
                    .getContext().getPackageManager().resolveContentProvider(
                            "com.android.cts.normalapp.provider", 0 /*flags*/);
            assertThat(providerInfo, is(nullValue()));
        }

        // resolve exposed provider
        {
            final ProviderInfo providerInfo = InstrumentationRegistry
                    .getContext().getPackageManager().resolveContentProvider(
                            "com.android.cts.normalapp.exposed.provider", 0 /*flags*/);
            assertThat(providerInfo, is(notNullValue()));
            assertThat(providerInfo.packageName,
                    is("com.android.cts.normalapp"));
            assertThat(providerInfo.name,
                    is("com.android.cts.normalapp.ExposedProvider"));
        }

        // resolve instant application provider
        {
            final ProviderInfo providerInfo = InstrumentationRegistry
                    .getContext().getPackageManager().resolveContentProvider(
                            "com.android.cts.ephemeralapp1.provider", 0 /*flags*/);
            assertThat(providerInfo, is(notNullValue()));
            assertThat(providerInfo.packageName,
                    is("com.android.cts.ephemeralapp1"));
            assertThat(providerInfo.name,
                    is("com.android.cts.ephemeralapp1.EphemeralProvider"));
        }
    }

    @Test
    public void testStartNormal() throws Exception {
        // start the normal activity
        try {
            final Intent startNormalIntent = new Intent(ACTION_START_NORMAL)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            InstrumentationRegistry
                    .getContext().startActivity(startNormalIntent, null /*options*/);
            final TestResult testResult = getResult();
            fail();
        } catch (ActivityNotFoundException expected) {
        }

        // start the normal activity; directed package
        try {
            final Intent startNormalIntent = new Intent(ACTION_START_NORMAL)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startNormalIntent.setPackage("com.android.cts.normalapp");
            InstrumentationRegistry
                    .getContext().startActivity(startNormalIntent, null /*options*/);
            final TestResult testResult = getResult();
            fail();
        } catch (ActivityNotFoundException expected) {
        }

        // start the normal activity; directed component
        try {
            final Intent startNormalIntent = new Intent(ACTION_START_NORMAL)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startNormalIntent.setComponent(new ComponentName(
                    "com.android.cts.normalapp", "com.android.cts.normalapp.NormalActivity"));
            InstrumentationRegistry
                    .getContext().startActivity(startNormalIntent, null /*options*/);
            final TestResult testResult = getResult();
            fail();
        } catch (ActivityNotFoundException expected) {
        }

// TODO: Ideally we should have a test for this. However, it shows a disambig between the
//       the normal app and chrome; for which there is no easy solution.
//        // start the normal activity; using VIEW/BROWSABLE
//        {
//            final Intent startViewIntent = new Intent(Intent.ACTION_VIEW)
//                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            startViewIntent.addCategory(Intent.CATEGORY_BROWSABLE);
//            startViewIntent.setData(Uri.parse("https://cts.google.com/normal"));
//            InstrumentationRegistry.getContext().startActivity(startViewIntent, null /*options*/);
//            final TestResult testResult = getResult();
//            assertThat(testResult.getPackageName(),
//                    is("com.android.cts.normalapp"));
//            assertThat(testResult.getComponentName(),
//                    is("NormalWebActivity"));
//            assertThat(testResult.getStatus(),
//                    is("PASS"));
//            assertThat(testResult.getEphemeralPackageInfoExposed(),
//                    is(false));
//            assertThat(testResult.getException(),
//                    is(nullValue()));
//        }

        // We don't attempt to start the service since it will merely return and not
        // provide any feedback. The alternative is to wait for the broadcast timeout
        // but it's silly to artificially slow down CTS. We'll rely on queryIntentService
        // to check whether or not the service is actually exposed

        // bind to the normal service; directed package
        {
            final Intent startNormalIntent = new Intent(ACTION_START_NORMAL);
            startNormalIntent.setPackage("com.android.cts.normalapp");
            final TestServiceConnection connection = new TestServiceConnection();
            try {
                assertThat(InstrumentationRegistry.getContext().bindService(
                        startNormalIntent, connection, Context.BIND_AUTO_CREATE /*flags*/),
                        is(false));
            } finally {
                InstrumentationRegistry.getContext().unbindService(connection);
            }
        }

        // bind to the normal service; directed component
        {
            final Intent startNormalIntent = new Intent(ACTION_START_NORMAL);
            startNormalIntent.setComponent(new ComponentName(
                    "com.android.cts.normalapp", "com.android.cts.normalapp.NormalService"));
            final TestServiceConnection connection = new TestServiceConnection();
            try {
                assertThat(InstrumentationRegistry.getContext().bindService(
                        startNormalIntent, connection, Context.BIND_AUTO_CREATE /*flags*/),
                        is(false));
            } finally {
                InstrumentationRegistry.getContext().unbindService(connection);
            }
        }

        // connect to the normal provider
        {
            final String provider = "content://com.android.cts.normalapp.provider/table";
            final Cursor testCursor = InstrumentationRegistry
                    .getContext().getContentResolver().query(
                            Uri.parse(provider),
                            null /*projection*/,
                            null /*selection*/,
                            null /*selectionArgs*/,
                            null /*sortOrder*/);
            assertThat(testCursor, is(nullValue()));
        }
    }

    @Test
    public void testStartExposed01() throws Exception {
        // start the explicitly exposed activity
        final Intent startExposedIntent = new Intent(ACTION_START_EXPOSED)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        InstrumentationRegistry
                .getContext().startActivity(startExposedIntent, null /*options*/);
        final TestResult testResult = getResult();
        assertThat(testResult.getPackageName(),
                is("com.android.cts.normalapp"));
        assertThat(testResult.getComponentName(),
                is("ExposedActivity"));
        assertThat(testResult.getStatus(),
                is("PASS"));
        assertThat(testResult.getEphemeralPackageInfoExposed(),
                is(false));
        assertThat(testResult.getException(),
                is(PackageManager.NameNotFoundException.class.getName()));
    }

    @Test
    public void testStartExposed02() throws Exception {
        // start the explicitly exposed activity; directed package
        final Intent startExposedIntent = new Intent(ACTION_START_EXPOSED)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startExposedIntent.setPackage("com.android.cts.normalapp");
        InstrumentationRegistry
                .getContext().startActivity(startExposedIntent, null /*options*/);
        final TestResult testResult = getResult();
        assertThat(testResult.getPackageName(),
                is("com.android.cts.normalapp"));
        assertThat(testResult.getComponentName(),
                is("ExposedActivity"));
        assertThat(testResult.getStatus(),
                is("PASS"));
        assertThat(testResult.getEphemeralPackageInfoExposed(),
                is(false));
        assertThat(testResult.getException(),
                is(PackageManager.NameNotFoundException.class.getName()));
    }

    @Test
    public void testStartExposed03() throws Exception {
        // start the explicitly exposed activity; directed component
        final Intent startExposedIntent = new Intent(ACTION_START_EXPOSED)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startExposedIntent.setComponent(new ComponentName(
                "com.android.cts.normalapp", "com.android.cts.normalapp.ExposedActivity"));
        InstrumentationRegistry
                .getContext().startActivity(startExposedIntent, null /*options*/);
        final TestResult testResult = getResult();
        assertThat(testResult.getPackageName(),
                is("com.android.cts.normalapp"));
        assertThat(testResult.getComponentName(),
                is("ExposedActivity"));
        assertThat(testResult.getStatus(),
                is("PASS"));
        assertThat(testResult.getEphemeralPackageInfoExposed(),
                is(false));
        assertThat(testResult.getException(),
                is(PackageManager.NameNotFoundException.class.getName()));
    }

    @Test
    public void testStartExposed04() throws Exception {
        // start the implicitly exposed activity; directed package
        try {
            final Intent startExposedIntent = new Intent(Intent.ACTION_VIEW)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startExposedIntent.setPackage("com.android.cts.implicitapp");
            startExposedIntent.addCategory(Intent.CATEGORY_BROWSABLE);
            startExposedIntent.setData(Uri.parse("https://cts.google.com/implicit"));
            InstrumentationRegistry
                    .getContext().startActivity(startExposedIntent, null /*options*/);
            fail("activity started");
        } catch (ActivityNotFoundException expected) { }
    }

    @Test
    public void testStartExposed05() throws Exception {
        // start the implicitly exposed activity; directed component
        try {
            final Intent startExposedIntent = new Intent(Intent.ACTION_VIEW)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startExposedIntent.setComponent(new ComponentName(
                    "com.android.cts.implicitapp",
                    "com.android.cts.implicitapp.ImplicitActivity"));
            startExposedIntent.addCategory(Intent.CATEGORY_BROWSABLE);
            startExposedIntent.setData(Uri.parse("https://cts.google.com/implicit"));
            InstrumentationRegistry
                    .getContext().startActivity(startExposedIntent, null /*options*/);
            fail("activity started");
        } catch (ActivityNotFoundException expected) { }
    }

    @Test
    public void testStartExposed06() throws Exception {
        // start the exposed service; directed package
        final Intent startExposedIntent = new Intent(ACTION_START_EXPOSED)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startExposedIntent.setPackage("com.android.cts.normalapp");
        InstrumentationRegistry.getContext().startForegroundService(startExposedIntent);
        final TestResult testResult = getResult();
        assertThat(testResult.getPackageName(),
                is("com.android.cts.normalapp"));
        assertThat(testResult.getComponentName(),
                is("ExposedService"));
        assertThat(testResult.getStatus(),
                is("PASS"));
        assertThat(testResult.getEphemeralPackageInfoExposed(),
                is(true));
        assertThat(testResult.getException(),
                is(nullValue()));
    }

    @Test
    public void testStartExposed07() throws Exception {
        // start the exposed service; directed component
        final Intent startExposedIntent = new Intent(ACTION_START_EXPOSED);
        startExposedIntent.setComponent(new ComponentName(
                "com.android.cts.normalapp", "com.android.cts.normalapp.ExposedService"));
        InstrumentationRegistry.getContext().startForegroundService(startExposedIntent);
        final TestResult testResult = getResult();
        assertThat(testResult.getPackageName(),
                is("com.android.cts.normalapp"));
        assertThat(testResult.getComponentName(),
                is("ExposedService"));
        assertThat(testResult.getMethodName(),
                is("onStartCommand"));
        assertThat(testResult.getStatus(),
                is("PASS"));
        assertThat(testResult.getEphemeralPackageInfoExposed(),
                is(true));
        assertThat(testResult.getException(),
                is(nullValue()));
    }

    @Test
    public void testStartExposed08() throws Exception {
        // bind to the exposed service; directed package
        final Intent startExposedIntent = new Intent(ACTION_START_EXPOSED);
        startExposedIntent.setPackage("com.android.cts.normalapp");
        final TestServiceConnection connection = new TestServiceConnection();
        try {
            assertThat(InstrumentationRegistry.getContext().bindService(
                    startExposedIntent, connection, Context.BIND_AUTO_CREATE /*flags*/),
                    is(true));
            final TestResult testResult = getResult();
            assertThat(testResult.getPackageName(),
                    is("com.android.cts.normalapp"));
            assertThat(testResult.getComponentName(),
                    is("ExposedService"));
            assertThat(testResult.getMethodName(),
                    is("onBind"));
            assertThat(testResult.getStatus(),
                    is("PASS"));
            assertThat(testResult.getEphemeralPackageInfoExposed(),
                    is(true));
            assertThat(testResult.getException(),
                    is(nullValue()));
        } finally {
            InstrumentationRegistry.getContext().unbindService(connection);
        }
    }

    @Test
    public void testStartExposed09() throws Exception {
        // bind to the exposed service; directed component
        final Intent startExposedIntent = new Intent(ACTION_START_EXPOSED);
        startExposedIntent.setComponent(new ComponentName(
                "com.android.cts.normalapp", "com.android.cts.normalapp.ExposedService"));
        final TestServiceConnection connection = new TestServiceConnection();
        try {
            assertThat(InstrumentationRegistry.getContext().bindService(
                    startExposedIntent, connection, Context.BIND_AUTO_CREATE /*flags*/),
                    is(true));
            final TestResult testResult = getResult();
            assertThat(testResult.getPackageName(),
                    is("com.android.cts.normalapp"));
            assertThat(testResult.getComponentName(),
                    is("ExposedService"));
            assertThat(testResult.getMethodName(),
                    is("onBind"));
            assertThat(testResult.getStatus(),
                    is("PASS"));
            assertThat(testResult.getEphemeralPackageInfoExposed(),
                    is(true));
            assertThat(testResult.getException(),
                    is(nullValue()));
        } finally {
            InstrumentationRegistry.getContext().unbindService(connection);
        }
    }

    @Test
    public void testStartExposed10() throws Exception {
        // connect to exposed provider
        final String provider = "content://com.android.cts.normalapp.exposed.provider/table";
        final Cursor testCursor = InstrumentationRegistry
                .getContext().getContentResolver().query(
                        Uri.parse(provider),
                        null /*projection*/,
                        null /*selection*/,
                        null /*selectionArgs*/,
                        null /*sortOrder*/);
        assertThat(testCursor, is(notNullValue()));
        assertThat(testCursor.getCount(), is(1));
        assertThat(testCursor.getColumnCount(), is(2));
        assertThat(testCursor.moveToFirst(), is(true));
        assertThat(testCursor.getInt(0), is(1));
        assertThat(testCursor.getString(1), is("ExposedProvider"));
        final TestResult testResult = getResult();
        assertThat(testResult.getPackageName(),
                is("com.android.cts.normalapp"));
        assertThat(testResult.getComponentName(),
                is("ExposedProvider"));
        assertThat(testResult.getStatus(),
                is("PASS"));
        assertThat(testResult.getEphemeralPackageInfoExposed(),
                is(true));
        assertThat(testResult.getException(),
                is(nullValue()));
    }

    @Test
    public void testStartExposed11() throws Exception {
        // start the explicitly exposed activity
        final Intent startExposedIntent = new Intent(ACTION_START_EXPOSED)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        final Context context = InstrumentationRegistry.getContext();
        context.startActivity(startExposedIntent.setComponent(
                new ComponentName(context, StartForResultActivity.class)));

        final TestResult testResult = getResult();
        assertThat(testResult.getPackageName(),
                is("com.android.cts.normalapp"));
        assertThat(testResult.getComponentName(),
                is("ExposedActivity"));
        assertThat(testResult.getStatus(),
                is("PASS"));
        assertThat(testResult.getEphemeralPackageInfoExposed(),
                is(true));
        assertThat(testResult.getException(),
                is(nullValue()));
    }

    @Test
    public void testStartEphemeral() throws Exception {
        // start the ephemeral activity
        {
            final Intent startEphemeralIntent = new Intent(ACTION_START_EPHEMERAL)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            InstrumentationRegistry
                    .getContext().startActivity(startEphemeralIntent, null /*options*/);
            final TestResult testResult = getResult();
            assertThat(testResult.getPackageName(),
                    is("com.android.cts.ephemeralapp1"));
            assertThat(testResult.getComponentName(),
                    is("EphemeralActivity"));
            assertThat(testResult.getStatus(),
                    is("PASS"));
            assertThat(testResult.getException(),
                    is(nullValue()));
        }

        // start the ephemeral activity; directed package
        {
            final Intent startEphemeralIntent = new Intent(ACTION_START_EPHEMERAL)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startEphemeralIntent.setPackage("com.android.cts.ephemeralapp1");
            InstrumentationRegistry
                    .getContext().startActivity(startEphemeralIntent, null /*options*/);
            final TestResult testResult = getResult();
            assertThat(testResult.getPackageName(),
                    is("com.android.cts.ephemeralapp1"));
            assertThat(testResult.getComponentName(),
                    is("EphemeralActivity"));
            assertThat(testResult.getStatus(),
                    is("PASS"));
            assertThat(testResult.getException(),
                    is(nullValue()));
        }

        // start the ephemeral activity; directed component
        {
            final Intent startEphemeralIntent = new Intent(ACTION_START_EPHEMERAL)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startEphemeralIntent.setComponent(
                    new ComponentName("com.android.cts.ephemeralapp1",
                            "com.android.cts.ephemeralapp1.EphemeralActivity"));
            InstrumentationRegistry
                    .getContext().startActivity(startEphemeralIntent, null /*options*/);
            final TestResult testResult = getResult();
            assertThat(testResult.getPackageName(),
                    is("com.android.cts.ephemeralapp1"));
            assertThat(testResult.getComponentName(),
                    is("EphemeralActivity"));
            assertThat(testResult.getStatus(),
                    is("PASS"));
            assertThat(testResult.getException(),
                    is(nullValue()));
        }

        // start a private ephemeral activity
        {
            final Intent startEphemeralIntent = new Intent(ACTION_START_EPHEMERAL_PRIVATE)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            InstrumentationRegistry
                    .getContext().startActivity(startEphemeralIntent, null /*options*/);
            final TestResult testResult = getResult();
            assertThat(testResult.getPackageName(),
                    is("com.android.cts.ephemeralapp1"));
            assertThat(testResult.getComponentName(),
                    is("EphemeralActivity2"));
            assertThat(testResult.getStatus(),
                    is("PASS"));
            assertThat(testResult.getException(),
                    is(nullValue()));
        }

        // start a private ephemeral activity; directed package
        {
            final Intent startEphemeralIntent = new Intent(ACTION_START_EPHEMERAL_PRIVATE)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startEphemeralIntent.setPackage("com.android.cts.ephemeralapp1");
            InstrumentationRegistry
                    .getContext().startActivity(startEphemeralIntent, null /*options*/);
            final TestResult testResult = getResult();
            assertThat(testResult.getPackageName(),
                    is("com.android.cts.ephemeralapp1"));
            assertThat(testResult.getComponentName(),
                    is("EphemeralActivity2"));
            assertThat(testResult.getStatus(),
                    is("PASS"));
            assertThat(testResult.getException(),
                    is(nullValue()));
        }

        // start a private ephemeral activity; directed component
        {
            final Intent startEphemeralIntent = new Intent(ACTION_START_EPHEMERAL_PRIVATE)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startEphemeralIntent.setComponent(
                    new ComponentName("com.android.cts.ephemeralapp1",
                            "com.android.cts.ephemeralapp1.EphemeralActivity2"));
            InstrumentationRegistry
                    .getContext().startActivity(startEphemeralIntent, null /*options*/);
            final TestResult testResult = getResult();
            assertThat(testResult.getPackageName(),
                    is("com.android.cts.ephemeralapp1"));
            assertThat(testResult.getComponentName(),
                    is("EphemeralActivity2"));
            assertThat(testResult.getStatus(),
                    is("PASS"));
            assertThat(testResult.getException(),
                    is(nullValue()));
        }

        // start a private ephemeral activity; directed component
        {
            final Intent startEphemeralIntent = new Intent()
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startEphemeralIntent.setComponent(
                    new ComponentName("com.android.cts.ephemeralapp1",
                            "com.android.cts.ephemeralapp1.EphemeralActivity3"));
            InstrumentationRegistry
                    .getContext().startActivity(startEphemeralIntent, null /*options*/);
            final TestResult testResult = getResult();
            assertThat(testResult.getPackageName(),
                    is("com.android.cts.ephemeralapp1"));
            assertThat(testResult.getComponentName(),
                    is("EphemeralActivity3"));
            assertThat(testResult.getStatus(),
                    is("PASS"));
            assertThat(testResult.getException(),
                    is(nullValue()));
        }

        // start an ephemeral activity; VIEW / BROWSABLE intent
        {
            final Intent startEphemeralIntent = new Intent(Intent.ACTION_VIEW)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startEphemeralIntent.addCategory(Intent.CATEGORY_BROWSABLE);
            startEphemeralIntent.setData(Uri.parse("https://cts.google.com/other"));
            InstrumentationRegistry
                    .getContext().startActivity(startEphemeralIntent, null /*options*/);
            final TestResult testResult = getResult();
            assertThat(testResult.getPackageName(),
                    is("com.android.cts.ephemeralapp2"));
            assertThat(testResult.getComponentName(),
                    is("EphemeralActivity"));
            assertThat(testResult.getIntent().getAction(),
                    is(Intent.ACTION_VIEW));
            assertThat(testResult.getIntent().getCategories(),
                    hasItems(Intent.CATEGORY_BROWSABLE));
            assertThat(testResult.getIntent().getData().toString(),
                    is("https://cts.google.com/other"));
            assertThat(testResult.getStatus(),
                    is("PASS"));
            assertThat(testResult.getException(),
                    is(nullValue()));
        }

        // start an ephemeral activity; EXTERNAL flag
        {
            final Intent startEphemeralIntent = new Intent(ACTION_START_EPHEMERAL_ACTIVITY)
                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MATCH_EXTERNAL);
            InstrumentationRegistry.getContext().startActivity(
                    startEphemeralIntent, null /*options*/);
            final TestResult testResult = getResult();
            assertThat(testResult.getPackageName(),
                    is("com.android.cts.ephemeralapp2"));
            assertThat(testResult.getComponentName(),
                    is("EphemeralActivity"));
            assertThat(testResult.getIntent().getAction(),
                    is(ACTION_START_EPHEMERAL_ACTIVITY));
            assertThat(testResult.getIntent().getData(),
                    is(nullValue()));
            assertThat(testResult.getStatus(),
                    is("PASS"));
            assertThat(testResult.getException(),
                    is(nullValue()));
        }

        // start the ephemeral service; directed package
        {
            final Intent startEphemeralIntent = new Intent(ACTION_START_EPHEMERAL);
            startEphemeralIntent.setPackage("com.android.cts.ephemeralapp1");
            try {
                InstrumentationRegistry.getContext().startService(startEphemeralIntent);
                final TestResult testResult = getResult();
                assertThat(testResult.getPackageName(),
                        is("com.android.cts.ephemeralapp1"));
                assertThat(testResult.getComponentName(),
                        is("EphemeralService"));
                assertThat(testResult.getMethodName(),
                        is("onStartCommand"));
                assertThat(testResult.getStatus(),
                        is("PASS"));
                assertThat(testResult.getException(),
                        is(nullValue()));
            } finally {
                InstrumentationRegistry.getContext().stopService(startEphemeralIntent);
            }
        }

        // start the ephemeral service; directed component
        {
            final Intent startEphemeralIntent = new Intent(ACTION_START_EPHEMERAL);
            startEphemeralIntent.setComponent(
                    new ComponentName("com.android.cts.ephemeralapp1",
                            "com.android.cts.ephemeralapp1.EphemeralService"));
            try {
                assertThat(InstrumentationRegistry.getContext().startService(startEphemeralIntent),
                        is(notNullValue()));
                final TestResult testResult = getResult();
                assertThat(testResult.getPackageName(),
                        is("com.android.cts.ephemeralapp1"));
                assertThat(testResult.getComponentName(),
                        is("EphemeralService"));
                assertThat(testResult.getMethodName(),
                        is("onStartCommand"));
                assertThat(testResult.getStatus(),
                        is("PASS"));
                assertThat(testResult.getException(),
                        is(nullValue()));
            } finally {
                InstrumentationRegistry.getContext().stopService(startEphemeralIntent);
            }
        }

        // bind to the ephemeral service; directed package
        {
            final Intent startEphemeralIntent = new Intent(ACTION_START_EPHEMERAL);
            startEphemeralIntent.setPackage("com.android.cts.ephemeralapp1");
            final TestServiceConnection connection = new TestServiceConnection();
            try {
                assertThat(InstrumentationRegistry.getContext().bindService(
                        startEphemeralIntent, connection, Context.BIND_AUTO_CREATE /*flags*/),
                        is(true));
                final TestResult testResult = getResult();
                assertThat(testResult.getPackageName(),
                        is("com.android.cts.ephemeralapp1"));
                assertThat(testResult.getComponentName(),
                        is("EphemeralService"));
                assertThat(testResult.getMethodName(),
                        is("onBind"));
                assertThat(testResult.getStatus(),
                        is("PASS"));
                assertThat(testResult.getException(),
                        is(nullValue()));
            } finally {
                InstrumentationRegistry.getContext().unbindService(connection);
            }
        }

        // bind to the ephemeral service; directed component
        {
            final Intent startEphemeralIntent = new Intent(ACTION_START_EPHEMERAL);
            startEphemeralIntent.setComponent(
                    new ComponentName("com.android.cts.ephemeralapp1",
                            "com.android.cts.ephemeralapp1.EphemeralService"));
            final TestServiceConnection connection = new TestServiceConnection();
            try {
                assertThat(InstrumentationRegistry.getContext().bindService(
                        startEphemeralIntent, connection, Context.BIND_AUTO_CREATE /*flags*/),
                        is(true));
                final TestResult testResult = getResult();
                assertThat(testResult.getPackageName(),
                        is("com.android.cts.ephemeralapp1"));
                assertThat(testResult.getComponentName(),
                        is("EphemeralService"));
                assertThat(testResult.getMethodName(),
                        is("onBind"));
                assertThat(testResult.getStatus(),
                        is("PASS"));
                assertThat(testResult.getException(),
                        is(nullValue()));
            } finally {
                InstrumentationRegistry.getContext().unbindService(connection);
            }
        }

        // connect to the instant app provider
        {
            final String provider = "content://com.android.cts.ephemeralapp1.provider/table";
            final Cursor testCursor = InstrumentationRegistry
                    .getContext().getContentResolver().query(
                            Uri.parse(provider),
                            null /*projection*/,
                            null /*selection*/,
                            null /*selectionArgs*/,
                            null /*sortOrder*/);
            assertThat(testCursor, is(notNullValue()));
            assertThat(testCursor.getCount(), is(1));
            assertThat(testCursor.getColumnCount(), is(2));
            assertThat(testCursor.moveToFirst(), is(true));
            assertThat(testCursor.getInt(0), is(1));
            assertThat(testCursor.getString(1), is("InstantAppProvider"));
        }
    }

    @Test
    public void testBuildSerialUnknown() throws Exception {
        assertThat(Build.SERIAL, is(Build.UNKNOWN));
    }

    @Test
    public void testPackageInfo() throws Exception {
        PackageInfo info;
        // own package info
        info = InstrumentationRegistry.getContext().getPackageManager()
                .getPackageInfo("com.android.cts.ephemeralapp1", 0);
        assertThat(info.packageName,
                is("com.android.cts.ephemeralapp1"));

        // exposed application package info
        info = InstrumentationRegistry.getContext().getPackageManager()
                .getPackageInfo("com.android.cts.normalapp", 0);
        assertThat(info.packageName,
                is("com.android.cts.normalapp"));

        // implicitly exposed application package info not accessible
        try {
            info = InstrumentationRegistry.getContext().getPackageManager()
                    .getPackageInfo("com.android.cts.implicitapp", 0);
            fail("Instant apps should not be able to access PackageInfo for an app that does not" +
                    " expose itself to Instant Apps.");
        } catch (PackageManager.NameNotFoundException expected) {
        }

        // unexposed application package info not accessible
        try {
            info = InstrumentationRegistry.getContext().getPackageManager()
                    .getPackageInfo("com.android.cts.unexposedapp", 0);
            fail("Instant apps should not be able to access PackageInfo for an app that does not" +
                    " expose itself to Instant Apps.");
        } catch (PackageManager.NameNotFoundException expected) {
        }

        // instant application (with visibleToInstantApp component) package info not accessible
        try {
            info = InstrumentationRegistry.getContext().getPackageManager()
                    .getPackageInfo("com.android.cts.ephemeralapp2", 0);
            fail("Instant apps should not be able to access PackageInfo for another Instant App.");
        } catch (PackageManager.NameNotFoundException expected) {
        }
    }

    @Test
    public void testActivityInfo() throws Exception {
        // own package info
        {
            final ComponentName component = new ComponentName(
                    "com.android.cts.ephemeralapp1",
                    "com.android.cts.ephemeralapp1.EphemeralActivity");
            final ActivityInfo info = InstrumentationRegistry.getContext().getPackageManager()
                .getActivityInfo(component, 0);
            assertThat(info.packageName,
                    is("com.android.cts.ephemeralapp1"));
        }

        // exposed application package info
        {
            final ComponentName component = new ComponentName(
                    "com.android.cts.normalapp",
                    "com.android.cts.normalapp.ExposedActivity");
            final ActivityInfo info = InstrumentationRegistry.getContext().getPackageManager()
                .getActivityInfo(component, 0);
            assertThat(info.packageName,
                    is("com.android.cts.normalapp"));
        }

        // implicitly exposed application package info not accessible
        {
            try {
                final ComponentName component = new ComponentName(
                        "com.android.cts.normalapp",
                        "com.android.cts.normalapp.NormalWebActivity");
                final ActivityInfo info = InstrumentationRegistry.getContext().getPackageManager()
                        .getActivityInfo(component, 0);
                fail("Instant apps should not be able to access ActivityInfo for"
                        + " an activity that implicitly exposes itself to Instant Apps.");
            } catch (PackageManager.NameNotFoundException expected) {
            }
        }

        // unexposed application package info not accessible
        {
            try {
                final ComponentName component = new ComponentName(
                        "com.android.cts.normalapp",
                        "com.android.cts.normalapp.NormalActivity");
                final ActivityInfo info = InstrumentationRegistry.getContext().getPackageManager()
                        .getActivityInfo(component, 0);
                fail("Instant apps should not be able to access ActivityInfo for"
                        + " an activity that does not expose itself to Instant Apps.");
            } catch (PackageManager.NameNotFoundException expected) {
            }
        }

        // instant application (with visibleToInstantApp component) package info not accessible
        {
            try {
                final ComponentName component = new ComponentName(
                        "com.android.cts.ephemeralapp2",
                        "com.android.cts.ephemeralapp2.ExposedActivity");
                final ActivityInfo info = InstrumentationRegistry.getContext().getPackageManager()
                        .getActivityInfo(component, 0);
                fail("Instant apps should not be able to access ActivityInfo for"
                        + " another Instant App.");
            } catch (PackageManager.NameNotFoundException expected) {
            }
        }
    }

    @Test
    public void testInstallPermissionNotGranted() throws Exception {
        assertThat(InstrumentationRegistry.getContext()
                    .checkCallingOrSelfPermission(Manifest.permission.SET_ALARM),
                is(PackageManager.PERMISSION_DENIED));
    }

    @Test
    public void testInstallPermissionGranted() throws Exception {
        assertThat(InstrumentationRegistry.getContext()
                    .checkCallingOrSelfPermission(Manifest.permission.INTERNET),
                is(PackageManager.PERMISSION_GRANTED));
    }

    @Test
    @AsbSecurityTest(cveBugId = 140256621)
    public void testInstallPermissionNotGrantedInPackageInfo() throws Exception {
        assertThat(isPermissionGrantedInPackageInfo(Manifest.permission.SET_ALARM), is(false));
    }

    @Test
    @AsbSecurityTest(cveBugId = 140256621)
    public void testInstallPermissionGrantedInPackageInfo() throws Exception {
        assertThat(isPermissionGrantedInPackageInfo(Manifest.permission.INTERNET), is(true));
    }

    private static boolean isPermissionGrantedInPackageInfo(String permissionName)
            throws Exception {
        final Context context = InstrumentationRegistry.getContext();
        final PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
                context.getPackageName(), PackageManager.GET_PERMISSIONS);
        final int permissionIndex = Arrays.asList(packageInfo.requestedPermissions).indexOf(
                permissionName);
        assertThat(permissionIndex, is(not(-1)));
        return (packageInfo.requestedPermissionsFlags[permissionIndex]
                & PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0;
    }

    @Test
    public void testExposedActivity() throws Exception {
        final Bundle testArgs = InstrumentationRegistry.getArguments();
        assertThat(testArgs, is(notNullValue()));
        final String action = testArgs.getString("action");
        final String category = testArgs.getString("category");
        final String mimeType = testArgs.getString("mime_type");
        assertThat(action, is(notNullValue()));
        final Intent queryIntent = makeIntent(action, category, mimeType);
        final List<ResolveInfo> resolveInfo = InstrumentationRegistry.getContext()
                .getPackageManager().queryIntentActivities(queryIntent, 0 /*flags*/);
        if (resolveInfo == null || resolveInfo.size() == 0) {
            fail("No activies found for Intent: " + queryIntent);
        }
    }

    @Test
    public void testGetInstaller01() throws Exception {
        // test we can read our own installer
        final String installerPackageName = InstrumentationRegistry.getContext().getPackageManager()
                .getInstallerPackageName("com.android.cts.ephemeralapp1");
        assertThat(installerPackageName, is("com.android.cts.normalapp"));
    }
    @Test
    public void testGetInstaller02() throws Exception {
        // test we can read someone else's installer if they're exposed to instant applications
        final String installerPackageName = InstrumentationRegistry.getContext().getPackageManager()
                .getInstallerPackageName("com.android.cts.normalapp");
        assertThat(installerPackageName, is("com.android.cts.normalapp"));
    }
    @Test
    public void testGetInstaller03() throws Exception {
        // test we can't read installer if they're not exposed to instant applications
        final PackageManager pm = InstrumentationRegistry.getContext().getPackageManager();
        assertThrows(IllegalArgumentException.class,
                () -> pm.getInstallerPackageName("com.android.cts.unexposedapp"));
    }

    @Test
    public void testStartForegroundService() throws Exception {
        final Context context = InstrumentationRegistry.getContext();
        final Intent intent = new Intent(context, SomeService.class);

        // Create a notification channel for the foreground notification
        final NotificationChannel channel = new NotificationChannel("foo", "foo",
                NotificationManager.IMPORTANCE_DEFAULT);
        final NotificationManager notificationManager = context.getSystemService(
                NotificationManager.class);
        notificationManager.createNotificationChannel(channel);

        // Shouldn't be able to start without a permission
        final CountDownLatch latch1 = new CountDownLatch(1);
        SomeService.setOnStartCommandCallback((int result) -> {
            assertSame("Shouldn't be able to start without "
                    + " INSTANT_APP_FOREGROUND_SERVICE permission", 0, result);
            latch1.countDown();
        });
        context.startForegroundService(intent);
        latch1.await(5, TimeUnit.SECONDS);

        // Now grant ourselves INSTANT_APP_FOREGROUND_SERVICE
        grantInstantAppForegroundServicePermission();

        // Should be able to start with a permission
        final CountDownLatch latch2 = new CountDownLatch(1);
        SomeService.setOnStartCommandCallback((int result) -> {
            assertSame("Should be able to start with "
                    + " INSTANT_APP_FOREGROUND_SERVICE permission", 1, result);
            latch2.countDown();
        });
        context.startForegroundService(intent);
        latch2.await(5, TimeUnit.SECONDS);
    }

    @Test
    public void testRecordAudioPermission() throws Throwable {
        final AudioRecord record =
                new AudioRecord(MIC, 8000, CHANNEL_IN_MONO, ENCODING_PCM_16BIT, 4096);
        try {
            assertThat("audio record not initialized",
                    record.getState(), is(AudioRecord.STATE_INITIALIZED));
        } finally {
            record.release();
        }
    }

    @Test
    public void testReadPhoneNumbersPermission() throws Throwable {
        final Context context = InstrumentationRegistry.getContext();
        if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
            return;
        }

        try {
            final TelephonyManager telephonyManager =
                    (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            final String nmbr = telephonyManager.getLine1Number();
        } catch (SecurityException e) {
            fail("Permission not granted");
        }
    }

    @Test
    public void testAccessCoarseLocationPermission() {
        final Context context = InstrumentationRegistry.getContext();

        final LocationManager locationManager =
                (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        final Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        final String bestProvider = locationManager.getBestProvider(criteria, false);
        try {
            final String provider =
                    bestProvider == null ? LocationManager.NETWORK_PROVIDER : bestProvider;
            locationManager.getLastKnownLocation(provider);
        } catch (SecurityException e) {
            fail("Permission not granted.");
        }
    }

    @Test
    public void testCameraPermission() throws Throwable {
        final Context context = InstrumentationRegistry.getContext();
        final CameraManager manager =
                (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        final String[] cameraIds = manager.getCameraIdList();
        if (cameraIds.length == 0) {
            return;
        }
        final CountDownLatch latch = new CountDownLatch(1);
        final HandlerThread backgroundThread = new HandlerThread("camera_bg");
        backgroundThread.start();
        final CameraDevice.StateCallback callback = new CameraDevice.StateCallback() {
            @Override
            public void onOpened(CameraDevice camera) {
                latch.countDown();
                camera.close();
            }
            @Override
            public void onDisconnected(CameraDevice camera) {
                camera.close();
            }
            @Override
            public void onError(CameraDevice camera, int error) {
                camera.close();
            }
        };
        manager.openCamera(cameraIds[0], callback, new Handler(backgroundThread.getLooper()));
        assertThat(latch.await(1000, TimeUnit.MILLISECONDS), is(true));
    }

    @Test
    public void testInternetPermission() throws Throwable {
        final ConnectivityManager manager = (ConnectivityManager) InstrumentationRegistry.getContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        manager.reportNetworkConnectivity(null, false);
    }

    @Test
    public void testVibratePermission() throws Throwable {
        final Vibrator vibrator = (Vibrator) InstrumentationRegistry.getContext()
                .getSystemService(Context.VIBRATOR_SERVICE);
        final VibrationEffect effect =
                VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE);
        vibrator.vibrate(effect);
    }

    @Test
    public void testWakeLockPermission() throws Throwable {
        WakeLock wakeLock = null;
        try {
            final PowerManager powerManager = (PowerManager) InstrumentationRegistry.getContext()
                    .getSystemService(Context.POWER_SERVICE);
            wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "test");
            wakeLock.acquire();
        }
        finally {
            if (wakeLock != null &&  wakeLock.isHeld()) {
                wakeLock.release();
            }
        }
    }

    @Test
    public void testGetSearchableInfo() throws Throwable {
        final SearchManager searchManager = (SearchManager) InstrumentationRegistry.getContext()
                .getSystemService(Context.SEARCH_SERVICE);
        if (searchManager == null) {
            return;
        }
        // get searchable info for a component in ourself; pass
        {
            final SearchableInfo info = searchManager.getSearchableInfo(
                    new ComponentName("com.android.cts.ephemeralapp1",
                            "com.android.cts.ephemeralapp1.EphemeralActivity"));
            assertThat(info, is(notNullValue()));
            assertThat(info.getSearchActivity(),
                    is(equalTo(
                            new ComponentName("com.android.cts.ephemeralapp1",
                                    "com.android.cts.ephemeralapp1.EphemeralActivity"))));
        }

        // get searchable info for a component in a different instant application; fail
        {
            final SearchableInfo info = searchManager.getSearchableInfo(
                    new ComponentName("com.android.cts.ephemeralapp2",
                            "com.android.cts.ephemeralapp2.EphemeralActivity"));
            assertThat(info, is(nullValue()));
        }

        // get searchable info for an exposed in a full application; pass
        {
            final SearchableInfo info = searchManager.getSearchableInfo(
                    new ComponentName("com.android.cts.normalapp",
                            "com.android.cts.normalapp.ExposedActivity"));
            assertThat(info, is(notNullValue()));
            assertThat(info.getSearchActivity(),
                    is(equalTo(
                            new ComponentName("com.android.cts.normalapp",
                                    "com.android.cts.normalapp.ExposedActivity"))));
        }

        // get searchable info for an unexposed component in a full application; fail
        {
            final SearchableInfo info = searchManager.getSearchableInfo(
                    new ComponentName("com.android.cts.normalapp",
                            "com.android.cts.normalapp.NormalActivity"));
            assertThat(info, is(nullValue()));
        }
    }

    /** Tests getting changed packages for instant app. */
    @Test
    public void testGetChangedPackages() {
        final PackageManager pm = InstrumentationRegistry.getContext().getPackageManager();

        // Instant apps can't get changed packages.
        final ChangedPackages changedPackages = pm.getChangedPackages(0);
        assertNull(changedPackages);
    }

    /** Returns {@code true} if the given filter handles all web URLs, regardless of host. */
    private boolean handlesAllWebData(IntentFilter filter) {
        return filter.hasCategory(Intent.CATEGORY_APP_BROWSER) ||
                (handlesWebUris(filter) && filter.countDataAuthorities() == 0);
    }

    /** Returns {@code true} if the given filter handles at least one web URL. */
    private boolean handlesWebUris(IntentFilter filter) {
        // Require ACTION_VIEW, CATEGORY_BROWSEABLE, and at least one scheme
        if (!filter.hasAction(Intent.ACTION_VIEW)
            || !filter.hasCategory(Intent.CATEGORY_BROWSABLE)
            || filter.countDataSchemes() == 0) {
            return false;
        }
        // Now allow only the schemes "http" and "https"
        final Iterator<String> schemesIterator = filter.schemesIterator();
        while (schemesIterator.hasNext()) {
            final String scheme = schemesIterator.next();
            final boolean isWebScheme = "http".equals(scheme) || "https".equals(scheme);
            if (isWebScheme) {
                return true;
            }
        }
        return false;
    }

    private TestResult getResult() {
        final TestResult result;
        try {
            result = mResultQueue.poll(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (result == null) {
            throw new IllegalStateException("Activity didn't receive a Result in 5 seconds");
        }
        return result;
    }

    private static void grantInstantAppForegroundServicePermission() throws IOException {
        InstrumentationRegistry.getInstrumentation().getUiAutomation().grantRuntimePermission(
                InstrumentationRegistry.getContext().getPackageName(),
                android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE);
    }

    private static Intent makeIntent(String action, String category, String mimeType) {
        Intent intent = new Intent(action);
        if (category != null) {
            intent.addCategory(category);
        }
        if (mimeType != null) {
            intent.setType(mimeType);
        }
        return intent;
    }

    private static class ActivityBroadcastReceiver extends BroadcastReceiver {
        private final SynchronousQueue<TestResult> mQueue;
        public ActivityBroadcastReceiver(SynchronousQueue<TestResult> queue) {
            mQueue = queue;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                mQueue.offer(intent.getParcelableExtra(TestResult.EXTRA_TEST_RESULT),
                        5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private static class TestServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }
}