I would generally recommend doing this in either onCreate()
/onDestroy()
or onStart()
/onStop()
, depending on the semantics that you want:
If your Activity
wants to be interacting with the Service
the 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 onCreate()
/onDestroy()
is probably appropriate. Note that the semantics here is that the entire time your Activity
is running it needs the Service
, so if this Service
is 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.
If your Activity
is only interested in working with the Service
while visible, then onStart()
/onStop()
is appropriate. This means your Activity
will unbind from the Service
when 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 onResume()
and 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 Activity
s 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 (onCreate()
/onDestroy()
, onStart()
/onStop()
, onPause()
/onResume()
) are intended to be the proper pairs for acquiring and then releasing resources (such as binding to Service
s, registering receivers, etc) to ensure that they are correctly acquired prior to being needed and released (and not leaked) when no longer needed.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…