Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add background task #2664

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
51 changes: 51 additions & 0 deletions src/kotlin/flwr/src/main/java/dev/flower/android/Worker.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package dev.flower.android

import android.content.Context
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.Data
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequest
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import java.util.UUID
import java.util.concurrent.TimeUnit

class FlwrWorker(private val context: Context,
workerParams: WorkerParameters,
private val flwrClient: Client,
danielnugraha marked this conversation as resolved.
Show resolved Hide resolved
private val grpcRere: Boolean) : CoroutineWorker(context, workerParams) {
override suspend fun doWork(): Result {
if (grpcRere) {
inputData.getString("serverAddress")?.let { startFlowerRere(it, false, flwrClient) }
} else {
inputData.getString("serverAddress")?.let { startClient(it, false, flwrClient) }
}
val workManager: WorkManager = WorkManager.getInstance(context)
workManager.cancelWorkById(id)
return Result.success()
}

fun startFlwrPeriodicWorker(interval: Long, serverAddress: String) {
danielnugraha marked this conversation as resolved.
Show resolved Hide resolved
val constraints: Constraints = Constraints.Builder().build()

val workRequest: PeriodicWorkRequest = PeriodicWorkRequestBuilder<FlwrWorker>(
interval, TimeUnit.MINUTES
)
.setInitialDelay(0, TimeUnit.MILLISECONDS)
.setInputData(
Data.Builder()
.putString("serverAddress", serverAddress)
.build()
)
.setConstraints(constraints)
.build()

val uniqueWorkName = "FlwrWorker${UUID.randomUUID()}"

WorkManager.getInstance(context)
.enqueueUniquePeriodicWork(uniqueWorkName, ExistingPeriodicWorkPolicy.KEEP, workRequest)
}

}