Junior
How to connect a BroadcastReceiver to receive messages in Android?
sobes.tech AI
Answer from AI
There are two main methods:
-
Dynamic registration:
- Registered and unregistered programmatically in the code.
- Lives as long as the object that registered it is active.
- Used for events that do not need to be received constantly or when the application is inactive (e.g., when changing orientation, battery level).
// In Activity or Fragment private val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { // Handling the received message intent?.action?.let { action -> when (action) { Intent.ACTION_BATTERY_CHANGED -> { // Handling battery change } // Other actions } } } } override fun onResume() { super.onResume() val intentFilter = IntentFilter().apply { addAction(Intent.ACTION_BATTERY_CHANGED) // Other actions } registerReceiver(receiver, intentFilter) } override fun onPause() { super.onPause() unregisterReceiver(receiver) } -
Static registration:
- Declared in the manifest file (
AndroidManifest.xml). - Lives longer than the lifecycle of the component that registered it. Can receive messages even when the application is inactive (with some limitations in recent Android versions).
- Used for system events that need to be received constantly (e.g., device boot).
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.yourapp"> <application ...> <receiver android:name=".MyBroadcastReceiver" android:exported="true"> <!-- Important for Android 12+ --> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.AIRPLANE_MODE" /> <!-- Other actions --> </intent-filter> </receiver> ... </application> </manifest>// BroadcastReceiver class class MyBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { // Handling the received message intent?.action?.let { action -> when (action) { Intent.ACTION_BOOT_COMPLETED -> { // Handling boot completion } Intent.ACTION_AIRPLANE_MODE_CHANGED -> { // Handling airplane mode change } // Other actions } } } } - Declared in the manifest file (