解决android中service被kill后重启异常终止的问题

今天解决了一个android上service异常终止的bug。情况是这样的,原来这个应用在手机上上并未出现异常终止的情况,现移到TV上,经常就意外终止了,看了下log, 原来在异常终止前有这么一条

No longer want my_service_name (pid 1617): hidden #6)

显然系统把我的service给kill了,然后又自动重启,调用onStartCommand时,出错了,因为我在onStartCommand里用到了intent参数,这个参数在最初我启动Service时是传入了的,但系统杀掉service后再重启时,这个intent成null了,所以报了空指针的错误。

解决:

步骤一、用startForeground()启动服务。

官网文档中有:

A foreground service holds a higher level of importance within the system—the system will almost never kill the service, because it is of immediate importance to the user.

也就是说一个foreground service几乎不会被系统kill掉。

步骤二、Service启动后返回START_REDELIVER_INTENT标识(原来用了START_STICKY)。

根据官方文档对于START_REDELIVER_INTENT的说明:

if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then it will be scheduled for
a restart and the last delivered Intent re-delivered to it again via onStartCommand(Intent, int, int).

这样Service被系统kill了以后,再重启时系统会重新把最后一次的Intent传进来。

posted @ 2013-04-08 16:42  shtzsp  阅读(721)  评论(0编辑  收藏  举报