Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 104 ยท Activities and the Lifecycle

Broadcast Receivers

Learn Android broadcast receivers: manifest vs context registration, system broadcasts, Android 8 limits, exported flags, goAsync, ordered broadcasts and Flow instead of LocalBroadcastManager.

Things happen on a phone without your app doing anything: the battery gets low, the charger is plugged in, the device finishes booting, airplane mode switches on, another app is installed. Android announces such events to every app that cares by sending a broadcast, an Intent delivered to any number of listeners at once. The component that listens is the BroadcastReceiver, the third of the four Android components.

Receivers are small and sharp tools. They are meant to react quickly and hand the real work to something else. Because broadcasts could wake every installed app at once, Android has restricted them heavily since Android 8, which is why old tutorials about "listen for connectivity changes in the manifest" no longer work. This lesson covers the two ways to register, what the system still delivers to the manifest, the time limits, the exported rules, goAsync(), ordered broadcasts and what replaced LocalBroadcastManager. The Android classes cannot run on this site, so the real code is read-only. The TryIts are stand-ins in plain Kotlin that model delivery rules, ordered broadcasts and a modern replacement built from SharedFlow, which is real.

A receiver in two parts

A receiver is a class with one method, and a registration that tells the system which broadcasts to hand to it.

Kotlin
// read-only example
class BatteryLowReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        when (intent.action) {
            Intent.ACTION_BATTERY_LOW -> Log.d("Battery", "Low battery: pause heavy work")
            Intent.ACTION_POWER_CONNECTED -> Log.d("Battery", "Charging")
        }
    }
}

onReceive runs on the main thread, and the system expects it to return quickly. The receiver object is only alive for the duration of that call; it is not a place to keep state or start a long task (more below).

There are two ways to register.

1. In the manifest (static). The system can start your app's process to deliver the broadcast, even if no activity exists.

XML
<!-- read-only example -->
<receiver android:name=".BootReceiver" android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

2. In code (dynamic, context-registered). The receiver lives as long as the component that registered it, and you must unregister it.

Kotlin
// read-only example: a Compose screen that listens while it is visible
@Composable
fun ChargingIndicator(onChange: (Boolean) -> Unit) {
    val context = LocalContext.current
    DisposableEffect(context) {
        val receiver = object : BroadcastReceiver() {
            override fun onReceive(c: Context, intent: Intent) {
                onChange(intent.action == Intent.ACTION_POWER_CONNECTED)
            }
        }
        val filter = IntentFilter().apply {
            addAction(Intent.ACTION_POWER_CONNECTED)
            addAction(Intent.ACTION_POWER_DISCONNECTED)
        }
        ContextCompat.registerReceiver(context, receiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED)
        onDispose { context.unregisterReceiver(receiver) }
    }
}

DisposableEffect (see Side Effects) is the Compose way to pair register with unregister. In an activity you would register in onStart() and unregister in onStop() (see The Activity Lifecycle), so the receiver is never leaked. A receiver registered with an activity context and never removed keeps the activity alive, the leak described in Context in Android.

What can still be declared in the manifest

Before Android 8 (API 26), an app could listen in its manifest for almost any broadcast. Hundreds of apps woke up whenever the network changed, the screen turned on or a photo was taken, and phones drained. Since API 26, apps that target 26 or higher cannot receive most implicit broadcasts through manifest receivers.

  • An implicit broadcast is not aimed at a specific app (such as ACTION_POWER_CONNECTED).
  • An explicit broadcast targets your package or component (intent.setPackage("com.example.app")); it is always delivered.
  • A short exception list of implicit broadcasts is still allowed in the manifest because they are rare or app-specific: BOOT_COMPLETED, LOCKED_BOOT_COMPLETED, LOCALE_CHANGED, MY_PACKAGE_REPLACED, SMS and some Bluetooth, USB and account events (the official list is in the Android documentation).
  • Everything else, for example ACTION_SCREEN_ON, ACTION_POWER_CONNECTED, ACTION_BATTERY_LOW and the connectivity broadcasts, you can only receive with a context-registered receiver while your app is running.

The connectivity broadcast CONNECTIVITY_ACTION is deprecated; use ConnectivityManager.registerDefaultNetworkCallback (see Errors and Offline-First). Anything you want to do periodically in the background belongs in WorkManager with constraints such as "charging" or "network connected", which is the supported replacement for most old broadcast-triggered jobs.

Recent releases keep tightening this: for apps targeting Android 15 and higher, a BOOT_COMPLETED receiver may not start several foreground service types. If you rely on a boot receiver to start something, check the current platform rules.

Exported or not

Receivers can be reached by other apps, so access matters.

  • In the manifest, android:exported must be set explicitly (required since Android 12 for any receiver with an intent filter). Use false for broadcasts that only your app sends; true for system broadcasts or deliberate public ones. For protection, add android:permission to demand a permission from the sender.
  • When you register in code and your app targets Android 14 (API 34) or higher, you must pass either RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED for non-system broadcasts, or the system throws a SecurityException. ContextCompat.registerReceiver makes this compatible with older versions. Choose RECEIVER_NOT_EXPORTED unless other apps must really talk to you.
  • When sending to your own receivers, set the package (intent.setPackage(packageName)) so the broadcast is explicit and no other app can intercept it. sendBroadcast(intent, "com.example.PERMISSION") restricts receivers to apps holding a permission.

Treat the contents of any received broadcast as untrusted input, just like intents from other apps (see Security basics).

The first stand-in models who gets a broadcast under these rules: manifest and dynamic receivers, implicit and explicit broadcasts, the allowlist and exported receivers.

Kotlin Who receives a broadcast? (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Time limits and goAsync

Because onReceive() runs on the main thread, anything slow in it freezes the app, and the system is strict about time. A broadcast receiver that does not finish within about 10 seconds (for foreground broadcasts; 60 seconds for background ones) causes an ANR (Application Not Responding). More importantly, when onReceive() returns, the system considers the broadcast handled and may kill your process at once if nothing else is keeping it alive. So these do not work:

  • starting a plain thread or coroutine in onReceive and returning (the process may be killed mid-work)
  • binding to a service from a receiver (not allowed; startService is also restricted in the background)
  • showing a dialog

The options are:

  1. Do almost nothing in onReceive: read the intent, schedule real work with WorkManager, return.
  2. Use goAsync() for a short job (a database write, a small network call). It returns a PendingResult; the broadcast stays "in progress" until you call finish(). You still have only seconds, so it is for short jobs, and you must call finish() in a finally.
  3. Start a foreground service if the app is allowed to (not from most background states since Android 12).
Kotlin
// read-only example: goAsync for a short job
class NotesChangedReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val pending = goAsync()
        val appContext = context.applicationContext
        CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
            try {
                NotesDatabase.get(appContext).dao().markSynced()
            } finally {
                pending.finish()               // always release the broadcast
            }
        }
    }
}

// read-only example: hand longer work to WorkManager
override fun onReceive(context: Context, intent: Intent) {
    val request = OneTimeWorkRequestBuilder<SyncWorker>().build()
    WorkManager.getInstance(context).enqueue(request)
}

Ordered broadcasts, sticky broadcasts and results

A normal broadcast (sendBroadcast) goes to all receivers in an undefined order, at the same time. An ordered broadcast (sendOrderedBroadcast) delivers to one receiver at a time, from the highest android:priority (in the intent filter, -1000 to 1000) to the lowest. Each receiver can read and modify a result (code, data, extras) for the next one, or abort the broadcast so lower-priority receivers never see it. Ordered broadcasts are rare today, but they explain old behavior, such as an SMS app intercepting an incoming message.

A sticky broadcast remembers its last value for later subscribers; sending sticky broadcasts is deprecated and not allowed for apps, but the system still has a few, and the famous example is battery status: registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) returns the last battery intent immediately, without a receiver.

Kotlin Ordered broadcast with priority, result and abort (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

LocalBroadcastManager and what replaced it

For years apps used LocalBroadcastManager to send events inside one app (an upload finished, tell the screen). It is deprecated, because it is a global bus with untyped intents and no lifecycle awareness. Inside your app you do not need Android's broadcast system at all. Expose a SharedFlow (for events) or StateFlow (for state) from a repository or a singleton, and collect it in the UI with the lifecycle-aware collectors from Flow Collection and StateFlow in Compose. The compiler checks the types, and a collector stops when the screen goes away.

Use real broadcasts only for what Android defines: system events, and communication with other apps or with your own other processes.

The last TryIt is real coroutines code, close to what you write in an app: a SharedFlow as an in-app event bus with two subscribers, one that stops listening.

Kotlin SharedFlow as an in-app event bus (real coroutines)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Common mistakes

  • Declaring an implicit broadcast in the manifest (POWER_CONNECTED, SCREEN_ON) and wondering why it never fires. Register in code, or use WorkManager constraints.
  • Forgetting unregisterReceiver. The registration (and your activity) leaks.
  • Doing slow work in onReceive. It freezes the main thread and risks an ANR; the process may die when you return.
  • Missing RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED when registering on API 34 and above.
  • Leaving exported="true" on a private receiver. Any app can send it a broadcast.
  • Sending a broadcast with secrets in extras. An implicit broadcast can be read by any matching receiver; make it explicit with setPackage.
  • Using LocalBroadcastManager in new code instead of SharedFlow.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Your app targets Android 14 and needs ACTION_POWER_CONNECTED. What is the right way to receive it?

    That implicit broadcast is not allowed in the manifest since Android 8. Register dynamically, and state the export flag for apps targeting API 34 or higher.
  2. 2. What happens when onReceive() returns while you started a coroutine inside it?

    After onReceive returns the broadcast is finished. Use goAsync() and finish() for a short job, or WorkManager for real work.
  3. 3. What does goAsync() give you?

    You still only have seconds and must call finish() in a finally block. It is for short work, not long tasks.
  4. 4. What replaced LocalBroadcastManager for events inside one app?

    A typed Flow exposed from a repository gives compile-time checks and stops delivering when the collector's lifecycle ends.
  5. 5. In an ordered broadcast, a receiver with priority 100 calls abortBroadcast(). What happens to the receiver with priority 0?

    Ordered broadcasts go from the highest to the lowest priority, and an abort stops delivery to all remaining receivers.

Summary

  • A BroadcastReceiver reacts to a broadcast Intent in onReceive(), which runs on the main thread and must return quickly.
  • Register in the manifest (the system can start your process) or in code (while a component lives, paired with unregisterReceiver or DisposableEffect).
  • Since Android 8 most implicit broadcasts cannot be received through the manifest; a short allowlist such as BOOT_COMPLETED remains, everything else needs a context-registered receiver or WorkManager.
  • Set exported deliberately; on API 34 and higher pass RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED when registering in code, and send private broadcasts with setPackage.
  • Use goAsync() for short jobs and WorkManager for anything longer; never rely on a thread started inside onReceive.
  • Ordered broadcasts deliver by priority and can be aborted; sticky broadcasts are deprecated.
  • Inside your app use SharedFlow and StateFlow, not LocalBroadcastManager.
  • The Android code is read-only; the TryIts model delivery rules and ordered delivery, and the Flow bus is real coroutines code.

Next: Services, Notifications and Foreground Work