Friday, December 10, 2010

Android Service Lifecycle

The Android Service Lifecycle will be similar to that of an Activity Lifecycle except a few important details. We will discuss those here.

onCreate and onStart differences: Services can be started when a client calls the Context.startService(Intent) method. If the service isn't already running, Android starts it and calls its onCreate method followed by the onStart method. If the service is already running, its onStart method is invoked again with the new intent. So it's quite possible and normal for a service's onStart method to be called repeatedly in a single run of the service.

onResume, onPause, and onStop are not needed: Recall that a service generally has no user interface, so there isn't any need for the onPause, onResume, or onStop methods. Whenever a service is running, it is always in the background.

onBind: If a client needs a persistent connection to a service, it can call the Context.bindService method. This creates the service if it is not running, and calls onCreate but not onStart. Instead, the onBind method is called with the client's intent, and it returns an IBind object that the client can use to make further calls to the service. It's quite normal for a service to have clients starting it and clients bound to it at the same time.

onDestroy: As with an activity, the onDestroy method is called when the service is about to be terminated. Android will terminate a service when there are no more clients starting or bound to it. As with activities, Android may also terminate a service when memory is getting low. If that happens, Android will attempt to restart the service when the memory pressure passes, so if your service needs to store persistent information for that restart, it's best to do so in the onStart method.

No comments:

Post a Comment