This seems like an interesting question.
Personally, I like the DND idea. It is simple, less messy and effective.
But say we need to reach out to lower APIs, You can use one approach to be like this.
You can have your own Notification Listener.
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.
}
}
Add this to Manifest
<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>
Now, you will need Notification Access Permission for this. In your application, entry points(or before test as per your logic) you can check this
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");
}
This intent will open a page like below, which user will have to enable for giving you Access.

Hope this helps.