When to Register/Unregister Broadcast Receivers created in an activity?

jamesc picture jamesc · Oct 25, 2011 · Viewed 53.2k times · Source

I have a need to create a custom broadcast receiver in the onCreate event of an activity and obviously I need to unRegister the broadcast receiver in the onDestroy event of the activity

For clarity this is a snippet of the code I use

public class AnActivity extends Activity {
    private ResponseReceiver receiver;

    public class ResponseReceiver extends BroadcastReceiver {
           public static final String ACTION_RESP =
              "mypackagename.intent.action.MESSAGE_PROCESSED";

           @Override
            public void onReceive(Context context, Intent intent) {
// TODO Start a dialogue if message indicates successfully posted to server
            }
    }   

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        receiver = new ResponseReceiver();
        registerReceiver(receiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

I have read that onPause/onResume and onStart/onStop events for the activity should also register and unregister the broadcast receiver.

I'm really wanting to understand what is considered to be the best practice for this and why.

Answer

SnowyTracks picture SnowyTracks · Oct 25, 2011

You should register and unregister your receivers onStart() and onStop().

The only reason an Activity would register BroadcastReceivers is to use the events in some way on the current activity, to inform the User of an event. If onStop() has been called, then the Activity is no longer in the foreground, and therefore cant update the User.

If you want to receive broadcast events in the background you should consider using a service as indicated here.

Like Konstantin says, onDestroy() is not guaranteed to be called, and you could continue receiving broadcasts for a long time, when the Activity is no longer open.