Проверить существование notification

Есть ForegroundService с постоянно висящим уведомлением для того, чтобы служба поддерживалась даже при закрытии приложения. Всё прекрасно работает.

Как сделать отслеживание наличия уведомления? То есть если оно не висит, то вызывать его, а если висит, то не вызывать. Иначе при постоянном запуске службы оно постоянно вызывается повторно и надоедает.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Intent notificationIntent = new Intent(this, StartActivity.class);

    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Title")
            .setContentText("Text")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pendingIntent)
            .build();

    startForeground(1, notification);

    return START_NOT_STICKY;
}

Ответы (1 шт):

Автор решения: Alex_Skvortsov

Для Android API >= 23 возможно такое решение:

NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
StatusBarNotification[] notifications = mNotificationManager.getActiveNotifications();
for (StatusBarNotification notification : notifications) {
    if (notification.getId() == 100) {
        // Do something.
    }
}

Так же Вы можете сохранять к каком-то флаге: было отправлено уведомление раньше, или нет.

→ Ссылка