开发者

What happens to a service started by BOOT_COMPLETE after system kills it?

What happens to a service started by BOOT_COMPLETE after system kills it for memo开发者_StackOverflowry?

Will it ever be restarted without rebooting the phone? Is it possible to restart it somehow?

What is the best practice to avoid as much as possible an important service from being killed?


Will it ever be restarted without rebooting the phone?

Possibly. If it truly was because "system kills it for memory", and you return an appropriate value from onStartCommand() (e.g., START_STICKY), it should be restarted at some point in the future. If the service was killed due to user action (e.g., Force Stop in the Manage Services screen in Settings), it will not be restarted.

What is the best practice to avoid as much as possible an important service from being killed?

First, design your application to not rely on an everlasting service like this. 99.44% of Android applications do not need a service that runs continuously, let alone one that starts doing so at boot time. Android device users hate developers who think that their apps are sooooooooooooo important that they have services running all the time -- that's why we have task killers, Force Stop, and Android killing services due to old age. For example, if you are checking for new email every 15 minutes, use AlarmManager and an IntentService, not a service that runs forever.

If you can demonstrate -- to me and to your users -- that yours is among the 0.56% of applications that really do need a service that starts at boot time and runs forever, you can use startForeground(). This will indicate to the OS that your service is part of the foreground user experience. You will have to display a Notification, ideally to allow the user to shut down your service cleanly if and when the user no longer feels that it is justified.


If you need to restart the service then you should use AlarmManager to check up on the service in a separate BroadcastReceiver, but nominally when a service is killed by the system for memory it will not get automatically restarted.


You may want to take a look at START_STICKY


Use the AlarmManager to periodically send an Intent-- receive the intent and make sure your service is running.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜