Why not doing unregisterReceiver(BroadcastReceiver) while destroy the activity will cause the memory leak?

983 views Asked by At

I am aware that not doing the unregisterReveiver(BroadcastReceiver) will lead to the memory leak when Activity destroys. But I don't understand why it is leading to the memory leak.

I am registering the receiver in the activity using LocalBroadcastManager. Even though activity destroy, BroadcastReceiver will hold the context reference ?

1

There are 1 answers

0
Yves Delerm On

I guess it is the LocalBroadcastManager that keeps an instance of BroadcastReceiver.

So, when the activity is destroyed, the BroadcastReceiver is out of date and should be unregistered, so that it would be cleaned.

By not doing the unregisterReceiver(BroadcastReceiver), the useless BroadcastReceiver is kept, and this is what causes the memory leak.

If the activity is stopped x times, there will be x BroadcastReceiver leaked.