In this tutorial, you will get a complete understanding of the Android Broadcast Receiver. You will learn about system-generated intents with their working, classes of broadcasts and implementation of broadcast receivers in Android studio.
What is Android Broadcast Receiver?
A broadcast receiver is an Android component that allows an application to respond to messages (an Android Intent
) that are broadcast by the Android operating system or by an application. To deliver events to the app like sending a low battery message or screen turned off the message to the app. The apps can also initiate broadcasts to let other apps know that required data available in a device to use it.
Generally, we use Intents to deliver broadcast events to other apps and Broadcast Receivers use status bar notifications to let the user know that broadcast event occurs.
In android, Broadcast Receiver is implemented as a subclass of BroadcastReceiver and each broadcast is delivered as an Intent object.
Receiving Broadcasts
In android, we can receive broadcasts by registering in two ways.
One way is by registering broadcasts using an android application manifest file (AndroidManifest.xml). We need to specify <receiver> element in apps manifest file like as shown below.
<receiver android:name=".SampleBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
The above statement will fire the defined system broadcast event whenever the boot process is completed.
Another way is to register a receiver dynamically via Context.registerReceiver() method. To register broadcast receiver we need to extend our class using BroadcastReceiver and need to implement an onReceive(Context, Intent) method like as shown below.
public class MainActivity extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, log, Toast.LENGTH_LONG).show();
}
}
Suppose if we register for ACTION_BOOT_COMPLETED event, whenever the boot process is completed the broadcast receiver’s method onReceive() method will be invoked.
Sending Broadcasts
In android, we can send a broadcasts in apps using three different ways, those are
Method | Description |
---|---|
sendOrderedBroadcast(Intent, String) | This method is used to send broadcasts to one receiver at a time. |
sendBroadcast(Intent) | This method is used to send broadcasts to all receivers in an undefined order. |
LoadBroadcastManager.sendBroadcast | This method is used to send broadcasts to receivers that are in the same app as the sender. |
Broadcasting Custom Intents
In android, we can create our own custom broadcasts using intents. Following is the simple code snippet of sending a broadcast by creating an intent using sendBroadcast(Intent) method.
Intent sintent = new Intent();
intent.setAction("in.codingtimes.broadcast.MY_NOTIFICATION");
intent.putExtra("data","Welcome to Codingtimes");
sendBroadcast(intent);
If you observe above code snippet we create a custom Intent “sintent”. We need to register our intent action in android manifest file like as shown below
<receiver android:name=".SampleBroadcastReceiver">
<intent-filter>
<action android:name="in.codingtimes.broadcast.MY_NOTIFICATION"/>
</intent-filter>
</receiver>
This is how we can create our own custom brDescriptionDescriptionoadcasts using Intents in android applications.
System Broadcasts
In android, several system events are defined as final static fields in the Intent class. The following are some of the system events available in android applications.
Event | Description |
---|---|
android.intent.action.BOOT_COMPLETED | It raises an event, once boot completed. |
android.intent.action.POWER_CONNECTED | It is used to trigger an event when power connected to the device. |
android.intent.action.POWER_DISCONNECTED | It is used to trigger an event when the power got disconnected from the device. |
android.intent.action.BATTERY_LOW | It is used to call an event when battery is low on device. |
android.intent.action.BATTERY_OKAY | It is used to call an event when a battery is OKAY again. |
android.intent.action.REBOOT | It call an event when the device rebooted again. |
Likewise, we have many system events available in the android application.
Android BroadcastReceiver Example
To setup a Broadcast Receiver in our android application we need to do the following things.
- Create a BroadcastReceiver
- Register a BroadcastReceiver
Create a new android application using android studio and give names as BroadcastReceiver.
Now we need to create our own broadcast content file MyBroadcastReceiver.java in \src\main\java\in.codingtimes.broadcastreceiver path to define our actual provider and associated methods for that right-click on your application folder à Go to New à select Java Class and give name as MyBroadcastReceiver.java.
Once we create a new file MyBroadcastReceiver.java, open it and write the code like as shown below
MyBroadcastReceiver.java
package in.codingtimes.broadcastreceiver_android;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class BroadcastReceived extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Broadcast Received", Toast.LENGTH_SHORT).show();
}
}
Now open activity_main.xml file from \src\main\res\layout path and write the following code.
activity_main.xml
<?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/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Broadcast"
android:backgroundTint="@color/purple_200"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Now open MainActivity.java file from \java\in.codingtimes.broadcastreceiver path and write following to implement custom broadcast intents.
MainActivity.java
package in.codingtimes.broadcastreceiver_android;
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
BroadcastReceiver br = new BroadcastReceived();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction("mybroadcast");
sendBroadcast(intent);
Toast.makeText(MainActivity.this, "Broadcast Sent", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter("mybroadcast");
registerReceiver(br,intentFilter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(br);
}
}
Now we need to register our broadcast receiver in android manifest file (AndroidManifest.xml) using <receiver> attribute like as shown below.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.codingtimes.broadcastreceiver_android">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.BroadcastReceiver_Android">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".BroadcastReceived"
android:exported="true">
<intent-filter>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
</application>
</manifest>
That’s it!
You have successfully completed the post. Do Share : )
Peace Out!
Source Code – https://github.com/Adityaraj-30/BroadcastReceiver_Android.git
Also Read – Android Fragment Life Cycle
Check Out Deals on -> Amazon , Flipkart , Myntra , Adidas , Apple TV , Boat , Canva , Beardo , Coursera , Cleartrip , Fiverr , MamaEarth , Swiggy, KFC
[…] Also Read – Android Broadcast Receiver […]