From c0db88960c824576e52a251b4e5e34cd4dc82f0e Mon Sep 17 00:00:00 2001 From: Greyson Parrelli Date: Wed, 11 May 2022 13:42:40 -0400 Subject: [PATCH] Make FcmFetchForegroundService stop itself. --- .../gcm/FcmFetchForegroundService.kt | 26 +++++++++++++++++-- .../securesms/gcm/FcmFetchManager.kt | 2 +- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/org/thoughtcrime/securesms/gcm/FcmFetchForegroundService.kt b/app/src/main/java/org/thoughtcrime/securesms/gcm/FcmFetchForegroundService.kt index 18e4503c9..ff9ec27e9 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/gcm/FcmFetchForegroundService.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/gcm/FcmFetchForegroundService.kt @@ -2,6 +2,7 @@ package org.thoughtcrime.securesms.gcm import android.app.PendingIntent import android.app.Service +import android.content.Context import android.content.Intent import android.os.IBinder import androidx.core.app.NotificationCompat @@ -16,7 +17,22 @@ import org.thoughtcrime.securesms.notifications.NotificationIds */ class FcmFetchForegroundService : Service() { - private val TAG = Log.tag(FcmFetchForegroundService::class.java) + companion object { + private val TAG = Log.tag(FcmFetchForegroundService::class.java) + private const val KEY_STOP_SELF = "stop_self" + + /** + * Android's requirement for calling [startForeground] is enforced _even if your service was stopped before it started_. + * That means we can't just stop it normally, since we don't know if it got to start yet. + * The safest thing to do is to just tell it to start so it can call [startForeground] and then stop itself. + * Fun. + */ + fun buildStopIntent(context: Context): Intent { + return Intent(context, FcmFetchForegroundService::class.java).apply { + putExtra(KEY_STOP_SELF, true) + } + } + } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { startForeground( @@ -31,7 +47,13 @@ class FcmFetchForegroundService : Service() { .build() ) - return START_STICKY + return if (intent != null && intent.getBooleanExtra(KEY_STOP_SELF, false)) { + stopForeground(true) + stopSelf() + START_NOT_STICKY + } else { + START_STICKY + } } override fun onDestroy() { diff --git a/app/src/main/java/org/thoughtcrime/securesms/gcm/FcmFetchManager.kt b/app/src/main/java/org/thoughtcrime/securesms/gcm/FcmFetchManager.kt index 1448a355c..3abc49b56 100644 --- a/app/src/main/java/org/thoughtcrime/securesms/gcm/FcmFetchManager.kt +++ b/app/src/main/java/org/thoughtcrime/securesms/gcm/FcmFetchManager.kt @@ -66,8 +66,8 @@ object FcmFetchManager { if (activeCount <= 0) { Log.i(TAG, "No more active. Stopping.") - context.stopService(Intent(context, FcmFetchForegroundService::class.java)) context.stopService(Intent(context, FcmFetchBackgroundService::class.java)) + context.startService(FcmFetchForegroundService.buildStopIntent(context)) } } }