开发者

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, that Notification 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), call startForeground(). This takes a Notification and a locally-unique integer, just like the notify() method on NotificationManager. It causes the Notification to appear and moves the service into foreground priority. Later on, you can call stopForeground() to return to normal priority.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜