Flutter Course (21 Blogs) Become a Certified Professional

Android Broadcast Receiver: Tutorials for Beginners- 5

Last updated on Mar 15,2023 60K Views


This is the fifth in our Android Tutorials for beginners series, and discusses another very important component of Android system: Android Broadcast Receiver. We hope you have gone through the previous Android tutorials in this series! If not, here they are: Activity, Intent, Services, Content ProviderFor a grassroot level clarity on the basic concepts of Android, you can pursue this Android development course and understand each & every nuance of the technology.

An example of Android Broadcast Receiver along with sample code has been given at the end of this Android Tutorial. Download the code here!

What is Android Broadcast Receiver?

A broadcast receiver is a dormant component of the Android system. Only an Intent (for which it is registered) can bring it into action. The Broadcast Receiver’s job is to pass a notification to the user, in case a specific event occurs.

Using a Broadcast Receiver, applications can register for a particular event. Once the event occurs, the system will notify all the registered applications. Want to learn how to build mobile apps using Flutter? Enroll in a Flutter Certification and start your journey today.

Android-Tutorial-android-broadcast-receiver

For instance, a Broadcast receiver triggers battery Low notification that you see on your mobile screen.

Other instances caused by a Broadcast Receiver are new friend notifications, new friend feeds, new message etc. on your Facebook app.

In fact, you see broadcast receivers at work all the time. Notifications like incoming messages, WiFi Activated/Deactivated message etc. are all real-time announcements of what is happening in the Android system and the applications.

notification-android-broadcast-receiver

Consider this:

You have an important social gathering to attend. Because of your shoddy memory, you have requested your friend to notify you a day before the event. Now, because you have ‘registered’ for the said friend’s help, you will get a reminder from him as discussed. This is roughly how the Broadcast Receiver works.

We have also discussed an example at the end of this Android Tutorial (in the example, a notification is generated once the system time is changed).

How important is it to implement Broadcast Receivers correctly?

If you wish to create a good Android application, this is of utmost importance. If the broadcast events do not perform their job (of sending notifications to support the application’s primary task) perfectly, the application would not be intuitive and user friendly.

Registration of Broadcast Receiver

There are two ways to register a Broadcast Receiver; one is Static and the other Dynamic.

1)      Static: Use <receiver> tag in your Manifest file. (AndroidManifest.xml)

2)      Dynamic: Use Context.registerReceiver () method to dynamically register an instance.

Classes of Broadcasts

The two major classes of broadcasts are:

1)  Ordered Broadcasts: These broadcasts are synchronous, and therefore follow a specific order. The order is defined using android: priority attribute. The receivers with greater priority would receive the broadcast first. In case there are receivers with same priority levels, the broadcast would not follow an order. Each receiver (when it receives the broadcast) can either pass on the notification to the next one, or abort the broadcast completely. On abort, the notification would not be passed on to the receivers next in line.

2)  Normal Broadcasts: Normal broadcasts are not orderly. Therefore, the registered receivers often run all at the same time. This is very efficient, but the Receivers are unable to utilize the results.

Sometimes to avoid system overload, the system delivers the broadcasts one at a time, even in case of normal broadcasts. However, the receivers still cannot use the results.

Difference between Activity Intent and Broadcasting Intent

You must remember that Broadcasting Intents are different from the Intents used to start an Activity or a Service (discussed in previous Android Tutorials). The intent used to start an Activity makes changes to an operation the user is interacting with, so the user is aware of the process. However, in case of broadcasting intent, the operation runs completely in the background, and is therefore invisible to the user.

Implementing the Broadcast Receiver

You need to follow these steps to implement a broadcast receiver:

1)      Create a subclass of Android’s BroadcastReceiver

2)      Implement the onReceive() method: In order for the notification to be sent, an onReceive() method has to be implemented. Whenever the event for which the receiver is registered occurs, onReceive() is called. For instance, in case of battery low notification, the receiver is registered to Intent.ACTION_BATTERY_LOW event. As soon as the battery level falls below the defined level, this onReceive() method is called.

Following are the two arguments of the onReceive() method:

  • Context: This is used to access additional information, or to start services or activities.
  • Intent: The Intent object is used to register the receiver.

Security

As the broadcast receivers have a global work-space, security is very important concern here. If you do not define the limitations and filters for the registered receivers, other applications can abuse them.
Here are a few limitations that might help:

  • Whenever you publish a receiver in your application’s manifest, make it unavailable to external applications by using android: exported=”false”. You might think that specifying Intent filters while publishing the receiver would do the task for you, when in reality they are not enough.
  • When you send a broadcast, it is possible for the external applications too to receive them. This can be prevented by specifying a few limitations.
  • Similarly, when you register your receiver using registerReceiver, any application may send it broadcasts. This can be prevented using permissions as well.

(PS: As of Android 3.1, the Android system will not receive any external Intent, so the system is comparatively secure now.)

Prolonged Operations

The Broadcast Receiver object is active only for the duration of onReceive (Context, Intent).
Therefore, if you need to allow an action after receiving the notification services should be triggered, and not broadcast receivers.

  • To show a dialogue, then you should use NotificationManager API
  • If you wish to send a broadcast intent that would stick around even after the broadcast is complete, you must use sendStickyBroadcast (Intent) method.

Broadcast Receiver Example

In this sample application, a notification is generated when you change the system time. The notification when clicked leads the user to the Contacts. This is how the application works:

example-screenshot-android-broadcast-receiver

Sample code

Here’s the sample code for this Broadcast Receiver:

public class MyBroadcastReceiver extends BroadcastReceiver {

	private NotificationManager mNotificationManager;
	private int SIMPLE_NOTFICATION_ID;

	@Override
	public void onReceive(Context context, Intent intent) {

		mNotificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);

		Notification notifyDetails = new Notification(R.drawable.android,
				"Time Reset!", System.currentTimeMillis());

		PendingIntent myIntent = PendingIntent.getActivity(context, 0,
				new Intent(Intent.ACTION_VIEW, People.CONTENT_URI), 0);

		notifyDetails.setLatestEventInfo(context, "Time has been Reset",
				"Click on me to view Contacts", myIntent);

		notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
		notifyDetails.flags |= Notification.DEFAULT_SOUND;

		mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
		Log.i("hisham_debug", "Sucessfully Changed Time");

	}

Do you have any doubts in this Android tutorial? Ask Us!

We hope you enjoyed learning about the Android building blocks in these basic Android tutorials. The forthcoming Android tutorials would deal with topics more advanced than this! Stay Tuned for that!

Happy Learning!

Following resources were used in creating this Android Tutorial: developer.android.com, Edureka.co 

You may also like these related posts:

Comments
35 Comments
  • this was a great tutorial. I have one confusion regarding the usage of broadcast reciever, i’m trying to access the service from multiple activities(of different applications) by two ways:

    Starting the broadcast from activities and broadcasting the value from activities, and through broadcast, calling the service.
    Directly calling the service and passing the value from the activities.
    But I am not understanding the difference between the two methodology.The only difference I understood is that any application installed on my android phone can broadcast and start the service by calling and passing the value to the broadcast receiver.

    Is this is the only difference between the two methodologies. If any other please specify. Thanks in Advance.

  • I am commonly to blogging and i genuinely appreciate your content. The article has really peaks my interest. I am going to bookmark your internet site and keep checking for new details.

  • I’m impressed, I should say. Definitely rarely do I encounter a weblog that is both educative and entertaining, and let me tell you, you’ve got hit the nail on the head. Your thought is outstanding; the problem is some thing that not sufficient persons are speaking intelligently about. I am quite pleased that I stumbled across this in my search for something relating to this.
    Nice post. I discover something more difficult on diverse blogs everyday. It’s going to normally be stimulating to read content from other writers and practice just a little something from their store. I’d prefer to use some using the content on my blog whether or not you do not mind. Natually I’ll provide you with a link on your web weblog. Thanks for sharing.

  • Aw, this was a seriously nice post. In idea I would like to put in writing like this in addition – taking time and actual effort to create a pretty decent article?- but what can I say?- I procrastinate alot and by no indicates appear to get something carried out.

  • An fascinating discussion is worth comment. I feel that you will need to write far more on this topic, it could not be a taboo subject but frequently many people are not enough to speak on such topics. To the next. Cheers

  • I discovered your weblog web-site on google and check a number of of your early posts. Continue to keep up the very superior operate. I just additional up your RSS feed to my MSN News Reader. Searching for forward to reading far more from you later on!

  • I will be newcomer in this element, I’m hoping every body will help me to obtain more details inside below

  • Thank you for all your hard work on this website. Betty loves carrying out investigations and it’s really easy to understand why. Many of us notice all relating to the lively means you produce precious tactics on your website and in addition attract participation from some other people about this subject then our daughter is always studying a great deal. Take pleasure in the remaining portion of the year. You are doing a wonderful job.

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Android Broadcast Receiver: Tutorials for Beginners- 5

edureka.co