1 /*
2  * Copyright (C) 2019 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 
17 package com.android.cts.deviceowner;
18 
19 import android.service.notification.NotificationListenerService;
20 import android.service.notification.StatusBarNotification;
21 
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.concurrent.CountDownLatch;
25 import java.util.concurrent.TimeUnit;
26 import java.util.function.Consumer;
27 
28 /**
29  * A {@link NotificationListenerService} that allows tests to register to respond to notifications.
30  */
31 public class NotificationListener extends NotificationListenerService {
32 
33     private static final int TIMEOUT_SECONDS = 120;
34 
35     private static NotificationListener instance;
36     private static CountDownLatch connectedLatch = new CountDownLatch(1);
37 
getInstance()38     public static NotificationListener getInstance() {
39         try {
40             connectedLatch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
41         } catch (InterruptedException e) {
42             throw new RuntimeException("NotificationListener not connected.", e);
43         }
44 
45         return instance;
46     }
47 
48     private List<Consumer<StatusBarNotification>> mListeners = new ArrayList<>();
49 
addListener(Consumer<StatusBarNotification> listener)50     public void addListener(Consumer<StatusBarNotification> listener) {
51         mListeners.add(listener);
52     }
53 
clearListeners()54     public void clearListeners() {
55         mListeners.clear();
56     }
57 
58     @Override
onNotificationPosted(StatusBarNotification sbn)59     public void onNotificationPosted(StatusBarNotification sbn) {
60         for (Consumer<StatusBarNotification> listener : mListeners) {
61             listener.accept(sbn);
62         }
63     }
64 
65     @Override
onListenerConnected()66     public void onListenerConnected() {
67         instance = this;
68         connectedLatch.countDown();
69     }
70 }
71