Skip to content

Instantly share code, notes, and snippets.

@MAshhal
Created July 19, 2024 07:17
Show Gist options
  • Select an option

  • Save MAshhal/97e711bd4d05b8e0e204840f90157609 to your computer and use it in GitHub Desktop.

Select an option

Save MAshhal/97e711bd4d05b8e0e204840f90157609 to your computer and use it in GitHub Desktop.
Attach a broadcast receiver in Jetpack Compose
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
/**
* BroadcastReceiver
* @param action for intent filter
* @param onIntent callback when receive intent
*/
@Composable
fun BroadcastReceiver(
action: String,
onBroadcastReceived: (Intent) -> Unit
) {
val context = LocalContext.current
DisposableEffect(Unit) {
val receiver = object: BroadcastReceiver() {
private val tag = "InnerReceiver for $action"
override fun onReceive(context: Context, intent: Intent) {
Log.d(tag, "Broadcast received")
intent.extras?.keySet().forEach {
Log.d(tag, "$it -> ${intent.extras?.get(it)}")
}
// TODO: Filter the intents based on Intent filter
onBroadcastReceived(intent)
}
}
ContextCompat.registerReceiver(context, receiver, IntentFilter(action), ContextCompat.RECEIVER_NOT_EXPORTED)
onDispose { context.unregisterReceiver(receiver) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment