Search code examples
androidbroadcastreceiverandroid-broadcastandroid-broadcastreceiver

Is unregisterReceiver absolutely required for a context-based Android Broadcast Receiver?


The Android developer pages for Broadcasts say this about broadcast receivers and their receiving of broadcasts:

Context-registered receivers receive broadcasts as long as their registering context is valid. For an example, if you register within an Activity context, you receive broadcasts as long as the activity is not destroyed.

It also says this:

Be mindful of where you register and unregister the receiver, for example, if you register a receiver in onCreate(Bundle) using the activity's context, you should unregister it in onDestroy() to prevent leaking the receiver out of the activity context.

To me, this means that if you register a receiver in a context of an activity but do not unregister it when that activity is destroyed, you will not longer receive broadcasts but you will still "leak" the receiver. Is this correct?

The reason why I want to know this precisely is that I want to wrap a context-based broadcast receiver an in object, and I'd like the interface to this object to be like this:

class DoesManyThings {
    DoesManyThings(Context context) {
        context.registerReceiver(...);
    }
}

I will create this object in the onCreate method of an activity. But if I do this, I will not know when to unregister the receiver and I will have to add an explicit method like void cleanup() which I have to call at onDestroy. I'd like to know whether I have to do this explicit cleanup.


Solution

  • I believe your understanding is correct - once the activity is destroyed, you should no longer receive broadcasts. However, since you haven't unregistered, you may still leak the object. (At the very least, you'll get unhappy warning messages in your logcat about this)

    Just from a code cleanliness standpoint, it feels like you should have a cleanup method as well. In the future, you may extend what the "DoesManyThings" object does, and other state you add may be less safe to hold on to outside the lifecycle of an Activity.

    However, note that onDestroy is not guaranteed to be called. You may wish to consider moving to onStart/onStop - but that depends on your exact use case for the dynamic receiver.