|
| 1 | +package com.powersync.demo.backgroundsync |
| 2 | + |
| 3 | +import android.app.Notification |
| 4 | +import android.content.Intent |
| 5 | +import android.content.pm.ServiceInfo |
| 6 | +import android.os.Build |
| 7 | +import androidx.core.app.NotificationChannelCompat |
| 8 | +import androidx.core.app.NotificationManagerCompat |
| 9 | +import androidx.core.app.ServiceCompat |
| 10 | +import androidx.lifecycle.LifecycleService |
| 11 | +import androidx.lifecycle.lifecycleScope |
| 12 | +import co.touchlab.kermit.Logger |
| 13 | +import com.powersync.PowerSyncDatabase |
| 14 | +import com.powersync.connector.supabase.SupabaseConnector |
| 15 | +import com.powersync.sync.SyncStatusData |
| 16 | +import io.github.jan.supabase.auth.status.SessionStatus |
| 17 | +import kotlinx.atomicfu.atomic |
| 18 | +import kotlinx.coroutines.CancellationException |
| 19 | +import kotlinx.coroutines.launch |
| 20 | +import org.koin.android.ext.android.inject |
| 21 | + |
| 22 | +class SyncService: LifecycleService() { |
| 23 | + |
| 24 | + private val connector: SupabaseConnector by inject() |
| 25 | + private val database: PowerSyncDatabase by inject() |
| 26 | + private var holdsServiceLock = false |
| 27 | + |
| 28 | + private val notificationManager get()= NotificationManagerCompat.from(this) |
| 29 | + |
| 30 | + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { |
| 31 | + super.onStartCommand(intent, flags, startId) |
| 32 | + |
| 33 | + holdsServiceLock = SERVICE_RUNNING.compareAndSet(false, true) |
| 34 | + if (!holdsServiceLock) { |
| 35 | + stopSelf() |
| 36 | + return START_NOT_STICKY |
| 37 | + } |
| 38 | + |
| 39 | + createNotificationChannel() |
| 40 | + ServiceCompat.startForeground( |
| 41 | + this, |
| 42 | + startId, |
| 43 | + buildNotification(), |
| 44 | + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { |
| 45 | + ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC |
| 46 | + } else { |
| 47 | + 0 |
| 48 | + } |
| 49 | + ) |
| 50 | + |
| 51 | + lifecycleScope.launch { |
| 52 | + database.currentStatus.asFlow().collect { |
| 53 | + try { |
| 54 | + Logger.i("Sync service received status $it") |
| 55 | + notificationManager.notify(startId, buildNotification(it)) |
| 56 | + } catch (e: SecurityException) { |
| 57 | + Logger.d("Ignoring security exception when updating notification", e) |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + lifecycleScope.launch { |
| 63 | + connector.sessionStatus.collect { |
| 64 | + when (it) { |
| 65 | + is SessionStatus.Authenticated -> { |
| 66 | + database.connect(connector) |
| 67 | + } |
| 68 | + is SessionStatus.NotAuthenticated -> { |
| 69 | + database.disconnectAndClear() |
| 70 | + Logger.i("Stopping sync service, user logged out") |
| 71 | + return@collect |
| 72 | + } |
| 73 | + else -> { |
| 74 | + // Ignore |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + }.invokeOnCompletion { |
| 79 | + if (it !is CancellationException) { |
| 80 | + this.lifecycle.currentState |
| 81 | + stopSelf(startId) |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + return START_NOT_STICKY |
| 86 | + } |
| 87 | + |
| 88 | + override fun onTimeout(startId: Int, fgsType: Int) { |
| 89 | + // Background sync was running for too long without the app ever being open... |
| 90 | + stopSelf(startId) |
| 91 | + } |
| 92 | + |
| 93 | + override fun onDestroy() { |
| 94 | + if (holdsServiceLock) { |
| 95 | + SERVICE_RUNNING.value = false |
| 96 | + } |
| 97 | + |
| 98 | + super.onDestroy() |
| 99 | + } |
| 100 | + |
| 101 | + private fun createNotificationChannel() { |
| 102 | + val channel = NotificationChannelCompat.Builder(CHANNEL_ID, NotificationManagerCompat.IMPORTANCE_LOW) |
| 103 | + .setName(getString(R.string.background_channel_name)) |
| 104 | + .build() |
| 105 | + notificationManager.createNotificationChannel(channel) |
| 106 | + } |
| 107 | + |
| 108 | + private fun buildNotification(state: SyncStatusData? = null): Notification = Notification.Builder(this, CHANNEL_ID).apply { |
| 109 | + setContentTitle(getString(R.string.sync_notification_title)) |
| 110 | + setSmallIcon(R.drawable.ic_launcher_foreground) |
| 111 | + |
| 112 | + if (state != null) { |
| 113 | + if (state.uploading || state.downloading) { |
| 114 | + setProgress(0, 0, true) |
| 115 | + } |
| 116 | + } |
| 117 | + }.build() |
| 118 | + |
| 119 | + private companion object { |
| 120 | + val CHANNEL_ID = "background_sync" |
| 121 | + val SERVICE_RUNNING = atomic(false) |
| 122 | + } |
| 123 | +} |
0 commit comments