Broadcasts

sending broadcasts

You can send a custom broadcast, for example, to notify that an event has occurred.

You can send broadcast to all system from you context. Or you can send message only within your app via LocalBroadcastManager, which is much more efficient.

The broadcast message is wrapped in an Intent object. The intent action is used as message type. You can pass some data with message.

val intent = Intent("com.example.YOUR_ACTION") 
intent.putExtra("key", "value") // data to be passed with your broadcast

context.sendBroadcast(intent)
val intent = Intent("com.example.YOUR_ACTION") intent.putExtra("key", "value") // data to be passed with your broadcast val manager = LocalBroadcastManager.getInstance(context) manager.sendBroadcast(intent)

BroadcastReceiver

The BroadcastReceiver allows you to handle broadcast.

class MyBroadcastReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        // ...
    }
}

The onReceive is called in main thread and must be complete within 16ms. If you need some long time operation, than execute it in background.

BroadcastReceiver with background task

To receive messages you must register your BroadcastReceiver in Manifest.xml file or programmatically.

From API 26+, you cannot use the manifest to declare a receiver for implicit broadcasts (broadcasts that do not target your app specifically), except for a few implicit broadcasts. In most cases, you can use scheduled jobs instead.

<receiver android:name=".MyBroadcastReceiver"  android:exported="true">
    <intent-filter>
        <action android:name="com.example.YOUR_ACTION"/>
    </intent-filter>
</receiver>
val br: BroadcastReceiver = MyBroadcastReceiver()

val filter = IntentFilter(BR_MY_ACTION).apply {
    // add other actions if necessary
    // addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED)
}

context.registerReceiver(br, filter)

// to register for local broadcasts, call 
LocalBroadcastManager.registerReceiver(br, filter)

To stop receiving broadcasts, call

context.unregisterReceiver(myBroadcastReceiver)

best practices

There are three ways to control who can receive your broadcasts:

  • you can specify a permission when sending a broadcast
  • you can specify a package with setPackage() when sending a broadcast. The system restricts the broadcast to the set of apps that match the package.
  • send local broadcasts with LocalBroadcastManager

The namespace for broadcast actions is global. Make sure that action names and other strings are written in a namespace you own, or else you may inadvertently conflict with other apps.

Do not start activities from broadcast receivers because the user experience is jarring; especially if there is more than one receiver. Instead, consider displaying a notification.