Can anyone explain the Service setForeground method?
I'd like to know more about the setForeground()
method in the Service
class.
Can any one e开发者_如何转开发xplain it in detail?
setForeground()
is deprecated, and I think simply does not work on newer versions of Android. You want the newer startForeground()
instead.
Quoting myself from one of my books:
However, some services will be missed by the user if they mysteriously vanish. For example, the default music player application that ships with Android uses a service for the actual music playback. That way, the user can listen to music while continuing to use their phone for other purposes. The service only stops when the user goes in and presses the stop button in the music player activity. If that service were to be shut down unexpectedly, the user might wonder what is wrong.
Services like this can declare themselves as being part of the "foreground". This will cause their priority to rise and make them less likely to be bumped out of memory. The trade-off is that the service has to maintain a
Notification
, so the user knows that this service is claiming part of the foreground. And, ideally, thatNotification
provides an easy path back to some activity where the user can stop the service.To do this, in
onCreate()
of your service (or wherever else in the service's life it would make sense), callstartForeground()
. This takes aNotification
and a locally-unique integer, just like thenotify()
method onNotificationManager
. It causes theNotification
to appear and moves the service into foreground priority. Later on, you can callstopForeground()
to return to normal priority.
精彩评论