Broadcast receivers

Learn Android Broadcast Receivers to master manifest and context registration, handle Android 8 and 14 restrictions, and manage onReceive threading. About 25 minutes.

Why it matters

  • Boot, time zone, locale and package events still arrive as broadcasts, and alarms deliver through receivers. Missing the Android 8 implicit-broadcast limit gives a receiver that silently never runs.
  • Android 14 (target 34) requires RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED on registerReceiver() calls; forgetting it throws SecurityException at the call.
  • onReceive() runs on the main thread, and the process can be killed soon after it returns. Slow work there causes ANRs; background work started there can be lost.
  • Interviewers pair this topic with WorkManager and foreground services to see whether you know what a receiver should and should not do.

The simple explanation

  • A broadcast is an announcement over the building's speakers; a receiver is someone listening for one kind of announcement.
  • A manifest receiver is a name on the building's list: the system wakes you up for the announcement even if you were asleep (process not running), but since Android 8 only for a short list of announcements.
  • A context-registered receiver is someone in the room with a radio on: they hear everything while they are there, and nothing after they leave.
  • An ordered broadcast is a relay: listeners hear it one at a time by priority, can pass a note to the next one, and can stop the relay with abortBroadcast().
  • goAsync() is asking the announcer to wait a few more seconds while you write something down; you say "done" with finish().

Two ways to register.

  • Manifest-declared (<receiver> in AndroidManifest.xml): the system can start your process to deliver the broadcast. From Android 12 (target 31) a receiver with an intent filter must set android:exported explicitly, or the app will not install.
  • Context-registered (registerReceiver()): active only between register and unregisterReceiver(). It can receive implicit broadcasts, but only while your code is running.

Implicit broadcast limits (target 26, Android 8). A manifest receiver no longer gets most implicit broadcasts (ones not addressed to a specific app). Still delivered: explicit broadcasts (with setPackage() or a component), broadcasts sent only to your app such as MY_PACKAGE_REPLACED, and an exemption list including BOOT_COMPLETED, LOCKED_BOOT_COMPLETED, TIMEZONE_CHANGED, TIME_SET and LOCALE_CHANGED. CONNECTIVITY_ACTION stopped reaching manifest receivers earlier, on target 24, and is deprecated; use ConnectivityManager.NetworkCallback.

Export flags (target 34, Android 14). registerReceiver() must pass Context.RECEIVER_EXPORTED or Context.RECEIVER_NOT_EXPORTED unless the receiver only listens for system broadcasts; otherwise it throws SecurityException. Use ContextCompat.registerReceiver(), which takes the flag on every version. Manifest receivers use android:exported instead.

Threading and lifetime. onReceive() runs on the main thread. A foreground broadcast that is not finished in about 10 seconds causes an ANR (background broadcasts get longer). After onReceive() returns, the receiver is no longer an active component, so the system may kill the process and any thread you started. goAsync() returns a BroadcastReceiver.PendingResult that keeps the broadcast active until you call finish(), still within the same time limit. For longer work, enqueue WorkManager work.

AspectManifest-declaredContext-registered
ActiveAlways, system starts the processBetween register and unregister
Implicit broadcasts (target 26+)Only the exemption listYes, while registered
Export settingandroid:exported (required with a filter, target 31+)RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED (target 34+)
Typical useBoot, time zone, locale, alarmsEvents that matter only while the app runs

Inside your app, LocalBroadcastManager is deprecated. Use a Flow, SharedFlow or another observable in your own code instead of broadcasts.

Notes

  • onReceive() runs on the main thread. Keep it short: read the intent, then hand work to a coroutine with goAsync() (seconds) or to WorkManager (anything longer or retryable).
  • goAsync() does not extend the deadline: the whole broadcast should still finish in about 10 seconds. Always call pendingResult.finish() in a finally block.
  • A thread or coroutine started in onReceive() without goAsync() can be killed with the process once onReceive() returns.
  • On target 26+, manifest receivers get only exempt or explicit broadcasts. MY_PACKAGE_REPLACED still works because it is sent only to your app; PACKAGE_REPLACED for other apps does not.
  • On target 34+, a missing export flag on registerReceiver() throws SecurityException, unless every action is a system broadcast. Use RECEIVER_NOT_EXPORTED for broadcasts from your own app, RECEIVER_EXPORTED for broadcasts from other apps or system apps that are not the platform itself, such as DownloadManager.ACTION_DOWNLOAD_COMPLETE.
  • On target 31+, every manifest component with an <intent-filter> needs an explicit android:exported, or installation fails.
  • Pair registerReceiver() with unregisterReceiver() in the matching callbacks (onStart/onStop or onResume/onPause). A forgotten unregister leaks the receiver and the Activity it references, and the system logs a "leaked IntentReceiver" error.
  • On Android 14, broadcasts to context-registered receivers of a cached app may be queued until the app leaves the cached state, and repeated ones may be merged. Do not expect real-time delivery in the background.
  • BOOT_COMPLETED needs RECEIVE_BOOT_COMPLETED and arrives only after the user first unlocks the device; use LOCKED_BOOT_COMPLETED with direct boot for earlier work. On Android 15, a boot receiver cannot start several foreground service types, such as dataSync, mediaPlayback and camera.
  • Sticky broadcasts (sendStickyBroadcast()) are deprecated since API 21. You can still read the last sticky system intent, for example registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) returns the current battery state.

Code example

A context-registered receiver for download completion, tied to the lifecycle and registered with the right export flag, and a manifest receiver that uses goAsync() for a short DataStore write.

// DownloadWatcher.kt
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.core.content.ContextCompat
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
 
// Listens only while the screen is started: lifecycle.addObserver(DownloadWatcher(this) { id -> ... })
class DownloadWatcher(
    private val context: Context,
    private val onComplete: (Long) -> Unit,
) : DefaultLifecycleObserver {
 
    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L)
            if (id != -1L) onComplete(id) // main thread: just update state
        }
    }
 
    override fun onStart(owner: LifecycleOwner) {
        ContextCompat.registerReceiver(
            context,
            receiver,
            IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE),
            // Sent by the download provider, not the platform, so it must be EXPORTED
            ContextCompat.RECEIVER_EXPORTED,
        )
    }
 
    override fun onStop(owner: LifecycleOwner) {
        context.unregisterReceiver(receiver)
    }
}
 
// LocaleChangedReceiver.kt
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
 
object CachedContent {
    suspend fun clear(context: Context) {
        // delete cached, locale-specific text from DataStore
    }
}
 
class LocaleChangedReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action != Intent.ACTION_LOCALE_CHANGED) return
        val pendingResult: BroadcastReceiver.PendingResult = goAsync()
        val appContext = context.applicationContext
        CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
            try {
                withTimeout(9_000) { // the whole broadcast must finish in about 10 s
                    CachedContent.clear(appContext)
                }
            } finally {
                pendingResult.finish() // always, even on timeout or error
            }
        }
    }
}
<!-- AndroidManifest.xml: LOCALE_CHANGED is on the implicit-broadcast exemption list -->
<receiver
    android:name=".LocaleChangedReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.LOCALE_CHANGED" />
    </intent-filter>
</receiver>
  • PendingResult is the nested class BroadcastReceiver.PendingResult; there is no android.os.PendingResult.
  • ContextCompat.registerReceiver() always takes a flag and applies it on Android 13+. ACTION_DOWNLOAD_COMPLETE comes from another app's process, so RECEIVER_NOT_EXPORTED would silently block it.
  • Registering in onStart and unregistering in onStop keeps the receiver active only while the screen is visible, with no leak.
  • goAsync() plus withTimeout keeps the write inside the time limit, and finish() in finally always releases the broadcast. A network call or a large migration would go to WorkManager instead.

Run the idea in plain Kotlin

A model of two rules: whether registerReceiver() throws on target 34, and how an ordered broadcast moves through receivers by priority, passing result data until one calls abortBroadcast().

enum class ExportFlag { EXPORTED, NOT_EXPORTED }

val systemOnlyActions = setOf("android.intent.action.BATTERY_CHANGED", "android.intent.action.SCREEN_OFF")

fun registerReceiver(targetSdk: Int, actions: Set<String>, flag: ExportFlag?): String {
  val onlySystem = systemOnlyActions.containsAll(actions)
  if (targetSdk >= 34 && flag == null && !onlySystem) {
      return "SecurityException: RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED required"
  }
  return "registered" + if (flag != null) " (" + flag + ")" else ""
}

class OrderedResult(var data: String) {
  var aborted = false
  fun abortBroadcast() { aborted = true }
}

class Receiver(val name: String, val priority: Int, val handle: (OrderedResult) -> Unit)

fun sendOrderedBroadcast(receivers: List<Receiver>, initialData: String): String {
  val result = OrderedResult(initialData)
  for (r in receivers.sortedByDescending { it.priority }) {
      if (result.aborted) {
          println("  " + r.name + ": not called, broadcast aborted")
          continue
      }
      println("  " + r.name + " (priority " + r.priority + ") gets data=" + result.data)
      r.handle(result)
  }
  return result.data
}

fun main() {
  println("registerReceiver:")
  println("  custom action, target 33, no flag: " + registerReceiver(33, setOf("com.example.SYNC_DONE"), null))
  println("  custom action, target 34, no flag: " + registerReceiver(34, setOf("com.example.SYNC_DONE"), null))
  println("  custom action, target 34, flag:    " + registerReceiver(34, setOf("com.example.SYNC_DONE"), ExportFlag.NOT_EXPORTED))
  println("  system only, target 34, no flag:   " + registerReceiver(34, setOf("android.intent.action.BATTERY_CHANGED"), null))

  println("ordered broadcast:")
  val receivers = listOf(
      Receiver("Logger", 0) { },
      Receiver("Filter", 100) { it.data = it.data + "+checked" },
      Receiver("Blocker", 50) { it.data = it.data + "+blocked"; it.abortBroadcast() }
  )
  val finalData = sendOrderedBroadcast(receivers, "sms")
  println("final result data: " + finalData)
}

Expected output:

registerReceiver:
  custom action, target 33, no flag: registered
  custom action, target 34, no flag: SecurityException: RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED required
  custom action, target 34, flag:    registered (NOT_EXPORTED)
  system only, target 34, no flag:   registered
ordered broadcast:
  Filter (priority 100) gets data=sms
  Blocker (priority 50) gets data=sms+checked
  Logger: not called, broadcast aborted
final result data: sms+checked+blocked

In production

Connectivity receiver went silent
  • A news app declared a manifest receiver for android.net.conn.CONNECTIVITY_CHANGE to refresh the feed when the device came online.
  • After raising targetSdk, the refresh stopped. Manifest receivers stopped getting CONNECTIVITY_ACTION on target 24, and most implicit broadcasts on target 26. There was no crash and no log from the app.
  • Users saw a stale feed until they pulled to refresh.
The fix
  • They removed the receiver and enqueued a unique OneTimeWorkRequest with NetworkType.CONNECTED when a refresh failed offline, so WorkManager runs it when the network returns, even if the app is closed.
  • For the screen that shows an "offline" banner, they used ConnectivityManager.registerDefaultNetworkCallback() while the screen is visible.
  • They checked the merged manifest (Android Studio's Merged Manifest tab) for other receivers whose actions are no longer delivered.
Crash after raising targetSdk to 34
  • A file app registered a receiver for its own com.example.EXPORT_FINISHED action with context.registerReceiver(receiver, filter) and no flag.
  • After moving to targetSdk 34, every Android 14+ device crashed on that screen with SecurityException: ... RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED should be specified.
  • A second receiver for ACTION_DOWNLOAD_COMPLETE, "fixed" with RECEIVER_NOT_EXPORTED, stopped receiving anything, because that broadcast comes from another process.
The fix
  • They switched to ContextCompat.registerReceiver() everywhere: RECEIVER_NOT_EXPORTED for the app's own action, RECEIVER_EXPORTED for ACTION_DOWNLOAD_COMPLETE.
  • They replaced the app-internal broadcast with a SharedFlow in the export repository, removing a receiver that never needed to be a broadcast.
  • They tested each receiver on an API 34 emulator and added a lint check run in CI, since lint flags registerReceiver calls without an export flag.

Common mistakes

  • Omitting the export flag on registerReceiver. On target 34 this throws SecurityException for non-system broadcasts. Use ContextCompat.registerReceiver() with RECEIVER_NOT_EXPORTED for your own broadcasts and RECEIVER_EXPORTED for broadcasts from other apps.
  • Doing slow work in onReceive. It runs on the main thread, and a foreground broadcast that takes about 10 seconds causes an ANR. Use goAsync() for a few seconds of work or enqueue WorkManager work.
  • Starting a thread without goAsync. Once onReceive() returns, the process may be killed with your thread. Use goAsync() and call finish() in finally, or hand the work to WorkManager.
  • Relying on implicit broadcasts in the manifest. On target 26+, most never arrive. Check the exemption list, register in code while the app runs, or use the dedicated API (NetworkCallback, WorkManager constraints).
  • Forgetting unregisterReceiver. The receiver and the Activity it references leak. Pair register and unregister in matching lifecycle callbacks.
  • Using broadcasts inside one app. LocalBroadcastManager is deprecated, and global broadcasts for internal events add security and export-flag work. Use a Flow or SharedFlow.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between a manifest-declared and a context-registered receiver?”

“How do you do work in response to a broadcast without causing ANRs?”

“Why did implicit broadcasts stop reaching manifest receivers, and what do you use instead?”

“What changed for receivers in Android 14, and how do you choose the export flag?”

Quiz

An app targeting SDK 34 calls context.registerReceiver(receiver, IntentFilter("com.example.SYNC_DONE")) without flags. What happens?

What does goAsync() return, and what must you do with it?

An app targeting SDK 26+ declares a manifest receiver for each of these actions. Which one is NOT delivered?

A receiver registered in an Activity's onCreate is never unregistered. What is the consequence?

0 of 4 answered

Mini task

15-minute exercise: a receiver with the right flags and goAsync

  1. Context-registered receiver. Add DownloadWatcher from the example to a screen and attach it with lifecycle.addObserver(...). Start a download with DownloadManager.enqueue() and log the completed id.

  2. Break the flag. Change RECEIVER_EXPORTED to RECEIVER_NOT_EXPORTED, run another download and confirm the completion is never logged. Change it back.

  3. Manifest receiver with goAsync. Add LocaleChangedReceiver with its manifest entry. In CachedContent.clear(), write a timestamp to DataStore and log it.

  4. Trigger it. Change the device language in Settings and check logcat for your log line, and that finish() ran (add a log in the finally block).

  5. Check the merged manifest. Open the Merged Manifest tab for the app module and confirm both receivers have an explicit android:exported.

  6. Replace an internal broadcast. If your app sends a broadcast to itself, replace it with a MutableSharedFlow in a repository and collect it with repeatOnLifecycle(Lifecycle.State.STARTED).

Done when: download completion is logged only with the exported flag, the locale receiver logs once per language change with finish() called, and both receivers show an explicit exported value.

Next: Unit tests with JUnit and MockK