Created
July 19, 2024 07:17
-
-
Save MAshhal/97e711bd4d05b8e0e204840f90157609 to your computer and use it in GitHub Desktop.
Attach a broadcast receiver in Jetpack Compose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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