2

I have code in Activity that uses getApplication().bindService() or just bindService(). Is one preferable over another. Considering that Activity has lifecycles, under what scenario would an Application context be used to start/bind to a service.

Brijesh Kumar
  • 1,685
  • 2
  • 17
  • 28
Srinivasan
  • 399
  • 1
  • 2
  • 9
  • Check this answer [link](http://stackoverflow.com/questions/6446221/get-context-in-a-service) , it has some clarification about the 2 concepts. – Omar BISTAMI Oct 13 '16 at 14:48

1 Answers1

6

For binding to a service from an activity, use the Application context (getApplication()). That is because the binding itself represents state that needs to be handled as part of configuration change processing (e.g., via onRetainNonConfigurationInstance()). One activity instance might bind, but then you might not unbind until after a configuration change. Using the Activity as the Context for bindService() might introduce a memory leak (new activity holds an indirect reference back to the original activity that bound to the service).

However, starting a service from an activity involves no framework-imposed state in the activity. Hence, starting the service using startService() on the activity itself should be fine.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 1
    honestly, i never saw any `Activity` that calls `bindService` on the `Application` context, `bind` / `unbind` requests should be paired so there is no chance for a leak... – pskink Oct 13 '16 at 15:22
  • @pskink: If you unbind from the old activity, the service may shut down before you get a chance to bind again from the new activity, as part of a configuration change. Now, if you're sure that something else is keeping the service running (e.g., it's both bound and started), perhaps that is not an issue. – CommonsWare Oct 13 '16 at 15:29