From 87af10301271965d8af3b0db36e49b7aeab7007c Mon Sep 17 00:00:00 2001 From: Michelle Tang Date: Tue, 5 Aug 2025 10:20:20 -0400 Subject: [PATCH] Add additional foreground service timeout check. --- .../service/GenericForegroundService.kt | 33 +++++++++++++------ 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/org/thoughtcrime/securesms/service/GenericForegroundService.kt b/app/src/main/java/org/thoughtcrime/securesms/service/GenericForegroundService.kt index 9d7450435e..82aee08d05 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/service/GenericForegroundService.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/service/GenericForegroundService.kt @@ -178,6 +178,10 @@ class GenericForegroundService : Service() { override fun onTimeout(startId: Int, foregroundServiceType: Int) { Log.i(TAG, "[onTimeout] startId: $startId, fgsType: $foregroundServiceType") + stopDueToTimeout() + } + + private fun stopDueToTimeout() { lock.withLock { hasTimedOut = true allActiveMessages.clear() @@ -217,16 +221,25 @@ class GenericForegroundService : Service() { private fun postObligatoryForegroundNotification(active: Entry) { lastPosted = active - startForeground( - NOTIFICATION_ID, - NotificationCompat.Builder(this, active.channelId) - .setSmallIcon(active.iconRes) - .setContentTitle(active.title) - .setProgress(active.progressMax, active.progress, active.indeterminate) - .setContentIntent(PendingIntent.getActivity(this, 0, MainActivity.clearTop(this), mutable())) - .setVibrate(longArrayOf(0)) - .build() - ) + try { + startForeground( + NOTIFICATION_ID, + NotificationCompat.Builder(this, active.channelId) + .setSmallIcon(active.iconRes) + .setContentTitle(active.title) + .setProgress(active.progressMax, active.progress, active.indeterminate) + .setContentIntent(PendingIntent.getActivity(this, 0, MainActivity.clearTop(this), mutable())) + .setVibrate(longArrayOf(0)) + .build() + ) + } catch (e: Exception) { + if (Build.VERSION.SDK_INT >= 31 && e.message?.contains("Time limit", ignoreCase = true) == true) { + Log.w(TAG, "Foreground service timed out, but not in onTimeout call", e) + stopDueToTimeout() + } else { + throw e + } + } } private fun updateEntry(id: Int, transform: (Entry) -> Entry) {