{"id":19,"date":"2012-12-17T18:03:02","date_gmt":"2012-12-17T18:03:02","guid":{"rendered":"https:\/\/code4reference.com\/?p=19"},"modified":"2012-12-17T18:03:02","modified_gmt":"2012-12-17T18:03:02","slug":"code4referenceregistering-unregistering-android-broadcast-receiver","status":"publish","type":"post","link":"https:\/\/code4reference.com\/?p=19","title":{"rendered":"Code4ReferenceRegistering\/Unregistering Android broadcast receiver."},"content":{"rendered":"<p>In the <a href=\"http:\/\/code4reference.com\/2012\/08\/enabling-disabling-broadcast-receiver-during-runtime\/\">previous post<\/a>, 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\u2019s 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.<\/p>\n<h4>Example Code<\/h4>\n<p>Let\u2019s define the layout file and add two buttons. Associate registerBroadcastReceiver onclick method with register button and unregisterBroadcastReceiver onclick method with unregister button.<\/p>\n<pre>\n\n   \n  \n\n\n <\/pre>\n<p>Define the string constants used in layout file in string.xml.<\/p>\n<pre>\n\n    EnableDisableBroadcastReceiver2\n    Settings\n    EnableDisable\n    Register Broadcast Receiver\n    Unregister Broadcast Receiver\n\n<\/pre>\n<p>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.<\/p>\n<pre>\npackage com.code4reference.broadcastreceiver.enabledisable;\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.widget.Toast;\n\npublic class UserDefinedBroadcastReceiver extends BroadcastReceiver {\n\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(\"Current time : \");\n         Format formatter = new SimpleDateFormat(\"hh:mm:ss a\");\n         msgStr.append(formatter.format(new Date()));\n         Toast.makeText(context, msgStr, Toast.LENGTH_SHORT).show();\n        }\n}\n<\/pre>\n<p>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.<\/p>\n<pre>\npackage com.code4reference.broadcastreceiver.enabledisable;\n\nimport android.app.Activity;\nimport android.content.IntentFilter;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.view.View;\nimport android.widget.Toast;\n\npublic class RegisterUnregister extends Activity {\n\n        UserDefinedBroadcastReceiver broadCastReceiver = new UserDefinedBroadcastReceiver();\n\n        @Override\n        public void onCreate(Bundle savedInstanceState) {\n                super.onCreate(savedInstanceState);\n                setContentView(R.layout.activity_register_unregister);\n        }\n\n        @Override\n        public boolean onCreateOptionsMenu(Menu menu) {\n                getMenuInflater().inflate(R.menu.activity_enable_disable, menu);\n                return true;\n        }\n\n        \/**\n         * This method enables the Broadcast receiver for\n         * \"android.intent.action.TIME_TICK\" intent. This intent get\n         * broadcasted every minute.\n         *\n         * @param view\n         *\/\n        public void registerBroadcastReceiver(View view) {\n\n                this.registerReceiver(broadCastReceiver, new IntentFilter(\n                                \"android.intent.action.TIME_TICK\"));\n                Toast.makeText(this, \"Registered broadcast receiver\", Toast.LENGTH_SHORT)\n                                .show();\n        }\n\n        \/**\n         * This method disables the Broadcast receiver\n         *\n         * @param view\n         *\/\n        public void unregisterBroadcastReceiver(View view) {\n\n                this.unregisterReceiver(broadCastReceiver);\n\n                Toast.makeText(this, \"unregistered broadcst receiver\", Toast.LENGTH_SHORT)\n                                .show();\n        }\n}\n\n<\/pre>\n<p>We will not modify the AndroidManifest file because we are not registering the broadcast receiver in AndroidManifest file.<\/p>\n<pre>\n\n   \n  \n     \n       \n        \n        \n       \n    \n  \n\n<\/pre>\n<p>Just complete the coding and execute the code and you will see the application as shown below.<\/p>\n<p><a href=\"http:\/\/code4reference.com\/wp-content\/uploads\/2012\/09\/register-unregister-braodcastreceiver.png\"><img alt='register-unregister-braodcastreceiver-180x300-2458602' src='https:\/\/code4reference.com\/wp-content\/uploads\/2012\/12\/register-unregister-braodcastreceiver-180x300-2458602.png' \/><\/a><\/p>\n<p>You can get the complete source at <a href=\"http:\/\/github.com\/rakeshcusat\/Code4Reference\/tree\/master\/AndroidProjects\/EnableDisableBroadcastReceiver2\">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. Thanks!!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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\u2019s always suggested to register and unregister broadcast receiver programmatically as it saves system resources. In this tutorial, we will make an application [&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-19","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/19","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=19"}],"version-history":[{"count":0,"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/19\/revisions"}],"wp:attachment":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=19"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=19"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=19"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}