OK, so there is a solid justification for why Android kills background services all the time. It's a mobile OS, so performance and battery life are a big concern. But that doesn't stop a lot of people from asking, "How can I keep my services from getting killed?"
The general consensus seems to be that , which is mostly true. But there are a few options available.
If you're a system developer (like I am at the moment), you're really in luck. The
- It only applies to system apps (ie apps in /system/app). The flag is ignored for apps in /data/app. So as I said, this is only useful if you're developing an Android system, or maybe if you're manually installing an app on a rooted phone. Marketplace apps are right out of luck.
- Persistence only applies to services in the default application process. If any
tag includes an "android:process" attribute that causes it to run in a separate process, that process will NOT be persistent.
> adb shell dumpsys activity | grep PERS
PERS #17: adj=sys /F ae27b4d0 340:system/1000 (fixed)
Obviously this should be used with extreme care. Any non-critical tasks in your app should be moved to a separate service with the "android:process" attribute set, so that those particular bits are not persistent.
For Marketplace developers...sorry, but your services still have a bullseye on them. It's not all bad though; there are 3 solid (and well documented) solutions that should suffice:
- If you need to perform a task repeatedly at set intervals (ie polling for data), set anAlarmManager to spawn your service as needed.
- If you really need to remain running constantly (ie to maintain music playback or something else with zero interruptions), call startForeground(). In newer Android flavors, you'll have to provide a Notification to alert the user that your service is running...but that's not much to ask.
- If you need to remain running constantly but can endure short interruptions, just return START_STICKY from your onStartCommand() method. If Android does kill your service, it will be restarted ASAP (with calls to onCreate and onStartCommand). In my experience it's rarely more than a minute of downtime, but this could vary.
Note: if you are writing an older app that uses onStart instead of onStartCommand (or if you return the START_STICKY_COMPATIBILITY flag instead), your service will be restarted with a call to onCreate only (onStart will not be called for a restart).