In Android, I've registered a BroadcastReceiver in my onCreate(). Where should I unregister so that I won't have leaked receivers?
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.
You should register and unregister your broadcast in onResume() and onPause() methods. if you register in onStart() and unregister it in onStop().
Receiver can be registered via the Android manifest file. You can also register and unregister a receiver at runtime via the Context. registerReceiver() and Context. unregisterReceiver() methods.
As a general rule, broadcast receivers are allowed to run for up to 10 seconds before they system will consider them non-responsive and ANR the app.
http://developer.android.com/reference/android/content/BroadcastReceiver.html
"You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the tag in your AndroidManifest.xml. Note: If registering a receiver in your Activity.onResume() implementation, you should unregister it in Activity.onPause(). (You won't receive intents when paused, and this will cut down on unnecessary system overhead). Do not unregister in Activity.onSaveInstanceState()."
:) The SDK is your best friend. I would say do what it says in the SDK unless you absolutely need the receiver when paused but be careful. Do you have to dynamically register the receiver or would putting it in the AndroidManifest.xml be better? If you put the receiver in the manifest you won't need to worry about registering/unregistering it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With