Programmatically register a broadcast receiver


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.

8/26/2014 3:55:54 AM

Accepted Answer

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:, 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.

3/28/2012 6:59:00 PM

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

private BroadcastReceiver receiver;

public void onCreate(Bundle savedInstanceState){

  // your oncreate code should be

  IntentFilter filter = new IntentFilter();

  receiver = new BroadcastReceiver() {
    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:

 protected void onDestroy() {
  if (receiver != null) {
   receiver = null;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow