Android Core

Android broadcast receiver: Enable and disable during runtime

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

Application layout file.

<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/start_repeating_alarm'
        android:onClick='startRepeatingAlarm'
        tools:context='.EnableDisableBroadcastReceiver' />
     <Button
       android:layout_width='fill_parent'
       android:layout_height='wrap_content'
       android:padding='@dimen/padding_medium'
       android:text='@string/cancel_alarm'
       android:onClick='cancelAlarm'
       tools:context='.EnableDisableBroadcastReceiver' />
     
    <Button
        android:layout_width='fill_parent'
        android:layout_height='wrap_content'
        android:padding='@dimen/padding_medium'
        android:text='@string/enable_broadcast_receiver'
        android:onClick='enableBroadcastReceiver'
        tools:context='.EnableDisableBroadcastReceiver' />
   <Button
       android:layout_width='fill_parent'
       android:layout_height='wrap_content'
       android:padding='@dimen/padding_medium'
       android:text='@string/disable_broadcast_receiver'
       android:onClick='disableBroadcastReceiver'
       tools:context='.EnableDisableBroadcastReceiver' />
       
</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.

<resources>
    <string name='app_name'>EnableDisableBroadcastReceiver</string>
    <string name='enable_broadcast_receiver'>Enable Broadcast Receiver</string>
    <string name='disable_broadcast_receiver'>Disable Broadcast Receiver</string>
    <string name='start_repeating_alarm'>Start Repeating Alarm</string>
    <string name='cancel_alarm'>Cancel Alarm</string>
    <string name='menu_settings'>Settings</string>
    <string name='title_activity_enable_disable_boradcast_receiver'>EnableDisableBoradcastReceiver</string>
</resources>


Broadcast receiver

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.

package com.code4reference.enabledisablebroadcastreceiver;

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.os.PowerManager;
import android.widget.Toast;

public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {

 final public static String ONE_TIME = 'onetime';
 @Override
 public void onReceive(Context context, Intent intent) {

         //You can do the processing here update the widget/remote views.
         StringBuilder msgStr = new StringBuilder();
         //Format time.
         Format formatter = new SimpleDateFormat('hh:mm:ss a');
         msgStr.append(formatter.format(new Date()));

         Toast.makeText(context, msgStr, Toast.LENGTH_SHORT).show();
                 
 }
}


Enable/Disable Broadcast receiver

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.

package com.code4reference.enabledisablebroadcastreceiver;

import com.example.enabledisablebroadcastreceiver.R;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class EnableDisableBroadcastReceiver extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    /**
     * This method gets called when 'Start Repeating Alarm' button is pressed.
     * It sets the repeating alarm whose periodicity is 3 seconds.
     * @param view
     */
    public void startRepeatingAlarm(View view)
    {
        AlarmManager am=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmManagerBroadcastReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
        //After after 2 seconds
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 4 , pi); 
        Toast.makeText(this, 'Started Repeating Alarm', Toast.LENGTH_SHORT).show();
    }
 /**
  * This method gets called when 'cancel Alarm' button is pressed.
  * This method cancels the previously set repeating alarm.
  * @param view
  */
    public void cancelAlarm(View view)
    {
        Intent intent = new Intent(this, AlarmManagerBroadcastReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
        Toast.makeText(this, 'Cancelled alarm', Toast.LENGTH_SHORT).show();
    }
    /**
     * This method enables the Broadcast receiver registered in the AndroidManifest file.
     * @param view
     */
   public void enableBroadcastReceiver(View view){
    ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
    PackageManager pm = this.getPackageManager();

    pm.setComponentEnabledSetting(receiver,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
    Toast.makeText(this, 'Enabled broadcast receiver', Toast.LENGTH_SHORT).show();
   }
   /**
    * This method disables the Broadcast receiver registered in the AndroidManifest file.
    * @param view
    */
   public void disableBroadcastReceiver(View view){
    ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
    PackageManager pm = this.getPackageManager();

    pm.setComponentEnabledSetting(receiver,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);
    Toast.makeText(this, 'Disabled broadcst receiver', Toast.LENGTH_SHORT).show();
   }   
}

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

<manifest xmlns:android='http://schemas.android.com/apk/res/android'
    package='com.example.enabledisablebroadcastreceiver'
    android:versionCode='1'
    android:versionName='1.0' >

    <uses-sdk
        android:minSdkVersion='15'
        android:targetSdkVersion='15' />
    <application
        android:icon='@drawable/ic_launcher'
        android:label='@string/app_name'
        android:theme='@style/AppTheme' >
        <activity
            android:name='com.code4reference.enabledisablebroadcastreceiver.EnableDisableBroadcastReceiver'
            android:label='@string/title_activity_enable_disable_boradcast_receiver' >
            <intent-filter>
                <action android:name='android.intent.action.MAIN' />
                <category android:name='android.intent.category.LAUNCHER' />
            </intent-filter>
        </activity>
        <!-- Broadcast receiver -->
        <receiver android:name='com.code4reference.enabledisablebroadcastreceiver.AlarmManagerBroadcastReceiver' />
    </application>
</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: Enable and disable Broadcast receiver during runtime from our JCG partner Rakesh Cusat at the Code4Reference blog.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button