34,333
edits
Changes
→The Anatomy of a Service
In terms of implementing the communication between a client and a bound service, the recommended technique depends on whether the client and service reside in the same or different processes and whether or not the service is private to the client. Local communication can be achieved by extending the Binder class and returning an instance from the onBind() method. Interprocess communication, on the other hand, requires Messenger and Handler implementation. Details of both of these approaches will be covered in later chapters.
== The The Anatomy of a Service ==
A service must, as has already been mentioned, be created as a subclass of the Android Service class (more specifically android.app.Service) or a sub-class thereof (such as android.app.IntentService). As part of the subclassing procedure, one or more of the following superclass callback methods must be overridden, depending on the exact nature of the service being created:
* '''onStartCommand()''' – This is the method that is called when the service is started by another component via a call to the startService() method. This method does not need to be implemented for bound services.
* '''onBind()''' – Called when a component binds to the service via a call to the bindService() method. When implementing a bound service, this method must return an IBinder object facilitating communication with the client. In the case of started services, this method must be implemented to return a NULL value.
* '''onCreate()''' – Intended as a location to perform initialization tasks, this method is called immediately before the call to either onStartCommand() or the first call to the onBind() method.
* '''onDestroy() ''' – Called when the service is being destroyed.
* '''onHandleIntent()''' – Applies only to IntentService subclasses. This method is called to handle the processing for the service. It is executed in a separate thread from the main application.
Note that the IntentService class includes its own implementations of the onStartCommand() and onBind() callback methods so these do not need to be implemented in subclasses.