Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Broadcast Receiver in Fragment

Tags:

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.

like image 612
Theo Avatar asked Jan 05 '12 03:01

Theo


2 Answers

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()

like image 145
gnorsilva Avatar answered Sep 23 '22 05:09

gnorsilva


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

like image 44
user853583 Avatar answered Sep 23 '22 05:09

user853583