Wed. Jan 15th, 2025

Broadcast Receivers in Android

A Broadcast Receiver is a component in Android used to listen for system-wide or app-specific broadcast messages (or events). These messages can be sent by the system (e.g., when the device boots) or by an application.


Types of Broadcasts

  1. System Broadcasts: Sent by the Android system (e.g., battery level changes, connectivity changes, or incoming calls).
  2. Custom Broadcasts: Sent by applications to communicate events within the app or to other apps.

How Broadcast Receivers Work

  • Intent: Broadcast messages are sent using an Intent.
  • Receiver: A Broadcast Receiver listens for these intents and executes code when the intent is received.

Declaring a Broadcast Receiver

  1. Static Receiver (Manifest Declaration)
    Used for system-wide broadcasts or events. Declared in the AndroidManifest.xml.
  2. Dynamic Receiver (Code Registration)
    Registered at runtime, often used for app-specific needs. Declared using Context.registerReceiver.

Steps to Implement a Broadcast Receiver

1. Create the Receiver Class

class MyBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        // Handle the broadcast
        if (intent?.action == Intent.ACTION_BOOT_COMPLETED) {
            Toast.makeText(context, "Device Booted", Toast.LENGTH_SHORT).show()
        }
    }
}

2. Static Registration in Manifest

<receiver android:name=".MyBroadcastReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>
  • Add the required permission in the manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

3. Dynamic Registration

class MainActivity : AppCompatActivity() {

    private lateinit var myReceiver: MyBroadcastReceiver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        myReceiver = MyBroadcastReceiver()

        // Register the receiver dynamically
        val intentFilter = IntentFilter().apply {
            addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED)
        }
        registerReceiver(myReceiver, intentFilter)
    }

    override fun onDestroy() {
        super.onDestroy()
        // Unregister the receiver
        unregisterReceiver(myReceiver)
    }
}

Broadcast Sending

To send a custom broadcast:

Send a Broadcast

val intent = Intent("com.example.MY_CUSTOM_ACTION")
intent.putExtra("key", "value")
sendBroadcast(intent)

Receive a Custom Broadcast

Add a filter for the custom action in your receiver:

val intentFilter = IntentFilter("com.example.MY_CUSTOM_ACTION")
registerReceiver(myReceiver, intentFilter)

Common System Broadcast Actions

ActionDescription
Intent.ACTION_BOOT_COMPLETEDTriggered when the device boots up.
Intent.ACTION_BATTERY_LOWTriggered when the battery is low.
Intent.ACTION_AIRPLANE_MODE_CHANGEDTriggered when airplane mode changes.
Intent.ACTION_POWER_CONNECTEDTriggered when power is connected.
Intent.ACTION_POWER_DISCONNECTEDTriggered when power is disconnected.

Best Practices

  1. Static vs Dynamic Registration: Use static registration for system-level events and dynamic registration for app-specific needs.
  2. Security: Restrict broadcasts using permissions to prevent misuse by other apps.
  3. Performance: Avoid long-running operations in onReceive as it runs on the main thread. Use a service if needed.

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *