Programmatically register a broadcast receiver

CoolStraw picture CoolStraw · Jan 26, 2011 · Viewed 208.2k times · Source

I'd like to know what is the best practice/way of programmatically register a broadcast receiver. I want to register specific receivers according to user choice.

As the registration is done through the manifest file, I'm wondering if there's a proper way to achieve this in code.

Answer

Eric Nordvik picture Eric Nordvik · Jan 26, 2011

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

private BroadcastReceiver receiver;

@Override
public 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();
 }