Android BroadcastReceiver Tutorial

Android BroadcastReceiver is a android component that respond to broadcast announcement from other applications or system itself. It allow you register a broadcast receiver for particular system or event. For example, the battery life is getting lower it can be received and let the application perform some action. It such a good indicator for the android application.

In this example, you will know how to use broadcast receiver in android studio. You just need follow my steps.

Create a New Project

1. Open Android Studio IDE in your computer.
2. Create a new project and Edit the Application name to “BcReceiverExample”.
(Optional) You can edit the company domain or select the suitable location for current project tutorial. Then click next button to proceed.
3. Select Minimum SDK (API 15:Android 4.0.3 (IceCreamSandwich). I choose the API 15 because many android devices currently are support more than API 15. Click Next button.
4. Choose “Empty Project” and Click Next button
5. Lastly, press finish button.

Add a New Broadcast Receiver

Create a new broadcast receiver file by right click your package name > new > other > BroadcastReceiver. Name it as “MyReceiver”.

android broadcastreceiver pic 1

After create the broadcast receiver, the android manifest file will automatically include the receiver.

Edit MyReceiver.java class

In your MyReceiver.java, add the toast message in the onReceive method when receiving the broadcast. You should extends BroadcastReceiver in this class to use BroadcastReceiver method.

void onReceive(Context,Intent)

– This method will call when the BroadcastReceiver receive an Intent broadcast. You can also use the method on BroadcastReceiver to view and modify the result.

Edit activity_main.xml layout

This is the layout of the main activity and the file name is activity_main.xml.

Edit MainActivity.java class

The following code is my MainActivity.java. It is to perform a click to send a broadcast receiver.

Run your Project

Now, you can start your project in your emulator or android device to test the broadcast receiver.

(Android BroadcastReceiver)

Source Code

(Visited 567 times, 1 visits today)
Advertisements

Yong Loon Ng

Ng Yong Loon, better known as Kristofer is a software engineer and computer scientist who doubles up as an entrepreneur.

You may also like...

2 Responses

  1. September 18, 2016

    […] of the application and it is take caring when the connection is failure or system reboots. The broadcastreceiver which can use to combine with download manager for notify downloaded file. In this tutorial, I will […]

Leave a Reply

Your email address will not be published. Required fields are marked *