Home » Android » Android Core » Android broadcast receiver: Registering/unregistering during runtime

About Rakesh Cusat

Android broadcast receiver: Registering/unregistering during runtime

In the previous post, we leaned to enable and disable the Broadcast receiver added in the Android manifest file. In this post, we will learn to register and unregister broadcast receiver programmatically. It’s always suggested to register and unregister broadcast receiver programmatically as it saves system resources. In this tutorial, we will make an application having two buttons to register and unregister the broadcast receiver respectively.

Example Code

Let’s define the layout file and add two buttons. Associate registerBroadcastReceiver onclick method with register button and unregisterBroadcastReceiver onclick method with unregister button.

<LinearLayout xmlns:android='http://schemas.android.com/apk/res/android'
    tools:context='.RegisterUnregister' />
   tools:context='.RegisterUnregister' />


Define the string constants used in layout file in string.xml.

    <string name='app_name'>EnableDisableBroadcastReceiver2</string>
    <string name='menu_settings'>Settings</string>
    <string name='title_activity_enable_disable'>EnableDisable</string>
    <string name='register_broadcast_receiver'>Register Broadcast Receiver</string>
    <string name='unregister_broadcast_receiver'>Unregister Broadcast Receiver</string>

Now define the broadcast receiver. In onReceive() method, we will show a toast message containing the current time. The onReceive() method gets invoked when the particular intent is broadcasted.

package com.code4reference.broadcastreceiver.enabledisable;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class UserDefinedBroadcastReceiver extends BroadcastReceiver {

 public void onReceive(Context context, Intent intent) {

         //You can do the processing here update the widget/remote views.
         StringBuilder msgStr = new StringBuilder('Current time : ');
         Format formatter = new SimpleDateFormat('hh:mm:ss a');
         msgStr.append(formatter.format(new Date()));
         Toast.makeText(context, msgStr, Toast.LENGTH_SHORT).show();

We are going to define the main activity class called RegisterUnregister. In this class we will define two onclick methods, registerBroadcastReceiver and unregisterBroadcastReceiver attached with Register and Unregister buttons in layout file respectively. The registerBroadcastReceiver() method registers the UserDefinedBroadcastReceiver for TIME_TICK intent action type. The TIME_TICK intent gets fired every minute. Once the broadcast receiver gets registered, you will notice the toast message after every minute.

package com.code4reference.broadcastreceiver.enabledisable;

import android.app.Activity;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class RegisterUnregister extends Activity {

 UserDefinedBroadcastReceiver broadCastReceiver = new UserDefinedBroadcastReceiver();

 public void onCreate(Bundle savedInstanceState) {

 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.activity_enable_disable, menu);
  return true;

  * This method enables the Broadcast receiver for
  * 'android.intent.action.TIME_TICK' intent. This intent get
  * broadcasted every minute.
  * @param view
 public void registerBroadcastReceiver(View view) {

  this.registerReceiver(broadCastReceiver, new IntentFilter(
  Toast.makeText(this, 'Registered broadcast receiver', Toast.LENGTH_SHORT)

  * This method disables the Broadcast receiver
  * @param view
 public void unregisterBroadcastReceiver(View view) {


  Toast.makeText(this, 'unregistered broadcst receiver', Toast.LENGTH_SHORT)

We will not modify the AndroidManifest file because we are not registering the broadcast receiver in AndroidManifest file.

<manifest xmlns:android='http://schemas.android.com/apk/res/android'
 android:versionName='1.0' >
    android:targetSdkVersion='15' />
    android:theme='@style/AppTheme' >
      android:label='@string/title_activity_enable_disable' >
        <action android:name='android.intent.action.MAIN' />
        <category android:name='android.intent.category.LAUNCHER' />

Just complete the coding and execute the code and you will see the application as shown below.

You can get the complete source at github/Code4Reference.

Reference: Registering/unregistering of Android broadcast receiver during runtime. from our JCG partner Rakesh Cusat at the Code4Reference blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....


One comment

  1. Thanks for the tutorial,My code is this , http://pastebin.com/wdRqksD5
    but i am getting an error message of this http://pastebin.com/HEZPvNjn
    can you help me out pls

Leave a Reply

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


Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.