Android - How to decide whether to run a Service in a separate Process?

pableu picture pableu · Jan 11, 2011 · Viewed 19.9k times · Source

I am working on an Android application that collects sensor data over the course of multiple hours. For that, we have a Service that collects the Sensor Data (e.g. Acceleration, GPS, ..), does some processing and stores them remotely on a server.

Currently, this Service runs in a separate process (using android:service=":background" in the manifest). This complicates the communication between the Activities and the Service, but my predecessors created the Application this way because they thought that separating the Service from the Activities would make it more stable.

I would like some more factual reasons for the effort of running a separate process. What are the advantages? Does it really run more stable? Is the Service less likely to be killed by the OS (to free up resources) if it's in a separate process?

Our Application uses startForeground() and friends to minimize the chance of getting killed by the OS.

The Android docs are not very specific about this, the mostly state that it depends on the Application's purpose ;-)

TL;DR What are objective reasons to put a long-running Service in a separate process (in Android)?

Answer

Eric Levine picture Eric Levine · Jan 11, 2011

The first place to start is by reading through the description of component lifecycles. The take away from that is you really are not guaranteed that a Service or other component will be allowed to run for a long period of time.

However, it does sound like a Service is the right choice for the functionality you describe. This is because you are doing some operations that are not user facing. Going back to the lifecycle description, any time an Activity is not in the foreground, it is essentially a candidate for being killed.

What you should consider doing is using AlarmManager to periodically trigger your Service. You might want also to look at using the WakefulIntent library that @CommonsWare has created.

There is a good article describing multitasking and processes on the Android blog called Multitasking the Android Way that might get at some of the more details regarding processes you are interested in. For example:

A common misunderstanding about Android multitasking is the difference between a process and an application. In Android these are not tightly coupled entities: applications may seem present to the user without an actual process currently running the app; multiple applications may share processes, or one application may make use of multiple processes depending on its needs; the process(es) of an application may be kept around by Android even when that application is not actively doing something.