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.

Related Whitepaper:

Rapid Android Development: Build Rich, Sensor-Based Applications with Processing

Create mobile apps for Android phones and tablets faster and more easily than you ever imagined

Use 'Processing', the free, award-winning, graphics-savvy language and development environment, to work with the touchscreens, hardware sensors, cameras, network transceivers, and other devices and software in the latest Android phones and tablets.

Get it Now!  

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


seven + 9 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books