BackgroundHelper
Unified helper for running tasks in the background.
Picks the right Android mechanism automatically based on BackgroundMode:
// 1. Short async work tied to a ViewModel
backgroundHelper.run(
mode = BackgroundMode.Coroutine(viewModelScope),
task = { fetchData() }
)
// 2. One-shot deferred task (survives app kill)
backgroundHelper.registerWorker("sync") { syncContacts() }
backgroundHelper.run(
mode = BackgroundMode.WorkManagerOnce(
uniqueName = "sync",
constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
)
// 3. Periodic sync every 15 minutes
backgroundHelper.registerWorker("periodic-sync") { syncData() }
backgroundHelper.run(
mode = BackgroundMode.WorkManagerPeriodic(
uniqueName = "periodic-sync",
intervalMinutes = 15
)
)
// 4. Long-running foreground service (music, GPS, download)
backgroundHelper.registerWorker("download") { downloadFile() }
backgroundHelper.run(
mode = BackgroundMode.Foreground(
channelId = "downloads",
channelName = "Downloads",
title = "Downloading…",
icon = R.drawable.ic_download
),
taskKey = "download"
)Content copied to clipboard
Register in Koin:
single { BackgroundHelper(androidContext()) }Content copied to clipboard
Declare in AndroidManifest.xml:
<service
android:name="dev.kindling.android.natif.KForegroundService"
android:foregroundServiceType="dataSync"
android:exported="false" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />Content copied to clipboard
Functions
Link copied to clipboard
Cancels a scheduled WorkManager task by uniqueName.
Link copied to clipboard
Registers a suspend task under a key so it can be referenced by BackgroundMode.WorkManagerOnce, BackgroundMode.WorkManagerPeriodic, or BackgroundMode.Foreground.
Link copied to clipboard
Link copied to clipboard
Schedules the next occurrence of a WorkManagerScheduled task. Called automatically by run — call it again inside your worker to re-schedule for the following week:
Link copied to clipboard
Returns the current WorkInfo.State of a WorkManager task, or null if not found.
Link copied to clipboard
Stops the foreground service if running.