Bind service to FragmentActivity or Fragment?

Is it better to bind service to FragmentActivity:

bindService(Intent, ServiceConnection, int);

or to Fragment:

  • Sliding layer activity animation android
  • Set Value to Enum - Java
  • Android Toast equivalent in iOS
  • Android ListView: Header/Footer that fills the remaining space on screen
  • Add space to the end of the RecyclerView
  • android: AbsListView.OnScrollListener SCROLL_STATE_IDLE is not called after SCROLL_STATE_TOUCH_SCROLL (Version 2.1)
  • getActivity().bindService(Intent, ServiceConnection, int);

    What is better practice?

    Related posts:

    JDK 7 with Android SDK R13 in windows 7
    Can't add XStream file dependency to Android Studio project
    Bad notification posted from package
    What exactly is a Context in Java?
    Android Activity Transition Animation
    stop loading in webViewClient
  • CollapsingToolbarLayout with tablayout & image as collapsing with sticky toolbar
  • How to run Matlab code on an Android device?
  • How to integrate Scala into core Android platform?
  • Is there any way to automatically log the method name in Android?
  • PhoneGap readAsDataURL
  • What is the difference between setFocusable and setFocusableInTouchMode?
  • One Solution collect form web for “Bind service to FragmentActivity or Fragment?”

    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.

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.