From b0c6eeb9f7af7845cabdac58a87f183551a053a1 Mon Sep 17 00:00:00 2001 From: Torsten Grote Date: Wed, 13 Oct 2021 08:35:09 -0300 Subject: [PATCH] Clean up stuck notifications when service gets killed --- .../ConfigurableBackupTransportService.kt | 2 +- .../ui/notification/BackupNotificationManager.kt | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/stevesoltys/seedvault/transport/ConfigurableBackupTransportService.kt b/app/src/main/java/com/stevesoltys/seedvault/transport/ConfigurableBackupTransportService.kt index 69a3513f..1d67988d 100644 --- a/app/src/main/java/com/stevesoltys/seedvault/transport/ConfigurableBackupTransportService.kt +++ b/app/src/main/java/com/stevesoltys/seedvault/transport/ConfigurableBackupTransportService.kt @@ -53,7 +53,7 @@ class ConfigurableBackupTransportService : Service(), KoinComponent { override fun onDestroy() { super.onDestroy() - notificationManager.onBackupBackgroundFinished() + notificationManager.onServiceDestroyed() transport = null Log.d(TAG, "Service destroyed.") } diff --git a/app/src/main/java/com/stevesoltys/seedvault/ui/notification/BackupNotificationManager.kt b/app/src/main/java/com/stevesoltys/seedvault/ui/notification/BackupNotificationManager.kt index b7b03733..8b143160 100644 --- a/app/src/main/java/com/stevesoltys/seedvault/ui/notification/BackupNotificationManager.kt +++ b/app/src/main/java/com/stevesoltys/seedvault/ui/notification/BackupNotificationManager.kt @@ -144,8 +144,22 @@ internal class BackupNotificationManager(private val context: Context) { nm.notify(NOTIFICATION_ID_BACKGROUND, notification) } - fun onBackupBackgroundFinished() { + fun onServiceDestroyed() { nm.cancel(NOTIFICATION_ID_BACKGROUND) + // Cancel left-over notifications that are still ongoing. + // + // We have seen a race condition where the service was taken down at the same time + // as BackupObserver#backupFinished() was called, early enough to miss the cancel. + // + // This won't bring back the expected finish notification in this case, + // but at least we don't leave stuck notifications laying around. + nm.activeNotifications.forEach { notification -> + // only consider ongoing notifications in our ID space (storage backup uses > 1000) + if (notification.isOngoing && notification.id < 1000) { + Log.w(TAG, "Needed to clean up notification with ID ${notification.id}") + nm.cancel(notification.id) + } + } } fun onBackupFinished(success: Boolean, numBackedUp: Int?) {