Android Service全解(三)之 Foreground Service(怎么让Android程序一直后台运行,像QQ一样不被杀死?)

952 阅读3分钟

文章来源:www.juwends.com/tech/androi…

Foreground Service(意译为前台服务)并不完全像其意译的意思那样是工作在前台的Service,因为Service实际上始终是工作在后台的。由于Service工作在后台的原因,使用者并不知道它在运行,有时候开发者需要使用者知道某个Service在运行时,就需要设计一种方案来解决这个问题,Foreground Service就出现了。Foreground Service说简单点其实就是在Service开启的时候使用通知(Notification),这也是Android官方推荐的方式,或者一些其它的方式(甚至可以是Activity,但使用Activity是基本没有必要的)来告知用户这个Service正在运行。\

所以,要掌握Foreground Service的用法,就不得不先了解一下通知的使用方法。关于通知的使用方法可以参看我的另一篇文章《Android通知的使用及简单二次封装》。在文章里,我简单封装了一下Android的通知接口,可以很方便的使用。

接着,只要在程序开启了Service,则使用一个“正在运行”的通知表明服务正在运行就可以了,也就是在Service的onCreate()回调或者onStart()/onStartCommand()(区别详见《Android Service全解(一)之 startService》)回调中即可。虽然通知并不是一定需要的,或者说故意不提示用户有服务正在运行(稍稍流氓一点的程序就会这样),但是某些应用商场的应用审核就把通知提示做为了审核项目的。为了在Service周期(Life Cycle)结束的时候通知也能自动消失,所以需要在Service的onDestroy()回调里面写上取消通知的代码。以上就是配合通知自己实现的Foreground Service了。

当然,除了自己处理通知的方法外,Google在Android 2.0(SDK level 5)以上的SDK提供了一个直接而简单的方法。直接使用Service.startForeground()和Service.stopForeground()进行处理(注意,这两个方法是Service类的)。我封装的通知接口genNotification()(详见《Android通知的使用及简单二次封装》)在这里可以提供实例通知对象的支持。下面看下Google提供的两个接口:

1234567891011121314151617181920212223242526272829/**``  * 让service成为Foreground Service,并且产生一个“正在运行”``  * 的通知。默认情况下,service是后台的,这意味着service在系统``  * 回收内存(比如在浏览器里显示大图片)的时候可以被毫无顾忌的``  * kill掉。如果你比较在意这个service的挂掉,比如像后台音乐播放``  * 器这种突然挂了会影响用户的情况,就可以使用Foreground``  * Service来提示用户。``  *``  * 参数``  * id   The identifier for this notification as per``  *        NotificationManager.notify(int, Notification).``  * notification The Notification to be displayed.``  */``public final void startForeground (``                int id, Notification notification)  /**``  * 去掉service的foreground属性,允许在低内存时被kill掉``  *``  * Parameters``  * removeNotification  If true, the notification previously``  *                     provided to startForeground(``  *                                       int, Notification)``  *                     will be removed. Otherwise it will``  *                     remain until a later call removes``  *                     it (or the service is destroyed).``  */``public final void stopForeground (boolean removeNotification)

使用startForeground()之后,给出的Notification对象会发布,使用stopForeground()之后,通知会被撤销,当Service销毁(比如stopService()被调用)之后,通知也会被撤销。stopForeground()仅仅只是去掉service的foreground属性,并不会让service停止。

对于SDK 2.0之前的SDK使用这两个接口,Google也提供了另外的方法,并且使用到了反射机制,可以自行参考Android的官方文档。

使用Android SDK 2.0以上SDK的foreground service的完整工程包可以到Juwend’s Apps – Demos – Foreground Service下载学习使用。

Android Service全解(三)之 Foreground Service —— Juwend 
Juwend’s – http://www.juwends.com
笔者水平有限,若有错漏,欢迎指正,欢迎转载以及CV操作,但希注明出处,谢谢!

此条目由Derek发表在Android分类目录,并贴了AndroidForegroundService标签。将固定链接加入收藏夹。\