Context-registered Broadcast Receivers
Context-registered broadcast receivers (or runtime-registered broadcast receivers) are broadcast receivers that are programmatically registered to a Context
. The receiver will receive broadcasts as long as the Context
is valid.
Characteristics​
Compared to manifest-registered one, context-registered broadcast receiver has these characteristics:
- They are not constrained by implicit broadcast exceptions introduced in Android 8.0 (API level 26) like manifest-registered broadcast receivers.
- Android 13 introduces the ability to specify a flag to indicate whether the broadcast receiver is exported or not.
- If you are targeting Android 14 (API level 34), this flag becomes required for non-system broadcasts.
Basic Usage​
Let's say we have a simple BroadcastReceiver
subclass that listens to a custom intent action:
MyCustomBroadcastReceiver.kt
package com.hanmajid.androidnotebook
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
/**
* Simple broadcast receiver that listens to "com.hanmajid.androidnotebook.MY_CUSTOM_INTENT" intent action.
*/
class MyCustomBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val state = intent.getStringExtra("state")
Log.i("TAG", "State is: $state")
}
}
To register this broadcast receiver to a Context
you can use ContextCompat.registerReceiver()
method:
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.core.content.ContextCompat
// Initialize broadcast receiver within your context.
val broadcastReceiver = MyCustomBroadcastReceiver()
// Register broadcast receiver to [context].
ContextCompat.registerReceiver(
context,
broadcastReceiver,
IntentFilter("com.hanmajid.androidnotebook.MY_CUSTOM_INTENT"),
ContextCompat.RECEIVER_NOT_EXPORTED, // Required in Android 14+ for non-system broadcasts
)
You can test this broadcast receiver by sending the broadcast:
import android.content.Context
import android.content.Intent
context.sendBroadcast(
Intent().apply {
action = "com.hanmajid.androidnotebook.MY_CUSTOM_INTENT"
`package` = context.packageName
putExtra("state", "OK")
}
)
References​
- Context-registered receivers | Android Developers
- Implicit broadcast exceptions | Android Developers
- Runtime-registered broadcasts receivers must specify export behavior | Android Developers
- Safer exporting of context-registered receivers | Android Developers
ContextCompat.registerReceiver()
| Android Developers