Reputation: 6083
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.
Upvotes: 22
Views: 21239
Reputation: 11
You can register a broadcast receiver like this : getActivity().registerReceiver(...
Upvotes: 1
Reputation: 640
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()
Upvotes: 30
Reputation: 41
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
Upvotes: 3