Programmatically register a broadcast receiver Programmatically register a broadcast receiver android android

Programmatically register a broadcast receiver


In your onCreate method you can register a receiver like this:

private BroadcastReceiver receiver;@Overridepublic void onCreate(Bundle savedInstanceState){  // your oncreate code should be  IntentFilter filter = new IntentFilter();  filter.addAction("SOME_ACTION");  filter.addAction("SOME_OTHER_ACTION");  receiver = new BroadcastReceiver() {    @Override    public void onReceive(Context context, Intent intent) {      //do something based on the intent's action    }  };     registerReceiver(receiver, filter);}

Remember to run this in the onDestroy method:

 @Override protected void onDestroy() {  if (receiver != null) {   unregisterReceiver(receiver);   receiver = null;  }  super.onDestroy(); }


One important point that people forget to mention is the life time of the Broadcast Receiver. The difference of programmatically registering it from registering in AndroidManifest.xml is that. In the manifest file, it doesn't depend on application life time. While when programmatically registering it it does depend on the application life time. This means that if you register in AndroidManifest.xml, you can catch the broadcasted intents even when your application is not running.

Edit: The mentioned note is no longer true as of Android 3.1, the Android system excludes all receiver from receiving intents by default if the corresponding application has never been started by the user or if the user explicitly stopped the application via the Android menu (in Manage → Application). https://developer.android.com/about/versions/android-3.1.html

This is an additional security feature as the user can be sure that only the applications he started will receive broadcast intents.

So it can be understood as receivers programmatically registered in Application's onCreate() would have same effect with ones declared in AndroidManifest.xml from Android 3.1 above.


It sounds like you want to control whether components published in your manifest are active, not dynamically register a receiver (via Context.registerReceiver()) while running.

If so, you can use PackageManager.setComponentEnabledSetting() to control whether these components are active:

http://developer.android.com/reference/android/content/pm/PackageManager.html#setComponentEnabledSetting(android.content.ComponentName, int, int)

Note if you are only interested in receiving a broadcast while you are running, it is better to use registerReceiver(). A receiver component is primarily useful for when you need to make sure your app is launched every time the broadcast is sent.