System broadcasts are the ones that are sent by the Android system when various system events happen. Every message we send and finally receive is wrapped in the Intent class containing information about that particular event. Each Intent must have a proper action set. For example--android.intent.action.ACTION_POWER_CONNECTED. Information about the event is represented with bundled extra data. For example, we may have bundled an extra string field representing particular data related to the event we are interested in. Let's consider an example of charging and battery information. Each time the battery status changes, interested parties will be notified and receive a broadcast message with information about the battery level:
val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED) val batteryStatus = registerReceiver(null, intentFilter) val status = batteryStatus.getIntExtra(BatteryManager.
EXTRA_STATUS, -1) val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL val chargePlug = batteryStatus.getIntExtra(BatteryManager.
EXTRA_PLUGGED, -1) val usbCharge = chargePlug == BatteryManager.
BATTERY_PLUGGED_USB
val acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC
In this example, we registered the intent filter for battery information. However, we did not pass an instance of broadcast receiver. Why? This is because that battery data is sticky. Sticky intents are intents that stay around for some time after the broadcast is performed. Registering to this data will immediately return the intent containing the latest data. We could also pass an instance of a broadcast receiver. Let's do it:
val receiver = object : BroadcastReceiver() { override fun onReceive(p0: Context?, batteryStatus: Intent?) { val status = batteryStatus?.getIntExtra
(BatteryManager.EXTRA_STATUS, -1) val isCharging = status ==
BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL val chargePlug = batteryStatus?.getIntExtra
(BatteryManager.EXTRA_PLUGGED, -1) val usbCharge = chargePlug ==
BatteryManager.BATTERY_PLUGGED_USB val acCharge = chargePlug ==
BatteryManager.BATTERY_PLUGGED_AC } } val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
registerReceiver(receiver, intentFilter)
Every time the battery information changes, the receiver will perform a code we defined in its implementation; we could also define our receiver in the Android Manifest:
<receiver android:name=".OurPowerReceiver"> <intent-filter> <action android:name="android.intent.action.
ACTION_POWER_CONNECTED"/> <action android:name="android.intent.action.
ACTION_POWER_DISCONNECTED"/> </intent-filter>
</receiver>