A Service is an application component representing either an application’s desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Services can be started with
If someone calls
Context.startService() then the system will retrieve the service (creating it and calling its
onCreate() method if needed) and then call its
onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until
stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their
stopSelf(int) method to ensure the service is not stopped until started intents have been processed.
Clients can also use
Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling
onCreate() while doing so), but does not call onStartCommand(). The client will receive the
IBinder object that the service returns from its
onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service’s IBinder). Usually the IBinder returned is for a complex interface that has beenwritten in aidl.