In the previous post, we learned 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.

Register/unregister broadcast receiver.

You can get the complete source at github/Code4Reference. You can find more Android tutorials here.

Please feel free to comment on the post or website. Thanks!!

,
Trackback

no comment untill now

Add your comment now