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"
)

Register in Koin:

single { BackgroundHelper(androidContext()) }

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" />

Constructors

Link copied to clipboard
constructor(context: Context)

Types

Link copied to clipboard
object Companion

Functions

Link copied to clipboard
fun cancel(uniqueName: String)

Cancels a scheduled WorkManager task by uniqueName.

Link copied to clipboard
Link copied to clipboard
fun run(mode: BackgroundMode, task: BackgroundTask? = null, taskKey: String? = null)

Runs task (or the pre-registered worker at taskKey) using the given mode.

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
suspend fun stateOf(uniqueName: String): WorkInfo.State?

Returns the current WorkInfo.State of a WorkManager task, or null if not found.

Link copied to clipboard

Stops the foreground service if running.