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'
  xmlns:tools='http://schemas.android.com/tools'
  android:layout_width='match_parent'
  android:layout_height='match_parent'
  android:orientation='vertical'>
   <Button
    android:layout_width='fill_parent'
    android:layout_height='wrap_content'
    android:padding='@dimen/padding_medium'
    android:text='@string/register_broadcast_receiver'
    android:onClick='registerBroadcastReceiver'
    tools:context='.RegisterUnregister' />
  <Button
   android:layout_width='fill_parent'
   android:layout_height='wrap_content'
   android:padding='@dimen/padding_medium'
   android:text='@string/unregister_broadcast_receiver'
   android:onClick='unregisterBroadcastReceiver'
   tools:context='.RegisterUnregister' />

</LinearLayout>

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

<resources>
    <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>
</resources>

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 {

 @Override
 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();

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

 @Override
 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(
    'android.intent.action.TIME_TICK'));
  Toast.makeText(this, 'Registered broadcast receiver', Toast.LENGTH_SHORT)
    .show();
 }

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

  this.unregisterReceiver(broadCastReceiver);

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

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'
 package='com.code4reference.broadcastreceiver.enabledisable'
 android:versionCode='1'
 android:versionName='1.0' >
   <uses-sdk
    android:minSdkVersion='8'
    android:targetSdkVersion='15' />
  <application
    android:icon='@drawable/ic_launcher'
    android:label='@string/app_name'
    android:theme='@style/AppTheme' >
     <activity
      android:name='.RegisterUnregister'
      android:label='@string/title_activity_enable_disable' >
       <intent-filter>
        <action android:name='android.intent.action.MAIN' />
        <category android:name='android.intent.category.LAUNCHER' />
       </intent-filter>
    </activity>
  </application>
</manifest>

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 two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

One Response to "Android broadcast receiver: Registering/unregistering during runtime"

  1. Vamsi says:

    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


+ 3 = five



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close