Android Broadcast Receiver Notification Tutorial

In this tutorial, you will learn how to implement a Broadcast Receiver in your Android application. Broadcast Receiver is completely asynchronous, and is considered to be a foreground process and will be kept running with the Android system. We will be creating an activity that consists of a ToggleButton and a CheckBox that switches the Wifi and Broadcast Receiver on or off. A notification will be shown if the Broadcast Receiver is turned on while switching the Wifi on or off. So lets begin…

In this activity, we have created a toggle and a checkbox button. On toggle button click will switch on or off the wifi services and on checkbox check or uncheck will start or stop the broadcast receiver.

Broadcast Receiver checks for network availability asynchronously. So if the wifi is turned on or off, the application will be notified immediately and a notification will be shown.

Output:

Next, create an activity to view results on notification click. Go to File > New > Class and name it NotificationView.java. Select your package named com.androidbegin.broadcasttutorial and click Finish.

Next, change the application name and texts. Open your strings.xml in your res > values folder and paste the following code.

strings.xml

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<resources>

<stringname="app_name">Broadcast Tutorial</string>

<stringname="hello_world">Hello world!</string>

<stringname="menu_settings">Settings</string>

<stringname="title_activity_main">Broadcast Tutorial</string>

<stringname="notificationtitle">Broadcast Tutorial</string>

<stringname="lbltitle">"Title : "</string>

<stringname="lbltext">"Text : "</string>

<stringname="BroadcastReceiver">Broadcast Receiver</string>

<stringname="wifioff">WIFI OFF</string>

<stringname="wifion">WIFI ON</string>

</resources>

In your AndroidManifest.xml, we need to declare an activity, a broadcast manager and permissions to allow the application to change the wifi state and ability to access network state. Open your AndroidManifest.xml and paste the following code.