12

Is it better to bind service to FragmentActivity:

bindService(Intent, ServiceConnection, int);

or to Fragment:

getActivity().bindService(Intent, ServiceConnection, int);

What is better practice?

pawegio
  • 1,722
  • 3
  • 17
  • 29

1 Answers1

39

Is it better to bind service to FragmentActivity... or to Fragment

They are the same as you have them written here. getActivity() is not a Fragment -- it is a method that returns the Activity. You cannot call bindService() on a Fragment.

What is better practice?

Neither. Bind to the Application object, obtained via getApplicationContext(), with the ServiceConnection managed by (or perhaps actually being) a retained Fragment.

The reason is configuration changes. A binding is state. You need to maintain that state across configuration changes. While a retained Fragment can hold onto the ServiceConnection, there is an implicit tie in the system between the ServiceConnection and the Context that registered it for a binding. Since activities can be destroyed and recreated on configuration changes, the Activity is not a good choice of Context here. Application, which is system-global, is a safer choice, and one of the few places where choosing Application over another Context is a wise move IMHO.

Here is a blog post of mine, from a time before fragments, that gets into this a bit more. Here is a sample project demonstrating the technique.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Could you please share your opinion on this: http://stackoverflow.com/questions/24309379/bind-service-to-activity-or-fragment – Anjani Jun 19 '14 at 14:44
  • Looking at your demo, it appears you're leaking memory. You keep a reference to a UI element in a retained Fragment, so an old Context will still be referenced even though the configuration may have changed. I would keep the UI elements in a separate Fragment. – mkuech Mar 02 '15 at 16:42
  • @mkuech: That UI element is set to a new value in `onCreateView()`. Hence, after the configuration change, the fragment will not be holding onto the old widget anymore. – CommonsWare Mar 02 '15 at 16:44
  • @CommonsWare Ah, yes, for some reason I had it in my head that `onCreateView()` wasn't called again with a retained fragment. Apologies! – mkuech Mar 02 '15 at 21:12
  • @mkuech: No problem, though you had me scared there for a minute... :-) – CommonsWare Mar 02 '15 at 21:40