How does the ForeGround Service be worthy enough to Stay alive in Background, and normal Service not…?

Let’s explore the magic behind it.

Aryan Dhankar
WalkInTheCode
6 min readAug 16, 2020

--

If we listen, what official android doc has to say over the topic.

Foreground Service: A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a Notification. Foreground services continue running even when the user isn’t interacting with the app.

Background Service: A background service performs an operation that isn’t directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service.

Note:- If your app targets API level 26 or higher, the system imposes restrictions on running background services when the app itself isn’t in the foreground

So from the above explanation, we could conclude, that if our app is targets above and equal to API level 26 and if we want to do some work when the user is not interacting with the app, then we have gone for ForeGround Services.

So what different we have to create a foreground service. No don’t worry too much, we just have to add this…

So just by adding
startForeground(ONGOING_NOTIFICATION_ID, notification), android allows us to run a service that exists even after our app got killed.

Now I will explain how does StartForeground, makes Service worthy enough to run in the background.

Here I am going to relate this topic with the story of Mjolnir(hammer of thor)

Everyone is a simple person, but if any ordinary person is worthy to wield the hammer, then posses all the powers of thor.

Similarly, every service is ordinary service, but if the service is worthy, to lie in the Foreground Process, then it can run in the background even if the app kills.

So to understand, what does it mean to lie in the Foreground Process, we have to understand what is a process and its lifecycle

Processes

By default, all components of the same application run in the same process, and most applications should not change this. However, if you find that you need to control which process a certain component belongs to, you can do so in the manifest file.

The manifest entry for each type of component element — <activity>, <service>, <receiver>, and <provider>—supports an android:process the attribute that can specify a process in which that component should run. You can set this attribute so that each component runs in its own process, or so that some components share a process while others do not. You can also set android:process so that components of different applications run in the same process—provided that the applications share the same Linux user ID and are signed with the same certificates.

The <application> element also supports an android:process attribute, to set a default value that applies to all components.

Android might decide to shut down a process at some point when memory is low and required by other processes that are more immediately serving the user. Application components running in the process that’s killed are consequently destroyed. The decision of whether to terminate a process, therefore, depends on the state of the components running in that process. The rules used to decide which processes to terminate is discussed below.

Note:- If a person wields the hammer, that doesn’t he/she can’t get killed, like cap after wielding Mjolnir he was to able to stand against Thanos and fight with him up to some level, but in the end, he failed and his shield also got destroyed. Similarly, if a Service belongs to the Foreground process, that means it can run in the background even after the app gets killed, but if android wants to recover memory then service would be terminated by the os.

Just like how the cap is worthy?

So to understand which process got killed first and whose chance is last, we have to understand the process lifecycle…

Process lifecycle

The Android system tries to maintain an application process for as long as possible but eventually needs to remove old processes to reclaim memory for new or more important processes. To determine which processes to keep and which to kill, the system places each process into an “importance hierarchy” based on the components running in the process and the state of those components. Processes with the lowest importance are eliminated first, then those with the next lowest importance, and so on, as necessary to recover system resources.

There are five levels in the importance hierarchy. The following list presents the different types of processes in order of importance (the first process is most important and is killed last):

Foreground process

A process that is required for what the user is currently doing. A process is considered to be in the foreground if any of the following conditions are true:

Visible process

A process that doesn’t have any foreground components, but still can affect what the user sees on the screen. A process is considered to be visible if either of the following conditions is true:

  • It hosts an Activity that is not in the foreground but is still visible to the user (its onPause() method has been called). This might occur, for example, if the foreground activity started a dialog, which allows the previous activity to be seen behind it.
  • It hosts a Service that's bound to a visible (or foreground) activity.

A visible process is considered extremely important and will not be killed unless doing so is required to keep all foreground processes running.

Service process

A process that is running a service that has been started with the startService() method and does not fall into either of the two higher categories. Although service processes are not directly tied to anything the user sees, they are generally doing things that the user cares about (such as playing music in the background or downloading data on the network), so the system keeps them running unless there's not enough memory to retain them along with all foreground and visible processes.

Background process

A process holding an activity that’s not currently visible to the user (the activity’s onStop() the method has been called). These processes have no direct impact on the user experience, and the system can kill them at any time to reclaim memory for a foreground, visible, or service process. Usually, there are many background processes running, so they are kept in an LRU (least recently used) list to ensure that the process with the activity that was most recently seen by the user is the last to be killed. If an activity implements its lifecycle methods correctly, and saves its current state, killing its process will not have a visible effect on the user experience, because when the user navigates back to the activity, the activity restores all of its visible state. See the Activities document for information about saving and restoring state.

Empty process

A process that doesn’t hold any active application components. The only reason to keep this kind of process alive is for caching purposes, to improve startup time the next time a component needs to run in it. The system often kills these processes in order to balance overall system resources between process caches and the underlying kernel caches.

Conclusion:

Foreground Services lies in the first process i.e in Foreground Process. This means they are killed only as a last resort — if memory is so low that they cannot all continue to run.

Key Points to Remember before using Foreground Service:

  1. If your work is non-deferrable, then go for ForeGround Services.
  2. Don’t do heavy operations on Foreground Service. If you want to do some heavy operation create sperate threads to get your work done.
  3. The options you can use to create a thread (or threads ) in Foreground Service are AsyncTask, Threadpool, Coroutines, Rxjava.
  4. ForeGround Service can last long in action even if our app is not live. But if the OS is low on memory then ForeGround Service can also get killed.
  5. We don’t always have to choose ForeGround Service to do background tasks, we have lots of other options too, but we have to understand which one is best for what conditions.

References:

  1. Processes and threads
  2. Foreground Services

--

--