<p>This article is about Android broadcasts, broadcastReceiver, and how to work with the broadcastReceiver with the help of a simple example.</p>



<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link has-white-color has-text-color has-background" href="https://github.com/arunk7839/BroadcastReceiverExp" style="background-color:#520599" target="_blank" rel="noreferrer noopener"><strong>DOWNLOAD CODE</strong></a></div>
</div>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<span class="embed-youtube" style="text-align:center; display: block;"><amp-youtube data-videoid="xf4fHmoK09w" data-param-rel="1" data-param-showsearch="0" data-param-showinfo="1" data-param-iv_load_policy="1" data-param-fs="1" data-param-hl="en-US" data-param-autohide="2" data-param-wmode="transparent" width="1200" height="675" layout="responsive"><a href="https://www.youtube.com/watch?v=xf4fHmoK09w" placeholder><amp-img src="https://i.ytimg.com/vi/xf4fHmoK09w/hqdefault.jpg" alt="YouTube Poster" layout="fill" object-fit="cover"><noscript><img src="https://i.ytimg.com/vi/xf4fHmoK09w/hqdefault.jpg" loading="lazy" decoding="async" alt="YouTube Poster"></noscript></amp-img></a></amp-youtube></span>
</div></figure>



<h3 class="p1 wp-block-heading"><span style="color: #000080;"><b>Broadcasts</b></span></h3>



<p class="p2">Broadcasts are messages that the Android system and Android apps send when an event of interest occurs. The broadcast message itself is wrapped in an <span style="color: #0000ff;"><strong>Intent</strong></span> ;object.</p>



<p class="p2">There are two types of broadcasts:</p>



<ul class="ul1 wp-block-list"><li class="li2"><span style="color: #0000ff;"><strong>System broadcasts</strong></span> ;are delivered by the system.</li><li class="li2"><strong><span style="color: #0000ff;">Custom broadcasts ;</span></strong>are delivered by your app.</li></ul>



<h4 class="p1 wp-block-heading"><span style="color: #000080;"><b>System broadcasts</b></span></h4>



<p class="p2">A ;<span style="color: #008000;"><strong>system broadcast</strong></span> is a message that the Android system sends when a system event occurs.</p>



<p>System broadcasts are sent to all apps that are subscribed to receive the event.</p>



<p class="p2"><strong>System broadcasts Example:</strong></p>



<ul class="ul1 wp-block-list"><li class="li2">When the device boots, the system broadcasts a system ;Intent ;with the action ;<span style="color: #0000ff;"><strong><a style="color: #0000ff;" href="https://developer.android.com/reference/android/content/Intent.html#ACTION_BOOT_COMPLETED"><span class="s1">ACTION_BOOT_COMPLETED</span></a></strong></span>.</li><li class="li2">When a wired headset is connected or disconnected, the system sends a system Intent with the <strong><span style="color: #008000;">action</span></strong> field <strong><span style="color: #0000ff;"><a style="color: #0000ff;" href="https://developer.android.com/reference/android/content/Intent#ACTION_HEADSET_PLUG"><span class="s1">android.intent.action.HEADSET_PLUG</span></a></span></strong> ;and also contains more data about the event in its <span style="color: #008000;"><strong>extra</strong></span> field, for example, a boolean extra indicating whether a headset is connected or disconnected.</li></ul>



<h4 class="p1 wp-block-heading"><span style="color: #000080;"><b>Custom broadcasts</b></span></h4>



<p class="p2"><strong>Custom broadcasts</strong> are broadcasts that your app sends out. To create a custom broadcast, define a custom ;Intent ;action.</p>



<p class="p2"><strong>For example</strong>, use a custom broadcast when you want to let other apps know that data has been downloaded to the device and is available for them to use.</p>



<h3 class="wp-block-heading"><span style="color: #000080;"><strong>BroadcastReceiver</strong></span></h3>



<p class="p1">Broadcast receivers are app components that listen for the events that have been broadcast from apps or from the Android system and respond accordingly.</p>



<p class="p1">For instance, if you are implementing a media app and you&#8217;re interested in knowing when the user connects or disconnects a headset, register for the ;<span style="color: #0000ff;"><strong>ACTION_HEADSET_PLUG</strong></span> ;intent action.</p>



<p>Follow the two steps to make BroadcastReceiver works for your application:</p>



<ul class="wp-block-list"><li class="p1"><span style="color: #0000ff;"><b>Creating the Broadcast Receiver</b></span></li><li class="p1"><span style="color: #0000ff;"><b>Registering a BroadcastReceiver / Receiving Broadcasts</b></span></li></ul>



<h4 class="wp-block-heading"><span style="color: #000080;"><b>Creating the Broadcast Receiver</b></span></h4>



<ul class="ol1 wp-block-list"><li class="li1">To create a broadcast receiver, define a subclass of the <span style="color: #0000ff;"><strong><a style="color: #0000ff;" href="https://developer.android.com/reference/android/content/BroadcastReceiver"><span class="s1">BroadcastReceiver</span></a></strong></span> ;class and implement the ;<span style="color: #008000;"><strong>onReceive()</strong></span> method. This subclass is where ;Intent ;objects are delivered if they match the intent filters you register for.</li></ul>



<pre class="wp-block-preformatted">class MyReceiver : BroadcastReceiver() {
 override fun onReceive(context: Context?, intent: Intent?) {
 <strong><span style="color: #008000;">// logic of the code needs to be written here</span></strong>
 }
}</pre>



<h4 class="wp-block-heading"><span style="color: #000080;"><b>Registering a BroadcastReceiver</b></span></h4>



<p class="p2">There are two types of broadcast receivers:</p>



<ul class="ul1 wp-block-list"><li class="li2"><strong><span style="color: #0000ff;">Static receivers</span></strong> or <strong><span style="color: #0000ff;">Manifest-declared receivers</span></strong>: register in the Android manifest file.</li><li class="li2"><span style="color: #0000ff;"><strong>Dynamic receivers</strong></span> or <strong><span style="color: #0000ff;">Context-registered receivers</span></strong>: register using a context.</li></ul>



<h5 class="wp-block-heading"><span style="color: #000080;"><b>Manifest-declared receivers</b></span></h5>



<p class="p1">To register a <strong><span style="color: #000000;">manifest-declared receiver</span></strong>, include the following attributes inside the <span style="color: #008000;"><strong><;receiver>;</strong></span> element in your <span style="color: #0000ff;"><strong>AndroidManifest.xml </strong></span>file:</p>



<pre class="wp-block-preformatted"><;receiver android:name=".MyReceiver" android:exported="true">;
 <;intent-filter>;
 <;action android:name="android.intent.action.BOOT_COMPLETED"/>;
 <;action android:name="android.intent.action.BATTERY_LOW" />;
 <;/intent-filter>;
<;/receiver>;</pre>



<ul class="ul1 wp-block-list"><li class="li1"><span style="color: #0000ff;"><strong><span class="s1"><span class="s2">android: name</span></span></strong></span>: name of the ;BroadcastReceiver ;subclass.</li><li class="li1"><strong><span style="color: #0000ff;"><span class="s1"><span class="s2">android: exported</span></span> ;(optional):</span></strong> If this boolean value is set to ;false, other apps cannot send broadcasts to your receiver.</li><li class="li1"><strong><span style="color: #0000ff;"><span class="s1"><span class="s2"><;intent-filter>;</span></span>:</span></strong><span class="Apple-converted-space"> ; </span>specify the broadcast ;Intent ;actions that your broadcast receiver component is listening for.</li></ul>



<p class="p1"><span style="color: #0000ff;"><b>Note:</b></span> For Android 8.0 (API level 26) and higher, static receivers can&#8217;t receive most implicit broadcasts (<i>Implicit ;</i>broadcasts are broadcasts that don&#8217;t target your app specifically). Even if you register for these broadcasts in the manifest, the Android system won&#8217;t deliver them to your app. However, you can still use a dynamic receiver to register for these broadcasts. To learn more, see the complete list of <strong><span style="color: #0000ff;"><a style="color: #0000ff;" href="https://developer.android.com/guide/components/broadcast-exceptions" target="_blank" rel="noopener">implicit broadcast exceptions</a></span></strong>.</p>



<h5 class="p1 wp-block-heading"><span style="color: #000080;"><b>Context-registered receivers</b></span></h5>



<p class="p1">To register a dynamic receiver use an application context or an Activity context. A dynamic receiver receives broadcasts as long as the registering context is valid.</p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>




<p class="p1">To register a ;<b>Context-registered receiver</b>, follow the below steps:</p>



<p class="p1">1. Create an instance of BroadcastReceiver.</p>



<pre class="wp-block-preformatted">val br: BroadcastReceiver = MyReceiver()</pre>



<p class="p1">2. Create an instance of IntentFilter and register the receiver by calling ;<b>registerReceiver(BroadCastReceiver, IntentFilter).</b></p>



<pre class="wp-block-preformatted">IntentFilter("com.c1ctech.broadcast.CUSTOM_INTENT").also {
 <span style="color: #008000;"><strong>// registering the receiver
 // it parameter which is passed in registerReceiver() function
 // is the intent filter that we have just created</strong></span>
 registerReceiver(br, it)
}</pre>



<p class="p1">Be sure to unregister the receiver when you no longer need it or the context is no longer valid using <a href="https://developer.android.com/reference/android/content/Context#unregisterReceiver(android.content.BroadcastReceiver)"><span style="color: #0000ff;"><strong>unregisterReceiver(BroadcastReceiver)</strong></span>.</a></p>



<h4 class="p1 wp-block-heading"><span style="color: #000080;"><b>Sending broadcasts</b></span></h4>



<p class="p2">Android provides three ways for apps to send broadcast:</p>



<h5 class="p1 wp-block-heading"><span style="color: #0000ff;"><strong>Ordered Broadcasts</strong></span></h5>



<ul class="ul1 wp-block-list"><li class="li1">sends broadcasts to one receiver at a time.</li><li class="li1">As each receiver executes in turn, it can propagate a result to the next receiver.</li><li class="li1">Receiver can abort the broadcast and hence no broadcast is received by other receivers.</li><li class="li1">The order of receivers is managed and controlled by the attribute ;<span style="color: #0000ff;"><b>android:priority</b></span> ;in corresponding intent-filter.</li><li class="li1">If receivers will have the same priority then they may run in any order.</li><li>These broadcasts are sent with <span style="color: #008000;"><strong><a style="color: #008000;" href="https://developer.android.com/reference/android/content/Context#sendOrderedBroadcast(android.content.Intent,%20java.lang.String)"><span class="s2">sendOrderedBroadcast(Intent, String)</span></a> ;</strong></span>method.</li></ul>



<h5 class="wp-block-heading" id="normal-broadcasts"><strong><span style="color: #0000ff;">Normal broadcasts</span></strong></h5>



<ul class="ul1 wp-block-list"><li class="li2">Sends broadcasts to all receivers in an undefined order.</li><li class="li2">This is more efficient.</li><li class="li1">Receivers cannot read results from other receivers.</li><li class="li1">They cannot propagate data received from the broadcast, or abort the broadcast.</li><li class="li1">These broadcasts are sent with <strong><span style="color: #008000;"><a style="font-size: 16px; background-color: #ffffff; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif; color: #008000;" href="https://developer.android.com/reference/android/content/Context#sendBroadcast(android.content.Intent)"><span class="s2">sendBroadcast(Intent) </span></a></span></strong>method.</li></ul>



<h5 class="p1 wp-block-heading"><strong><span style="color: #0000ff;">Local Broadcasts</span></strong></h5>



<ul class="ul1 wp-block-list"><li class="li2">sends broadcasts to receivers that are in the same app as the sender.</li><li class="li2">Use local broadcasts, if you don&#8217;t need to send broadcasts across apps.</li><li class="li2">The implementation is much more efficient (no interprocess communication needed).</li><li class="li2">No security issues related to other apps being able to receive or send your broadcasts.</li><li>These broadcasts are sent with <span style="color: #008000;"><strong><a style="color: #008000;" href="https://developer.android.com/reference/androidx/localbroadcastmanager/content/LocalBroadcastManager#sendBroadcast(android.content.Intent)"><span class="s2">LocalBroadcastManager.sendBroadcast</span></a> </strong></span>method.</li></ul>



<h3 class="wp-block-heading"><span style="color: #000080;"><strong>Creating new project</strong></span></h3>



<p>1 . Create a new project by going to <span style="color: #008000;"><b>File ;</b><span class="s1"><b>⇒</b></span></span><b><span style="color: #008000;"> ;New Android Project</span>,</b> ;select ;<span style="color: #008000;"><strong>Empty Activity</strong></span> ;, provide ;<span style="color: #008000;"><strong>app name</strong></span>, select language to ;<strong><span style="color: #008000;">kotlin</span> ;</strong>and then finally click on ;<span style="color: #008000;"><strong>finish</strong></span>.</p>



<p>2 . Open <span style="color: #008000;"><strong>activity_main.xml</strong> </span>layout file to include a button to broadcast the custom intent.</p>



<p><span style="color: #0000ff;"><strong>activity_main.xml</strong></span></p>



<pre class="wp-block-preformatted"><;?xml version="1.0" encoding="utf-8"?>;
<;androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity">;

 <;Button
 android:id="@+id/btn_send_broadcast"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Show Broadcast"
 android:textSize="20sp"
 android:textAllCaps="false"
 android:padding="15dp"
 android:background="@color/colorPrimary"
 android:textColor="@android:color/white"
 app:layout_constraintBottom_toBottomOf="parent"
 app:layout_constraintEnd_toEndOf="parent"
 app:layout_constraintStart_toStartOf="parent"
 app:layout_constraintTop_toTopOf="parent" />;

<;/androidx.constraintlayout.widget.ConstraintLayout>;</pre>



<p>3 . Create a new Kotlin class by simply Go to<b> ;<span style="color: #008000;">app >; java >; your package name(in which the MainActicity is present) >; right-click >; New >; Kotlin File/Class</span></b> and name the file as ;<span style="color: #008000;"><b>MyReceiver</b></span>.</p>



<p><span style="color: #0000ff;"><b>MyReceiver.kt</b></span></p>



<pre class="wp-block-preformatted"><span style="color: #008000;"><strong>// MyReceiver class extending BroadcastReceiver class</strong></span>
class MyReceiver : BroadcastReceiver() {

 <strong><span style="color: #008000;">//executed when sendBroadcast() is called on button click</span></strong>
 override fun onReceive(context: Context?, intent: Intent?) {

 val data = intent!!.extras!!.getString("data")

 Toast.makeText(context, " Broadcast Received with data " + data, Toast.LENGTH_LONG).show()
 }
}</pre>



<p>4 . In <span style="color: #008000;"><strong>MainActivity.kt</strong></span> file, we are receiving broadcast dynamically and sending broadcast at the click of a button.</p>



<p><span style="color: #0000ff;"><strong>MainActivity.kt</strong></span></p>



<pre class="wp-block-preformatted">package com.c1ctech.broadcastreceiverexp
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

 lateinit var br: MyReceiver

 override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 setContentView(R.layout.activity_main)

 <span style="color: #008000;"><strong> //creating BroadcastReceiver instance</strong></span>
 br = MyReceiver()

 IntentFilter("com.c1ctech.broadcast.CUSTOM_INTENT").also {
 <strong><span style="color: #008000;">// registering the receiver
 // it parameter which is passed in registerReceiver() function
 // is the intent filter that we have just created</span></strong>
 registerReceiver(br, it)
 }

 btn_send_broadcast.setOnClickListener {

 Intent().also { intent ->;
 intent.setAction("com.c1ctech.broadcast.CUSTOM_INTENT")
 intent.putExtra("data", "Hello World!")
 sendBroadcast(intent)
 }
 }
 }

 override fun onDestroy() {
 super.onDestroy()
 <span style="color: #008000;"><strong>// unregister the BroadcastReceiver</strong></span>
 unregisterReceiver(br)
 }
}</pre>



<p><strong>When you run the app it will look like this:</strong></p>



<div class="wp-block-image"><figure class="aligncenter is-resized"><img src="https://c1ctech.com/wp-content/uploads/2021/06/Screenshot_1624883700.png" alt="" class="wp-image-2619" width="309" height="549"/></figure></div>


