1 /*
2  * Copyright (C) 2021 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.bedstead.nene.notifications;
18 
19 import static android.Manifest.permission.MANAGE_NOTIFICATION_LISTENERS;
20 
21 import static com.android.bedstead.nene.utils.Tags.USES_DEVICESTATE;
22 
23 import android.app.NotificationManager;
24 import android.content.ComponentName;
25 import android.os.Build;
26 import android.service.notification.StatusBarNotification;
27 
28 import com.android.bedstead.nene.TestApis;
29 import com.android.bedstead.nene.exceptions.AdbException;
30 import com.android.bedstead.nene.exceptions.NeneException;
31 import com.android.bedstead.nene.packages.ComponentReference;
32 import com.android.bedstead.nene.permissions.PermissionContext;
33 import com.android.bedstead.nene.users.UserReference;
34 import com.android.bedstead.nene.utils.ShellCommand;
35 import com.android.bedstead.nene.utils.Tags;
36 import com.android.bedstead.nene.utils.Versions;
37 
38 import java.util.Collections;
39 import java.util.Set;
40 import java.util.concurrent.ConcurrentHashMap;
41 
42 /** Helper methods related to notifications. */
43 public final class Notifications {
44     public static final Notifications sInstance = new Notifications();
45 
46     private final Set<NotificationListener> mRegisteredListeners =
47             Collections.newSetFromMap(new ConcurrentHashMap<>());
48     private boolean mListenerAccessIsGranted;
49 
50     static final ComponentReference LISTENER_COMPONENT = TestApis.packages().component(
51             new ComponentName(
52                     TestApis.context().instrumentedContext().getPackageName(),
53                     NeneNotificationListenerService.class.getCanonicalName())
54     );
55 
Notifications()56     private Notifications() {
57 
58     }
59 
60     /**
61      * Creates a {@link NotificationListener}.
62      *
63      * <p>This is required before interacting with notifications in any way. It is recommended that
64      * you do this in a try() block so that the {@link NotificationListener} closes when you are
65      * finished with it.
66      */
createListener()67     public NotificationListener createListener() {
68         if (Tags.hasTag(USES_DEVICESTATE) && !Tags.hasTag(Tags.USES_NOTIFICATIONS)) {
69             throw new NeneException(
70                     "Tests which use Notifications must be annotated @NotificationsTest");
71         }
72 
73         NotificationListener notificationListener = new NotificationListener(this);
74         mRegisteredListeners.add(notificationListener);
75         initListenerIfRequired();
76 
77         return notificationListener;
78     }
79 
removeListener(NotificationListener listener)80     void removeListener(NotificationListener listener) {
81         mRegisteredListeners.remove(listener);
82         teardownListenerIfRequired();
83     }
84 
initListenerIfRequired()85     private void initListenerIfRequired() {
86         if (mRegisteredListeners.isEmpty()) {
87             return;
88         }
89 
90         if (mListenerAccessIsGranted) {
91             return;
92         }
93 
94         mListenerAccessIsGranted = true;
95         setNotificationListenerAccessGranted(
96                 LISTENER_COMPONENT, /* granted= */ true, TestApis.users().instrumented());
97     }
98 
teardownListenerIfRequired()99     private void teardownListenerIfRequired() {
100         if (!mRegisteredListeners.isEmpty()) {
101             return;
102         }
103 
104         if (!mListenerAccessIsGranted) {
105             return;
106         }
107 
108         mListenerAccessIsGranted = false;
109         setNotificationListenerAccessGranted(
110                 LISTENER_COMPONENT, /* granted= */ false, TestApis.users().instrumented());
111     }
112 
onNotificationPosted(StatusBarNotification sbn)113     void onNotificationPosted(StatusBarNotification sbn) {
114         for (NotificationListener notificationListener : mRegisteredListeners) {
115             notificationListener.onNotificationPosted(sbn);
116         }
117     }
118 
119     /**
120      * See {@link NotificationManager#setNotificationListenerAccessGranted(ComponentName, boolean)}.
121      */
setNotificationListenerAccessGranted( ComponentReference listener, boolean granted, UserReference user)122     public void setNotificationListenerAccessGranted(
123             ComponentReference listener, boolean granted, UserReference user) {
124         if (listener == null || user == null) {
125             throw new NullPointerException();
126         }
127 
128         if (!Versions.meetsMinimumSdkVersionRequirement(Build.VERSION_CODES.S)) {
129             String command = granted ? "allow_listener" : "disallow_listener";
130             try {
131                 ShellCommand.builder("cmd notification")
132                         .addOperand(command)
133                         .addOperand(listener.componentName().flattenToShortString())
134                         .allowEmptyOutput(true)
135                         .validate(String::isEmpty)
136                         .execute();
137             } catch (AdbException e) {
138                 throw new NeneException(
139                             "Error setting notification listener access " + granted, e);
140             }
141 
142             return;
143         }
144 
145         try (PermissionContext p =
146                      TestApis.permissions().withPermission(MANAGE_NOTIFICATION_LISTENERS)) {
147             TestApis.context().androidContextAsUser(user)
148                     .getSystemService(NotificationManager.class)
149                     .setNotificationListenerAccessGranted(
150                             listener.componentName(), granted, /* userGranted= */ false);
151         }
152     }
153 }
154