'Android widget OnReceive() being called multiple times when running WorkManager request
I have an app which has a home screen widget via GlanceAppWidget().
I would like to run a worker inside the Content() function of GlanceAppWidget(). I have used enqueue(work) from WorkManager api to successfully execute my worker.
The problem is that onReceive is getting called multiple (infinite) number of times. How can I run the worker once without having onReceive called multiple times?
class MyWidget : GlanceAppWidget() {
@Composable
override fun Content() {
val work = OneTimeWorkRequest.Builder(MyWorker::class.java).build()
WorkManager.getInstance().enqueue(work)
//some composable/ui code that consumes worker output
}
}
class MyWorker(
private val context: Context,
private val workerParameters: WorkerParameters
) : CoroutineWorker(context, workerParameters) {
override suspend fun doWork(): Result {
return try {
startForegroundService()
//some task here
Result.Success.success(
workDataOf(
"MyKey" to "worker completed successfully"
)
)
} catch (throwable: Throwable) {
Result.failure()
}
}
private suspend fun startForegroundService() {
setForeground(
ForegroundInfo(
Random.nextInt(),
NotificationCompat.Builder(context, "download_channel")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentText("Downloading...")
.setContentTitle("Download in progress")
.build()
)
)
}
}
class GlanceReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget
get() = MyWidget()
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
}
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
super.onUpdate(context, appWidgetManager, appWidgetIds)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
