22

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.

Theo
  • 5,963
  • 3
  • 38
  • 56
  • You could let the host activity handle the broadcast and communicate to the fragment – Neil Aug 29 '12 at 14:31
  • Wouldn't that couple the activity and the fragment ? one of the advantages of fragments are that you can reuse them in other activities. this would reduce your ability to do so. I have the same problem in one of my apps and it's the same with everything that required a context. I ended up using an activity base class that encapsulated the functionality that the fragment needs. does not completely de-couple them but makes maintenance easier. – FunkSoulBrother Sep 03 '14 at 09:18

3 Answers3

30

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

gnorsilva
  • 640
  • 6
  • 11
  • Note that if you use setDebugUnregister(true) for a broadcast receiver then a reference to your fragment will be maintained through the entire lifecycle of the application. This can lead to an apparent memory leak, especially during heavy usage :) – greg7gkb Oct 03 '12 at 15:39
3

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

Community
  • 1
  • 1
user853583
  • 41
  • 5
  • 2
    Per original question, need to listen to the broadcasts sent by the system -- in this case the connectivity broadcasts sent when wifi connects. – Theo Jan 18 '12 at 21:36
1

You can register a broadcast receiver like this : getActivity().registerReceiver(...

Ano
  • 11
  • 1