I want to know what is the best place in an Activity to bind to a service?
I saw examples doing it in
onResume() and also in
onCreate(). I was asking myself if it is not a problem putting it into
onCreate(), because in
onPause() I will do a unbind to the service, so I don’t get a serviceConnectionLeak, if I leave the activity. Now if I press the Home Button and then switch to the Home Screen, the Activity will unbind from the service, when I go back to the Activity from the Task Manager, then
onCreate() will not be called and if the code is trying to access a function from the service I will get a NullPointerException. If I bind and unbind only in
onPause() I don’t have this problem. Am i right?
I would generally recommend doing this in either
onStop(), depending on the semantics that you want:
Activitywants to be interacting with the
Servicethe entire time it is running (for example maybe it can retrieve some data from a network for you and will return the data when ready and you want to allow this to happen while in the background so if the user returns you will have the data ready), then
onDestroy()is probably appropriate. Note that the semantics here is that the entire time your
Activityis running it needs the
Service, so if this
Serviceis running in another process then you have increased the weight of it and made it more likely for it to be killed while in the background.
Activityis only interested in working with the
Servicewhile visible, then
onStop()is appropriate. This means your
Activitywill unbind from the
Servicewhen the user leaves it (and it is no longer visible) and connect back up the next time the return and it is re-started and resumed.
I generally wouldn’t recommend doing bind/unbind in
onPause(). These generally won’t decrease significantly the amount you use the
Service (and thus your overhead), and in fact, because a pause and resume happens at every activity transition, this is a code path you want to keep as lightweight as possible. Doing it here can have other unexpected negative consequences: for example if multiple
Activitys in your app bind to the same
Service, when there is a transition between two of those activities the
Service may also get destroyed and recreated as the current
Activity is paused before the next one is resumed.
Also these pairs (
onResume()) are intended to be the proper pairs for acquiring and then releasing resources (such as binding to
Services, registering receivers, etc) to ensure that they are correctly acquired prior to being needed and released (and not leaked) when no longer needed.
What you say is correct. In most cases you will want to register in
onResume() and unregister in
onPause(). If you use
onCreate() and on
onDestroy() you will still be registering for updates when you are paused, which is being a bad citizen. If you register in
onCreate() and unregister in
onPause(), when you resume the task the registration will be gone, which is almost certainly not what you want.