{"id":56,"date":"2013-06-06T03:44:28","date_gmt":"2013-06-06T03:44:28","guid":{"rendered":"https:\/\/code4reference.com\/?p=56"},"modified":"2023-10-01T13:35:57","modified_gmt":"2023-10-01T13:35:57","slug":"code4referenceenable-and-disable-broadcast-receiver-during-runtime","status":"publish","type":"post","link":"https:\/\/code4reference.com\/?p=56","title":{"rendered":"Enable and disable broadcast receiver during runtime"},"content":{"rendered":"<p>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\u2019s 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.<\/p>\n<h3>Example code<\/h3>\n<p>Application layout file.<\/p>\n<pre>\n\n\n     \n     \n\n    \n   \n\n\n<\/pre>\n<p>In the above layout file, we have used some string constants in buttons\u2019 text field. Let\u2019s define these string constants in string.xml as shown below.<\/p>\n<pre>\n\n    EnableDisableBroadcastReceiver\n    Enable Broadcast Receiver\n    Disable Broadcast Receiver\n    Start Repeating Alarm\n    Cancel Alarm\n    Settings\n    EnableDisableBoradcastReceiver\n\n<\/pre>\n<h4>Broadcast receiver<\/h4>\n<p>We are going to use <a href=\"http:\/\/code4reference.com\/2012\/07\/tutorial-on-android-alarmmanager\/\">AlarmManager<\/a> to set the repeating alarm which eventually sends the intent at the specific time interval. Read <a href=\"http:\/\/code4reference.com\/2012\/07\/tutorial-on-android-alarmmanager\/\">this post<\/a> to know more about the AlarmManager.Now create AlarmManagerBroadcastReceiver class to extend the BroadcastReceiver class. The content of the class is given below.<\/p>\n<pre>\npackage com.code4reference.enabledisablebroadcastreceiver;\n\nimport java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.PowerManager;\nimport android.widget.Toast;\n\npublic class AlarmManagerBroadcastReceiver extends BroadcastReceiver {\n\n        final public static String ONE_TIME = \"onetime\";\n        @Override\n        public void onReceive(Context context, Intent intent) {\n\n         \/\/You can do the processing here update the widget\/remote views.\n         StringBuilder msgStr = new StringBuilder();\n         \/\/Format time.\n         Format formatter = new SimpleDateFormat(\"hh:mm:ss a\");\n         msgStr.append(formatter.format(new Date()));\n\n         Toast.makeText(context, msgStr, Toast.LENGTH_SHORT).show();\n\n        }\n}\n<\/pre>\n<h4>Enable\/Disable Broadcast receiver<\/h4>\n<p>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.<\/p>\n<pre>\npackage com.code4reference.enabledisablebroadcastreceiver;\n\nimport com.example.enabledisablebroadcastreceiver.R;\n\nimport android.app.Activity;\nimport android.app.AlarmManager;\nimport android.app.PendingIntent;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Toast;\n\npublic class EnableDisableBroadcastReceiver extends Activity {\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n    }\n    \/**\n     * This method gets called when \"Start Repeating Alarm\" button is pressed.\n     * It sets the repeating alarm whose periodicity is 3 seconds.\n     * @param view\n     *\/\n    public void startRepeatingAlarm(View view)\n    {\n        AlarmManager am=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);\n        Intent intent = new Intent(this, AlarmManagerBroadcastReceiver.class);\n        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);\n        \/\/After after 2 seconds\n        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 4 , pi);\n        Toast.makeText(this, \"Started Repeating Alarm\", Toast.LENGTH_SHORT).show();\n    }\n        \/**\n         * This method gets called when \"cancel Alarm\" button is pressed.\n         * This method cancels the previously set repeating alarm.\n         * @param view\n         *\/\n    public void cancelAlarm(View view)\n    {\n        Intent intent = new Intent(this, AlarmManagerBroadcastReceiver.class);\n        PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);\n        AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);\n        alarmManager.cancel(sender);\n        Toast.makeText(this, \"Cancelled alarm\", Toast.LENGTH_SHORT).show();\n    }\n    \/**\n     * This method enables the Broadcast receiver registered in the AndroidManifest file.\n     * @param view\n     *\/\n   public void enableBroadcastReceiver(View view){\n           ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);\n           PackageManager pm = this.getPackageManager();\n\n           pm.setComponentEnabledSetting(receiver,\n                   PackageManager.COMPONENT_ENABLED_STATE_ENABLED,\n                   PackageManager.DONT_KILL_APP);\n           Toast.makeText(this, \"Enabled broadcast receiver\", Toast.LENGTH_SHORT).show();\n   }\n   \/**\n    * This method disables the Broadcast receiver registered in the AndroidManifest file.\n    * @param view\n    *\/\n   public void disableBroadcastReceiver(View view){\n           ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);\n           PackageManager pm = this.getPackageManager();\n\n           pm.setComponentEnabledSetting(receiver,\n                   PackageManager.COMPONENT_ENABLED_STATE_DISABLED,\n                   PackageManager.DONT_KILL_APP);\n           Toast.makeText(this, \"Disabled broadcst receiver\", Toast.LENGTH_SHORT).show();\n   }\n}\n<\/pre>\n<p>We add the AlarmManagerBroadcastReceiver in the manifest file. This registers the Broadcast Receiver.<\/p>\n<pre>\n\n\n    \n    \n        \n            \n                \n                \n            \n        \n        \n        \n    \n\n<\/pre>\n<p>Once done, execute the code and you will notice the application as shown below.<\/p>\n<p><a href=\"http:\/\/code4reference.com\/wp-content\/uploads\/2012\/08\/enable-disable-broadcastReceiver.png\"><img alt='enable-disable-broadcastreceiver-180x300-6623194' src='https:\/\/code4reference.com\/wp-content\/uploads\/2013\/06\/enable-disable-broadcastReceiver-180x300-6623194.png' \/><\/a><\/p>\n<p>You can get the complete source at <a href=\"http:\/\/github.com\/rakeshcusat\/Code4Reference\/tree\/master\/AndroidProjects\/EnableDisableBroadcastReceiver\">github\/Code4Reference<\/a>. You can find more <strong><a href=\"http:\/\/code4reference.com\/android-tutorials\/\">Android tutorials here.<\/a><\/strong><\/p>\n<p>Please feel free to comment on the post or website.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-56","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/56","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=56"}],"version-history":[{"count":1,"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/56\/revisions"}],"predecessor-version":[{"id":361,"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/56\/revisions\/361"}],"wp:attachment":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=56"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=56"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=56"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}