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…

Download the Latest Support Library

Download the latest support library revision 13

Link : http://developer.android.com/tools/extras/support-library.html

Replace the old support library (android-support-v4.jar) with the new support library in your project.

Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project BroadcastTutorial.

Application Name : BroadcastTutorial

Project Name : BroadcastTutorial

Package Name : com.androidbegin.broadcasttutorial

Open your MainActivity.java and paste the following code.

MainActivity.java

package com.androidbegin.broadcasttutorial;

import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {
	// Declare Variables
	ToggleButton wifitoggle;
	CheckBox brcheckbox;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from activity_main.xml
		setContentView(R.layout.activity_main);

		// Locate the ToggleButton in activity_main.xml
		wifitoggle = (ToggleButton) findViewById(R.id.wifitoggle);

		// Locate the CheckBox in activity_main.xml
		brcheckbox = (CheckBox) findViewById(R.id.brcheckbox);

		// WifiManager to control the Wifi Service
		final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

		// Capture ToggleButton clicks
		wifitoggle.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (wifitoggle.isChecked()) {
					// Switch On Wifi
					wifiManager.setWifiEnabled(true);
				} else {
					// Switch Off Wifi
					wifiManager.setWifiEnabled(false);
				}
			}
		});

		// Capture CheckBox clicks
		brcheckbox.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (brcheckbox.isChecked()) {
					// Switch On Broadcast Receiver
					PackageManager pm = MainActivity.this.getPackageManager();
					ComponentName componentName = new ComponentName(
							MainActivity.this, BroadcastManager.class);
					pm.setComponentEnabledSetting(componentName,
							PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
							PackageManager.DONT_KILL_APP);
					Toast.makeText(getApplicationContext(),
							"Broadcast Receiver Started", Toast.LENGTH_LONG)
							.show();
				} else {
					// Switch Off Broadcast Receiver
					PackageManager pm = MainActivity.this.getPackageManager();
					ComponentName componentName = new ComponentName(
							MainActivity.this, BroadcastManager.class);
					pm.setComponentEnabledSetting(componentName,
							PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
							PackageManager.DONT_KILL_APP);
					Toast.makeText(getApplicationContext(),
							"Broadcast Receiver Stopped", Toast.LENGTH_LONG)
							.show();

				}
			}
		});
		// If Wifi already turned on switch ToggleButton to on
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm.getActiveNetworkInfo() != null
				&& cm.getActiveNetworkInfo().isAvailable()
				&& cm.getActiveNetworkInfo().isConnected()) {
			wifitoggle.setChecked(true);
		}
	}

	// Not using options menu in this tutorial
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
}

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.

Next, create an XML graphical layout for your MainActivity. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file activity_main.xml and paste the following code.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ToggleButton
        android:id="@+id/wifitoggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textOff="@string/wifioff"
        android:textOn="@string/wifion" />

    <CheckBox
        android:id="@+id/brcheckbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/wifitoggle"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/BroadcastReceiver" />

</RelativeLayout>

Output:

BroadcastReceiver Main XML

Next, create a Broadcast Receiver class. Go to File > New > Class and name it BroadcastManager.java. Select your package named com.androidbegin.broadcasttutorial and click Finish.

Open your BroadcastManager.java and paste the following code.

BroadcastManager.java

package com.androidbegin.broadcasttutorial;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.NotificationCompat;

public class BroadcastManager extends BroadcastReceiver {

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

		if (!isNetworkAvailable(context)) {
			Notification(context, "Wifi Connection Off");

		} else {
			Notification(context, "Wifi Connection On");
		}

	}

	public void Notification(Context context, String message) {
		// Set Notification Title
		String strtitle = context.getString(R.string.notificationtitle);
		// Open NotificationView Class on Notification Click
		Intent intent = new Intent(context, NotificationView.class);
		// Send data to NotificationView Class
		intent.putExtra("title", strtitle);
		intent.putExtra("text", message);
		// Open NotificationView.java Activity
		PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent,
				PendingIntent.FLAG_UPDATE_CURRENT);

		// Create Notification using NotificationCompat.Builder
		NotificationCompat.Builder builder = new NotificationCompat.Builder(
				context)
				// Set Icon
				.setSmallIcon(R.drawable.logosmall)
				// Set Ticker Message
				.setTicker(message)
				// Set Title
				.setContentTitle(context.getString(R.string.notificationtitle))
				// Set Text
				.setContentText(message)
				// Add an Action Button below Notification
				.addAction(R.drawable.ic_launcher, "Action Button", pIntent)
				// Set PendingIntent into Notification
				.setContentIntent(pIntent)
				// Dismiss Notification
				.setAutoCancel(true);

		// Create Notification Manager
		NotificationManager notificationmanager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		// Build Notification with Notification Manager
		notificationmanager.notify(0, builder.build());

	}

	// Check for network availability
	private boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null;
	}

}

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:

Broadcast Receiver Notification

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.

Open your NotificationView.java and paste the following code.

NotificationView.java

package com.androidbegin.broadcasttutorial;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class NotificationView extends Activity {
    // Declare Variable
	String title;
    String text;
    TextView txttitle;
    TextView txttext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notificationview);

        // Create Notification Manager
        NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // Dismiss Notification
        notificationmanager.cancel(0);

        // Retrive the data from MainActivity.java
        Intent i = getIntent();

        title = i.getStringExtra("title");
        text = i.getStringExtra("text");

        // Locate the TextView
        txttitle = (TextView) findViewById(R.id.title);
        txttext = (TextView) findViewById(R.id.text);

        // Set the data into TextView
        txttitle.setText(title);
        txttext.setText(text);
    }
}

Next, create an XML graphical layout to view a notification. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file notificationview.xml and paste the following code.

notificationview.xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/lbltitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/lbltitle" />

    <TextView
        android:id="@+id/lbltext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/lbltitle"
        android:text="@string/lbltext" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/lbltitle" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         android:layout_below="@+id/title"
        android:layout_toRightOf="@+id/lbltext" />

</RelativeLayout>

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

strings.xml

<resources>

    <string name="app_name">Broadcast Tutorial</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Broadcast Tutorial</string>
    <string name="notificationtitle">Broadcast Tutorial</string>
    <string name="lbltitle">"Title : "</string>
    <string name="lbltext">"Text : "</string>
    <string name="BroadcastReceiver">Broadcast Receiver</string>
    <string name="wifioff">WIFI OFF</string>
    <string name="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.

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbegin.broadcasttutorial"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".BroadcastManager" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

        <activity android:name=".NotificationView" >
        </activity>
    </application>

</manifest>

Output:

Broadcast Receiver ScreenShot

Source Code 

BroadcastTutorial (846.9 KiB, 216 downloads)