Tutorial details

Android broadcast receiver: Registering/unregistering during runtime | App Code for Sale | Preview

Android broadcast receiver: Registering/unregistering during runtime | Android Tutorial

How to register and unregister broadcast receiver programmatically

Overview PAGE TOP

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 PAGE TOP

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

01  <LinearLayout xmlns:android='http://schemas.android.com/apk/res/android'
02    xmlns:tools='http://schemas.android.com/tools'
03    android:layout_width='match_parent'
04    android:layout_height='match_parent'
05    android:orientation='vertical'>
06     <Button
07      android:layout_width='fill_parent'
08      android:layout_height='wrap_content'
09      android:padding='@dimen/padding_medium'
10      android:text='@string/register_broadcast_receiver'
11      android:onClick='registerBroadcastReceiver'
12      tools:context='.RegisterUnregister' />
13    <Button
14     android:layout_width='fill_parent'
15     android:layout_height='wrap_content'
16     android:padding='@dimen/padding_medium'
17     android:text='@string/unregister_broadcast_receiver'
18     android:onClick='unregisterBroadcastReceiver'
19     tools:context='.RegisterUnregister' />
20  
21  </LinearLayout>

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

1   <resources>
2       <string name='app_name'>EnableDisableBroadcastReceiver2</string>
3       <string name='menu_settings'>Settings</string>
4       <string name='title_activity_enable_disable'>EnableDisable</string>
5       <string name='register_broadcast_receiver'>Register Broadcast Receiver</string>
6       <string name='unregister_broadcast_receiver'>Unregister Broadcast Receiver</string>
7   </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.

01  package com.code4reference.broadcastreceiver.enabledisable;
02  
03  import java.text.Format;
04  import java.text.SimpleDateFormat;
05  import java.util.Date;
06  
07  import android.content.BroadcastReceiver;
08  import android.content.Context;
09  import android.content.Intent;
10  import android.widget.Toast;
11  
12  public class UserDefinedBroadcastReceiver extends BroadcastReceiver {
13  
14   @Override
15   public void onReceive(Context context, Intent intent) {
16  
17           //You can do the processing here update the widget/remote views.
18           StringBuilder msgStr = new StringBuilder('Current time : ');
19           Format formatter = new SimpleDateFormat('hh:mm:ss a');
20           msgStr.append(formatter.format(new Date()));
21           Toast.makeText(context, msgStr, Toast.LENGTH_SHORT).show();
22   }
23  }

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 TIMETICK intent action type. The TIMETICK intent gets fired every minute. Once the broadcast receiver gets registered, you will notice the toast message after every minute.

01  package com.code4reference.broadcastreceiver.enabledisable;
02  
03  import android.app.Activity;
04  import android.content.IntentFilter;
05  import android.os.Bundle;
06  import android.view.Menu;
07  import android.view.View;
08  import android.widget.Toast;
09  
10  public class RegisterUnregister extends Activity {
11  
12   UserDefinedBroadcastReceiver broadCastReceiver = new UserDefinedBroadcastReceiver();
13  
14   @Override
15   public void onCreate(Bundle savedInstanceState) {
16    super.onCreate(savedInstanceState);
17    setContentView(R.layout.activity_register_unregister);
18   }
19  
20   @Override
21   public boolean onCreateOptionsMenu(Menu menu) {
22    getMenuInflater().inflate(R.menu.activity_enable_disable, menu);
23    return true;
24   }
25  
26   /**
27    * This method enables the Broadcast receiver for
28    * 'android.intent.action.TIME_TICK' intent. This intent get
29    * broadcasted every minute.
30    *
31    * @param view
32    */
33   public void registerBroadcastReceiver(View view) {
34  
35    this.registerReceiver(broadCastReceiver, new IntentFilter(
36      'android.intent.action.TIME_TICK'));
37    Toast.makeText(this, 'Registered broadcast receiver', Toast.LENGTH_SHORT)
38      .show();
39   }
40  
41   /**
42    * This method disables the Broadcast receiver
43    *
44    * @param view
45    */
46   public void unregisterBroadcastReceiver(View view) {
47  
48    this.unregisterReceiver(broadCastReceiver);
49  
50    Toast.makeText(this, 'unregistered broadcst receiver', Toast.LENGTH_SHORT)
51      .show();
52   }
53  }

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

01  <manifest xmlns:android='http://schemas.android.com/apk/res/android'
02   package='com.code4reference.broadcastreceiver.enabledisable'
03   android:versionCode='1'
04   android:versionName='1.0' >
05     <uses-sdk
06      android:minSdkVersion='8'
07      android:targetSdkVersion='15' />
08    <application
09      android:icon='@drawable/ic_launcher'
10      android:label='@string/app_name'
11      android:theme='@style/AppTheme' >
12       <activity
13        android:name='.RegisterUnregister'
14        android:label='@string/title_activity_enable_disable' >
15         <intent-filter>
16          <action android:name='android.intent.action.MAIN' />
17          <category android:name='android.intent.category.LAUNCHER' />
18         </intent-filter>
19      </activity>
20    </application>
21  </manifest>

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

tab.png

You can get the complete source at github/Code4Reference.

Reference PAGE TOP

http://www.javacodegeeks.com/2012/09/android-broadcast-receiver.html

0 Comments Leave a comment

Please login in order to leave a comment.

Newest first
!

Sign-in to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.