CodexBloom - Programming Q&A Platform

how to update UI from Service using BroadcastReceiver in Android 14 with Jetpack Compose

👀 Views: 68 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-23
android jetpack-compose broadcast-receiver Kotlin

I'm optimizing some code but I need help solving I'm working with an scenario where I'm trying to update the UI in my Jetpack Compose application from a background service using a `BroadcastReceiver`. I'm sending a broadcast from the service when a specific task is completed, but the UI does not reflect the changes. I'm using Android 14 and I suspect it might be related to how I'm implementing the `BroadcastReceiver`. In my service, I send the broadcast like this: ```kotlin val intent = Intent("com.example.ACTION_UPDATE") intent.putExtra("status", "Task Completed") sendBroadcast(intent) ``` The `BroadcastReceiver` is registered in my Composable function: ```kotlin @Composable fun MyScreen() { val context = LocalContext.current val status = remember { mutableStateOf("") } val receiver = remember { object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { status.value = intent?.getStringExtra("status") ?: "" } }} LaunchedEffect(Unit) { val filter = IntentFilter("com.example.ACTION_UPDATE") context.registerReceiver(receiver, filter) onDispose { context.unregisterReceiver(receiver) } } Text(text = status.value) } ``` The scenario seems to stem from the fact that the UI does not update when the broadcast is received. I have checked the logs, and the `onReceive()` method is indeed being triggered, but the `status.value` does not cause a recomposition of the UI. I've also tried using `mutableStateOf` directly in the `MyScreen()` function, but that didn't help either. I suspect it may have something to do with state management in Jetpack Compose, but I'm not sure how to resolve this. Is there a better way to handle this scenario or any best practices I should be aware of? This is for a microservice running on Debian. I'm developing on Windows 10 with Kotlin. Any suggestions would be helpful. I'm working on a web app that needs to handle this. Cheers for any assistance!