Broadcast Receivers let your Android app respond to system or application events without constantly checking for changes. They are commonly used for events like power connection, battery updates, and custom app notifications.
What is a Broadcast Receiver?
A Broadcast Receiver listens for broadcast Intents sent by:
- Android system
- Your app
- Other apps (when permitted)
Examples of broadcasts include:
- Charger connected
- Device boot completed
- Airplane mode changed
- Custom events within your app
Create a Broadcast Receiver
Create a class that extends BroadcastReceiver.
class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == Intent.ACTION_POWER_CONNECTED) {
Toast.makeText(context, "Power Connected", Toast.LENGTH_SHORT).show()
}
}
}
Register the Receiver
Register the receiver dynamically inside your Activity or Fragment.
private val receiver = MyReceiver()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val filter = IntentFilter(Intent.ACTION_POWER_CONNECTED)
ContextCompat.registerReceiver(
this,
receiver,
filter,
ContextCompat.RECEIVER_NOT_EXPORTED
)
}
Unregister it when it's no longer needed.
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(receiver)
}
Send a Custom Broadcast
val intent = Intent("com.example.ACTION_UPDATE")
intent.putExtra("message", "Hello!")
sendBroadcast(intent)
Receive the message:
class CustomReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val message = intent?.getStringExtra("message")
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}
Common Broadcasts
| Action | Description |
|---|---|
ACTION_POWER_CONNECTED |
Charger connected |
ACTION_POWER_DISCONNECTED |
Charger removed |
ACTION_BOOT_COMPLETED |
Device finished booting |
ACTION_AIRPLANE_MODE_CHANGED |
Airplane mode changed |
Best Practices
- Prefer dynamic registration whenever possible.
- Always unregister dynamically registered receivers.
- Keep
onReceive()lightweight since it runs on the main thread. - Use unique action names for custom broadcasts (for example,
com.example.myapp.ACTION_UPDATE).
Conclusion
Broadcast Receivers are an essential part of Android development. They allow your app to react to system and application events efficiently. By registering receivers only when needed and keeping the receiver logic simple, you can build responsive and battery-friendly Android applications.

Top comments (0)