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 
17 package android.permission.cts
18 
19 import android.content.ComponentName
20 import android.content.Context
21 import com.android.compatibility.common.util.SystemUtil
22 import org.junit.rules.TestRule
23 import org.junit.runner.Description
24 import org.junit.runners.model.Statement
25 
26 /** Rule that enables and disables the CTS NotificationListenerService */
27 class CtsNotificationListenerHelperRule(context: Context) : TestRule {
28 
29     private val notificationListenerComponentName =
30         ComponentName(context, CtsNotificationListenerService::class.java)
31 
applynull32     override fun apply(base: Statement, description: Description): Statement {
33         return object : Statement() {
34             override fun evaluate() {
35                 try {
36                     // Allow NLS used to verify notifications sent
37                     SystemUtil.runShellCommand(
38                         ALLOW_NLS_COMMAND + notificationListenerComponentName.flattenToString()
39                     )
40 
41                     base.evaluate()
42                 } finally {
43                     // Disallow NLS used to verify notifications sent
44                     SystemUtil.runShellCommand(
45                         DISALLOW_NLS_COMMAND + notificationListenerComponentName.flattenToString()
46                     )
47                 }
48             }
49         }
50     }
51 
52     companion object {
53         private const val ALLOW_NLS_COMMAND = "cmd notification allow_listener "
54         private const val DISALLOW_NLS_COMMAND = "cmd notification disallow_listener "
55     }
56 }
57