Tutorial details

Android broadcast receiver: Enable and disable during runtime | App Code for Sale | Preview

Android broadcast receiver: Enable and disable during runtime | Android Tutorial

How to enable and disable the broadcast receiver

Overview PAGE TOP

Broadcast receiver is the one of the basic and important components of the Android application. There are two different ways of adding broadcast receiver in the Android application. It can be added either programmatically or in Android Manifest file. You should be careful while adding broadcast receiver because unnecessary broadcast receivers drain battery power. If you add the broadcast receiver in the Android manifest file, it’s implied that you are going to handle a particular intent in the broadcast receiver and not ignore it. There is a way to enable and disable the broadcast receiver which is added in the manifest file.

Example code PAGE TOP

Application layout file.

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  
07       <Button
08          android:layout_width='fill_parent'
09          android:layout_height='wrap_content'
10          android:padding='@dimen/padding_medium'
11          android:text='@string/start_repeating_alarm'
12          android:onClick='startRepeatingAlarm'
13          tools:context='.EnableDisableBroadcastReceiver' />
14       <Button
15         android:layout_width='fill_parent'
16         android:layout_height='wrap_content'
17         android:padding='@dimen/padding_medium'
18         android:text='@string/cancel_alarm'
19         android:onClick='cancelAlarm'
20         tools:context='.EnableDisableBroadcastReceiver' />
21        
22      <Button
23          android:layout_width='fill_parent'
24          android:layout_height='wrap_content'
25          android:padding='@dimen/padding_medium'
26          android:text='@string/enable_broadcast_receiver'
27          android:onClick='enableBroadcastReceiver'
28          tools:context='.EnableDisableBroadcastReceiver' />
29     <Button
30         android:layout_width='fill_parent'
31         android:layout_height='wrap_content'
32         android:padding='@dimen/padding_medium'
33         android:text='@string/disable_broadcast_receiver'
34         android:onClick='disableBroadcastReceiver'
35         tools:context='.EnableDisableBroadcastReceiver' />
36          
37  </LinearLayout>

In the above layout file, we have used some string constants in buttons’ text field. Let’s define these string constants in string.xml as shown below.

1   <resources>
2       <string name='app_name'>EnableDisableBroadcastReceiver</string>
3       <string name='enable_broadcast_receiver'>Enable Broadcast Receiver</string>
4       <string name='disable_broadcast_receiver'>Disable Broadcast Receiver</string>
5       <string name='start_repeating_alarm'>Start Repeating Alarm</string>
6       <string name='cancel_alarm'>Cancel Alarm</string>
7       <string name='menu_settings'>Settings</string>
8       <stringname='title_activity_enable_disable_boradcast_receiver'>EnableDisableBoradcastReceiver</string>
9   </resources>

Broadcast receiver PAGE TOP

We are going to use AlarmManager to set the repeating alarm which eventually sends the intent at the specific time interval. Read this post to know more about the AlarmManager.Now create AlarmManagerBroadcastReceiver class to extend the BroadcastReceiver class. The content of the class is given below.

01  package com.code4reference.enabledisablebroadcastreceiver;
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.os.PowerManager;
11  import android.widget.Toast;
12  
13  public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
14  
15   final public static String ONE_TIME = 'onetime';
16   @Override
17   public void onReceive(Context context, Intent intent) {
18  
19           //You can do the processing here update the widget/remote views.
20           StringBuilder msgStr = new StringBuilder();
21           //Format time.
22           Format formatter = new SimpleDateFormat('hh:mm:ss a');
23           msgStr.append(formatter.format(new Date()));
24  
25           Toast.makeText(context, msgStr, Toast.LENGTH_SHORT).show();
26                    
27   }
28  }

Enable/Disable Broadcast receiver PAGE TOP

Now we will define main activity which uses alarmManager to set a repeating alarm. The repeating alarm will broadcast intent after every 3 seconds. This alarm has been set in the setRepeatingAlarm() method below.

01  package com.code4reference.enabledisablebroadcastreceiver;
02  
03  import com.example.enabledisablebroadcastreceiver.R;
04  
05  import android.app.Activity;
06  import android.app.AlarmManager;
07  import android.app.PendingIntent;
08  import android.content.ComponentName;
09  import android.content.Context;
10  import android.content.Intent;
11  import android.content.pm.PackageManager;
12  import android.os.Bundle;
13  import android.view.View;
14  import android.widget.Toast;
15  
16  public class EnableDisableBroadcastReceiver extends Activity {
17  
18      @Override
19      public void onCreate(Bundle savedInstanceState) {
20          super.onCreate(savedInstanceState);
21          setContentView(R.layout.activity_main);
22      }
23      /**
24       * This method gets called when 'Start Repeating Alarm' button is pressed.
25       * It sets the repeating alarm whose periodicity is 3 seconds.
26       * @param view
27       */
28      public void startRepeatingAlarm(View view)
29      {
30          AlarmManager am=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
31          Intent intent = new Intent(this, AlarmManagerBroadcastReceiver.class);
32          PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
33          //After after 2 seconds
34          am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 4 , pi);
35          Toast.makeText(this, 'Started Repeating Alarm', Toast.LENGTH_SHORT).show();
36      }
37   /**
38    * This method gets called when 'cancel Alarm' button is pressed.
39    * This method cancels the previously set repeating alarm.
40    * @param view
41    */
42      public void cancelAlarm(View view)
43      {
44          Intent intent = new Intent(this, AlarmManagerBroadcastReceiver.class);
45          PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
46          AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
47          alarmManager.cancel(sender);
48          Toast.makeText(this, 'Cancelled alarm', Toast.LENGTH_SHORT).show();
49      }
50      /**
51       * This method enables the Broadcast receiver registered in the AndroidManifest file.
52       * @param view
53       */
54     public void enableBroadcastReceiver(View view){
55      ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
56      PackageManager pm = this.getPackageManager();
57  
58      pm.setComponentEnabledSetting(receiver,
59              PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
60              PackageManager.DONT_KILL_APP);
61      Toast.makeText(this, 'Enabled broadcast receiver', Toast.LENGTH_SHORT).show();
62     }
63     /**
64      * This method disables the Broadcast receiver registered in the AndroidManifest file.
65      * @param view
66      */
67     public void disableBroadcastReceiver(View view){
68      ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
69      PackageManager pm = this.getPackageManager();
70  
71      pm.setComponentEnabledSetting(receiver,
72              PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
73              PackageManager.DONT_KILL_APP);
74      Toast.makeText(this, 'Disabled broadcst receiver', Toast.LENGTH_SHORT).show();
75     }

76  }

We add the AlarmManagerBroadcastReceiver in the manifest file. This registers the Broadcast Receiver.

01  <manifest xmlns:android='http://schemas.android.com/apk/res/android'
02      package='com.example.enabledisablebroadcastreceiver'
03      android:versionCode='1'
04      android:versionName='1.0' >
05  
06      <uses-sdk
07          android:minSdkVersion='15'
08          android:targetSdkVersion='15' />
09      <application
10          android:icon='@drawable/ic_launcher'
11          android:label='@string/app_name'
12          android:theme='@style/AppTheme' >
13          <activity
14              android:name='com.code4reference.enabledisablebroadcastreceiver.EnableDisableBroadcastReceiver'
15              android:label='@string/title_activity_enable_disable_boradcast_receiver' >
16              <intent-filter>
17                  <action android:name='android.intent.action.MAIN' />
18                  <category android:name='android.intent.category.LAUNCHER' />
19              </intent-filter>
20          </activity>
21          <!-- Broadcast receiver -->
22          <receiverandroid:name='com.code4reference.enabledisablebroadcastreceiver.AlarmManagerBroadcastReceiver' />
23      </application>
24  </manifest>

Once done, execute the code and you will notice the application as shown below.

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

Reference PAGE TOP

http://www.javacodegeeks.com/2012/08/android-broadcast-receiver-enable-and.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.