[1].However, if you want the service to send a result back, then the client that starts the service can
create a PendingIntent
for
a broadcast (with getBroadcast()
)
and deliver it to the service in the Intent
that
starts the service. The service can then use the broadcast to deliver a result.
[2].Multiple
requests to start the service result in multiple corresponding calls to the service's onStartCommand()
.
However, only one request to stop the service (with stopSelf()
or stopService()
)
is required to stop it.
[3].For
example, a music player that plays music from a service should be set to run in the foreground, because the user is explicitly aware of its operation. To
request that your service run in the foreground, call startForeground()
.
This method takes two parameters: an integer that uniquely identifies the notification and the Notification
for
the status bar.
The
integer ID you give to startForeground()
must
not be 0.
[4].To
remove the service from the foreground, call stopForeground()
.
This method takes a boolean, indicating whether to remove the status bar notification as well. This method does not stop
the service. However, if you stop the service while it's still running in the foreground, then the notification is also removed.
[5].These
two paths are not entirely separate. That is, you can bind to a service that was already started with startService()
.
For example, a background music service could be started by calling startService()
with
an Intent
that
identifies the music to play. Later, possibly when the user wants to exercise some control over the player or get information about the current song, an activity can bind to the service by calling bindService()
.
In cases like this, stopService()
or stopSelf()
does
not actually stop the service until all clients unbind.
[6].
[7].If
the service is started, the active lifetime ends the same time that the entire lifetime ends (the service is still active even after onStartCommand()
returns).
If the service is bound, the active lifetime ends when onUnbind()
returns.