Android: keeping a background service alive (preventing process death)

Jon Willis picture Jon Willis · Oct 4, 2010 · Viewed 102.5k times · Source

I have a service that is defined as:

public class SleepAccelerometerService extends Service implements SensorEventListener

Essentially, I am making an app that monitors accelerometer activity for various reasons while the user sleeps with his or her phone/device on the bed. This is a long-running service that MUST NOT be killed during the night. Depending on how many background apps and periodic processes occur during the night, android sometimes kills off my process, thereby ending my service. Example:

10-04 03:27:41.673: INFO/ActivityManager(1269): Process com.androsz.electricsleep (pid 16223) has died.
10-04 03:27:41.681: INFO/WindowManager(1269): WIN DEATH: Window{45509f98 com.androsz.electricsleep/com.androsz.electricsleep.ui.SleepActivity paused=false}

I do not want to force the user to have 'SleepActivity' or some other activity in my app as the foreground. I can't have my service run periodically, because it is constantly intercepting onSensorChanged.

Any tips? source code is here: http://code.google.com/p/electricsleep/

Answer

Dave Webb picture Dave Webb · Oct 4, 2010

For Android 2.0 or later you can use the startForeground() method to start your Service in the foreground.

The documentation says the following:

A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)

The is primarily intended for when killing the service would be disruptive to the user, e.g. killing a music player service would stop music playing.

You'll need to supply a Notification to the method which is displayed in the Notifications Bar in the Ongoing section.