Why is onReceive called multiple times?

703 Views Asked by At

I am running a worker in a glance composable on android.

why is onReceive being continuously called in an infinite loop?

What am I missing here?

class MyWidget : GlanceAppWidget() {
    @Composable
    override fun Content() {
        val work = OneTimeWorkRequest.Builder(MyWorker::class.java).build()
        WorkManager.getInstance().enqueue(work)
    }
}


class MyWorker(
    private val context: Context,
    private val workerParameters: WorkerParameters
) : CoroutineWorker(context, workerParameters) {

    override suspend fun doWork(): Result {
        return Result.success()
    }
}

class GlanceReceiver : GlanceAppWidgetReceiver() {

    override val glanceAppWidget: GlanceAppWidget
        get() = MyWidget()

    override fun onReceive(context: Context, intent: Intent) {
        super.onReceive(context, intent)
    }
}

    //Dependencies
    implementation "androidx.work:work-runtime-ktx:2.7.1" // WorkManager with Coroutines
    implementation "androidx.glance:glance-appwidget:1.0.0-alpha03" //Glance


1

There are 1 best solutions below

0
On

That's because WM is disabling the on boot receiver when there are no workers scheduled. When an android app disables a receiver Android OS sends the PACKAGE_CHANGED broadcast event, causing the widget onReceive to be called.

https://issuetracker.google.com/115575872

For now the recommendation is to schedule a work with a long delay (e.g 10 years). We are working on a way to improve this.