Broadcast receivers
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_EXPORTEDorRECEIVER_NOT_EXPORTEDonregisterReceiver()calls; forgetting it throwsSecurityExceptionat 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" withfinish().
Two ways to register.
- Manifest-declared (
<receiver>inAndroidManifest.xml): the system can start your process to deliver the broadcast. From Android 12 (target 31) a receiver with an intent filter must setandroid:exportedexplicitly, or the app will not install. - Context-registered (
registerReceiver()): active only between register andunregisterReceiver(). 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.
| Aspect | Manifest-declared | Context-registered |
|---|---|---|
| Active | Always, system starts the process | Between register and unregister |
| Implicit broadcasts (target 26+) | Only the exemption list | Yes, while registered |
| Export setting | android:exported (required with a filter, target 31+) | RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED (target 34+) |
| Typical use | Boot, time zone, locale, alarms | Events 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 withgoAsync()(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 callpendingResult.finish()in afinallyblock.- A thread or coroutine started in
onReceive()withoutgoAsync()can be killed with the process onceonReceive()returns. - On target 26+, manifest receivers get only exempt or explicit broadcasts.
MY_PACKAGE_REPLACEDstill works because it is sent only to your app;PACKAGE_REPLACEDfor other apps does not. - On target 34+, a missing export flag on
registerReceiver()throwsSecurityException, unless every action is a system broadcast. UseRECEIVER_NOT_EXPORTEDfor broadcasts from your own app,RECEIVER_EXPORTEDfor broadcasts from other apps or system apps that are not the platform itself, such asDownloadManager.ACTION_DOWNLOAD_COMPLETE. - On target 31+, every manifest component with an
<intent-filter>needs an explicitandroid:exported, or installation fails. - Pair
registerReceiver()withunregisterReceiver()in the matching callbacks (onStart/onStoporonResume/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_COMPLETEDneedsRECEIVE_BOOT_COMPLETEDand arrives only after the user first unlocks the device; useLOCKED_BOOT_COMPLETEDwith direct boot for earlier work. On Android 15, a boot receiver cannot start several foreground service types, such asdataSync,mediaPlaybackandcamera.- Sticky broadcasts (
sendStickyBroadcast()) are deprecated since API 21. You can still read the last sticky system intent, for exampleregisterReceiver(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>PendingResultis the nested classBroadcastReceiver.PendingResult; there is noandroid.os.PendingResult.ContextCompat.registerReceiver()always takes a flag and applies it on Android 13+.ACTION_DOWNLOAD_COMPLETEcomes from another app's process, soRECEIVER_NOT_EXPORTEDwould silently block it.- Registering in
onStartand unregistering inonStopkeeps the receiver active only while the screen is visible, with no leak. goAsync()pluswithTimeoutkeeps the write inside the time limit, andfinish()infinallyalways 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
- A news app declared a manifest receiver for
android.net.conn.CONNECTIVITY_CHANGEto refresh the feed when the device came online. - After raising
targetSdk, the refresh stopped. Manifest receivers stopped gettingCONNECTIVITY_ACTIONon 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.
- They removed the receiver and enqueued a unique
OneTimeWorkRequestwithNetworkType.CONNECTEDwhen 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.
- A file app registered a receiver for its own
com.example.EXPORT_FINISHEDaction withcontext.registerReceiver(receiver, filter)and no flag. - After moving to
targetSdk34, every Android 14+ device crashed on that screen withSecurityException: ... RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED should be specified. - A second receiver for
ACTION_DOWNLOAD_COMPLETE, "fixed" withRECEIVER_NOT_EXPORTED, stopped receiving anything, because that broadcast comes from another process.
- They switched to
ContextCompat.registerReceiver()everywhere:RECEIVER_NOT_EXPORTEDfor the app's own action,RECEIVER_EXPORTEDforACTION_DOWNLOAD_COMPLETE. - They replaced the app-internal broadcast with a
SharedFlowin 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
registerReceivercalls without an export flag.
Common mistakes
- Omitting the export flag on registerReceiver. On target 34 this throws
SecurityExceptionfor non-system broadcasts. UseContextCompat.registerReceiver()withRECEIVER_NOT_EXPORTEDfor your own broadcasts andRECEIVER_EXPORTEDfor 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. UsegoAsync()and callfinish()infinally, 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.
LocalBroadcastManageris deprecated, and global broadcasts for internal events add security and export-flag work. Use aFloworSharedFlow.
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
-
Context-registered receiver. Add
DownloadWatcherfrom the example to a screen and attach it withlifecycle.addObserver(...). Start a download withDownloadManager.enqueue()and log the completed id. -
Break the flag. Change
RECEIVER_EXPORTEDtoRECEIVER_NOT_EXPORTED, run another download and confirm the completion is never logged. Change it back. -
Manifest receiver with goAsync. Add
LocaleChangedReceiverwith its manifest entry. InCachedContent.clear(), write a timestamp to DataStore and log it. -
Trigger it. Change the device language in Settings and check logcat for your log line, and that
finish()ran (add a log in thefinallyblock). -
Check the merged manifest. Open the Merged Manifest tab for the app module and confirm both receivers have an explicit
android:exported. -
Replace an internal broadcast. If your app sends a broadcast to itself, replace it with a
MutableSharedFlowin a repository and collect it withrepeatOnLifecycle(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.