Is it possible to dynamically register a broadcast receiver in a fragment to listen for connectivity state changes? If so how? If not, what are some workarounds for fragments?
EDIT: To register a BroadcastReceiver you need a Context. Since fragments live within activities, probably the best way to get a Context is to just use getActivity(). However, as gnorsilva explains below, there are certain special cases to look out for.
user853583 suggestion is a good one, but if you need access to a context inside a fragment you should use getActivity().getApplicationContext()
You should avoid passing an activity as a context whenever possible as this can introduce memory leaks - some object will hold on to that activity after its onDestroy() has been called and it won't be garbage collected.
Having said that, there are cases when you do need to pass an activity as a context - eg: for list adapters
Two more things though:
because a fragment is attached and detached from an activity, some times getActivity()
returns null - you can call it safely inside certain lifecycle methods where you know an activity is alive eg: onResume()
if your fragment does not retain its instance i.e. is destroyed on orientation change, be sure to unregister your receiver in your fragment, for eg inside onPause()
or onDestroy()
As far as I can see there is no way to register a BroadcastReceiver in a fragment. What do you need that broadcast receiver for? A nice solution is the one mentioned here
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