@@ -14,6 +14,7 @@ import com.powersync.PowerSyncDatabase
1414import com.powersync.connector.supabase.SupabaseConnector
1515import com.powersync.sync.SyncStatusData
1616import io.github.jan.supabase.auth.status.SessionStatus
17+ import kotlinx.atomicfu.atomic
1718import kotlinx.coroutines.CancellationException
1819import kotlinx.coroutines.launch
1920import org.koin.android.ext.android.inject
@@ -22,14 +23,20 @@ class SyncService: LifecycleService() {
2223
2324 private val connector: SupabaseConnector by inject()
2425 private val database: PowerSyncDatabase by inject()
26+ private var holdsServiceLock = false
2527
2628 private val notificationManager get()= NotificationManagerCompat .from(this )
2729
2830 override fun onStartCommand (intent : Intent ? , flags : Int , startId : Int ): Int {
2931 super .onStartCommand(intent, flags, startId)
3032
31- createNotificationChannel()
33+ holdsServiceLock = SERVICE_RUNNING .compareAndSet(false , true )
34+ if (! holdsServiceLock) {
35+ stopSelf()
36+ return START_NOT_STICKY
37+ }
3238
39+ createNotificationChannel()
3340 ServiceCompat .startForeground(
3441 this ,
3542 startId,
@@ -44,6 +51,7 @@ class SyncService: LifecycleService() {
4451 lifecycleScope.launch {
4552 database.currentStatus.asFlow().collect {
4653 try {
54+ Logger .i(" Sync service received status $it " )
4755 notificationManager.notify(startId, buildNotification(it))
4856 } catch (e: SecurityException ) {
4957 Logger .d(" Ignoring security exception when updating notification" , e)
@@ -82,6 +90,14 @@ class SyncService: LifecycleService() {
8290 stopSelf(startId)
8391 }
8492
93+ override fun onDestroy () {
94+ if (holdsServiceLock) {
95+ SERVICE_RUNNING .value = false
96+ }
97+
98+ super .onDestroy()
99+ }
100+
85101 private fun createNotificationChannel () {
86102 val channel = NotificationChannelCompat .Builder (CHANNEL_ID , NotificationManagerCompat .IMPORTANCE_LOW )
87103 .setName(getString(R .string.background_channel_name))
@@ -101,6 +117,7 @@ class SyncService: LifecycleService() {
101117 }.build()
102118
103119 private companion object {
104- private val CHANNEL_ID = " background_sync"
120+ val CHANNEL_ID = " background_sync"
121+ val SERVICE_RUNNING = atomic(false )
105122 }
106123}
0 commit comments