1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package android.app.notification.current.cts;
17 
18 import static com.google.common.truth.Truth.assertWithMessage;
19 
20 import android.content.BroadcastReceiver;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.IntentFilter;
24 
25 import java.time.Duration;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.concurrent.CountDownLatch;
29 import java.util.concurrent.TimeUnit;
30 
31 public class NotificationManagerBroadcastReceiver extends BroadcastReceiver {
32     private CountDownLatch latch;
33     public List<Intent> results = new ArrayList<>();
34     public Context mContext;
35 
36     @Override
onReceive(Context context, Intent intent)37     public void onReceive(Context context, Intent intent) {
38         results.add(intent);
39         latch.countDown();
40     }
41 
getExtra(String key, int index, long timeout)42     public Object getExtra(String key, int index, long timeout) throws InterruptedException {
43         latch.await(timeout, TimeUnit.MILLISECONDS);
44         return results.get(index).getExtras().get(key);
45     }
46 
register(Context context, String action, int count)47     public void register(Context context, String action, int count) {
48         latch = new CountDownLatch(count);
49         mContext = context;
50         mContext.registerReceiver(
51                 this, new IntentFilter(action), Context.RECEIVER_EXPORTED);
52     }
53 
54     /**
55      * Waits at most {@code duration} until all the broadcasts specified in {@link #register} have
56      * arrived, and fails if they have not.
57      */
assertBroadcastsReceivedWithin(Duration duration)58     public void assertBroadcastsReceivedWithin(Duration duration) throws InterruptedException {
59         boolean received = latch.await(duration.toMillis(), TimeUnit.MILLISECONDS);
60         assertWithMessage(
61                 "Still missing " + latch.getCount() + " broadcasts after " + duration)
62                 .that(received).isTrue();
63     }
64 
unregister()65     public void unregister() {
66         mContext.unregisterReceiver(this);
67     }
68 }
69