Это кажется интересным вопросом.
Лично мне нравится идея ДНР. Это просто, менее грязно и эффективно.
Но, скажем, нам нужно обратиться к более низким API, Вы можете использовать один подход, чтобы быть таким.
Вы можете иметь своего собственного слушателя уведомлений.
import android.annotation.SuppressLint;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
@SuppressLint("OverrideAbstract")
public class NotificationListener extends NotificationListenerService {
public static String TAG = NotificationListener.class.getSimpleName();
@Override
public void onNotificationPosted(StatusBarNotification sbm) {
/**
* This condition will define how you will identify your test is running
* You can have an in memory variable regarding it, or persistant variable,
* Or you can use Settings to store current state.
* You can have your own approach
*/
boolean condition = true; // say your test is running
if(condition)
cancelAllNotifications(); //Cancel all the notifications . No Disturbance
//else
// nothing.
}
}
Добавить это в Манифест
<service android:name=".NotificationListener"
android:label="@string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
Теперь для этого вам потребуется разрешение на доступ к уведомлениям. В вашем приложении точки входа (или перед тестированием согласно вашей логике) вы можете проверить это
if (!NotificationManagerCompat.getEnabledListenerPackages(getApplicationContext())
.contains(getApplicationContext().getPackageName())) {
//We dont have access
Intent intent= new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
//For API level 22+ you can directly use Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent,NOTIFICATION_REQUEST_CODE);
} else {
//Your own logic
Log.d(TAG, "You have Notification Access");
}
Это намерение откроет страницу, как показано ниже, которую пользователь должен будет разрешить для предоставления вам доступа.
Надеюсь, это поможет.