The New Features in Android Background Tasks

Kayvan Kaseb
Software Development
8 min readOct 24, 2021
The picture is provided by Unsplash

Basically, running tasks in the background consumes an Android device’s limited resources, such as RAM and battery life. This might leads to an inappropriate user experience. Therefore, it is essential to make balance between the needs of an Android app and the best user experience approach by removing unnecessary distractions. To enhance the productivity of background tasks, Google has announced some efficient changes to starting and running foreground services from the background. This article aims to discuss some advanced best practices for running Android background tasks.

Introduction and Overview

As you know, Android apps have always tried to obtain the users’ attention. The attention requested needs to add value to the user, and not just only be a distraction. Besides, just as the user has a limited attention span, the mobile phone has a limited amount of resources that can be consumed before it runs out of battery. With the number of exciting applications growing in the Play Store, it is essential to make balance between the needs of all these Android applications and the best user experience approach by eliminating unnecessary distractions. Initially, processing data in the background is a significant part of implementing an Android app that is both responsive for your users, as well as a proper issue on the Android platform. To be running in the background, there are two situations for an Android app: First, none of the app’s activities are visible to the user now. Second, the app is not running any foreground services, which started when an activity from the app was visible to the user. Eventually, in other conditions, the app is considered to be running in the foreground indeed.

In general, any task that takes more than a few milliseconds should be delegated to a background thread.

In fact, Android 12 has announced some efficient changes to starting and running foreground services from the background. Studying these changes plays an important role for Android developers to perform background works in a user and resource-friendly way.

Background Tasks

Fundamentally, background tasks can be classified into four categories:

  1. Immediate 2. Exact 3. Expedited 4. Deferred

The following decision tree helps you decide which category is the best choice for your background tasks.

The picture is provided by Google documents

Foreground Services

As far as the user is concerned, an app is in the foreground when it is showing UI or accomplishing user-perceptible work. When an app is performing work in the background, the user should have no idea about this issue at all. In some situations, such as navigation or music playback, the user should be aware and associate the notification with something they perceive as foreground. In short, Foreground services have to show a Notification. Foreground services also continue running even when the user is not interacting with the application. However, an app that display the notification, which is not adding any value to the user belongs in the background category. Foreground services are used to convey to the user that an app is continuing to support them a service that they might interact with. They allow the user to multitask issues, like listening to music while browsing the web. In addition, they allow apps to complete user-initiated tasks at a high priority, such as sending out a large-attachment email you just composed or finishing up the HDR processing for a series of photos that you just took. Foreground services are not meant for tasks that are not urgent or for work that the user does not need to be aware of. They also should not be used as a way for an app to stay resident in memory for the incorrect reasons.

Foreground services perform operations that are noticeable to the user. Foreground services show a status bar notification, so that users are actively aware that your app is performing a task in the foreground and is consuming system resources. The notification cannot be dismissed unless the service is either stopped or removed from the foreground.

Therefore, to sum up this section, Foreground Services are appropriate choice for: 1. Multitasking 2. Completing a user action. Additionally, Foreground Services are not appropriate choice for: 1. Background work that is not urgent. 2. Work that the user does not require to know about. 3. A way for an Android application to stay in memory.

To understand this matter effectively, there are some examples of apps that would use foreground services as follows: Firstly, a music player app that plays music in a foreground service. So, the notification might display the current song that is being played. Secondly, a fitness app that records a user’s run in a foreground service (after receiving permission). The notification probably indicates the distance that the user has walked during the current fitness session.

Disadvantages of Using Foreground Services

Even though Foreground Services are convenient and reliable in practice, they are not user-friendly when the user cannot discard them. As a result, they either turn off notifications for the app or uninstall it. Moreover, they can be distracting particularly when their notification pops up immediately in your status bar and then disappears before you even get a chance to observe the process precisely.

Foreground services can be able to consume valuable resources when used incorrectly, such as draining the battery and holding up precious memory. Finally, since the app decides when to invoke a foreground service and how long it runs, the OS cannot prioritize tasks efficiently.

To address these problematic consequences, Google has investigated that a user experiences anywhere between 200 and over 500 foreground service notifications per day. Thus, they found that almost half of foreground services are started from the background when the user is not interacting with the Android app and is not expecting the app to be active. Afterwards, they measured the duration of foreground service sessions. Almost, 70% of foreground services run for less than 10 seconds. They also noticed that most sessions are less than two minutes in duration. Accordingly, Google has proposed some solutions and changes for these drawbacks as follows:

  1. Restricting launch of foreground services from the background.

2. Supporting preferable tools for reliable background tasks.

The new changes in Android 12

First of all, Google has limited the situations in which foreground services can be started from the background. This is applicable to apps targeting API level 31 or newer. We also know that there are valid use cases that justified the use of foreground services. However, there are a few exceptions; different types of services always display a notification immediately.

If an app tries to start a foreground service while the app is running in the background, and the foreground service doesn’t satisfy one of the exceptional cases, the system throws a ForegroundServiceStartNotAllowedException.

Secondly, to deal with the sharp foreground services that distract the user, in some cases, Google has deferred showing the foreground service notification for 10 seconds. If the service is done by then, the notification is not shown (Hidden for the first 10 seconds). Any longer than this period of time, the notification will be showed to the user. The app can override this behavior by specifying its preference to defer or display immediately.

Introducing Expedited Jobs

For all other short background tasks that require to be executed as soon as possible, Google has introduced expedited jobs. These are low-latency jobs that can be invoked from either foreground or background to be executed immediately. The OS will do its best to run them quickly, but in order to give that same low latency to other contending expedited jobs, the maximum allocated job duration will be shorter. Therefore, these apps can get a chance to execute high-priority background tasks as soon as possible.

WorkManager introduces a new WorkRequest.Builder.setExpedited(...) API to help with Foreground Service restrictions in Android 12.

Furthermore, expedited jobs can be run during Doze and Battery Saver modes, similar to foreground services. This addresses the reliability concerns.

If a user leaves a device unplugged and stationary for a period of time, with the screen off, the device enters Doze mode. In Doze mode, the system attempts to conserve battery by restricting apps’ access to network and CPU-intensive services. It also prevents apps from accessing the network and defers their jobs, syncs, and standard alarms.

With the OS taking over scheduling and execution, expedited jobs are also subject to App Standby Buckets. This means that less frequently-used apps will get fewer opportunities to run these jobs from the background.

Android 9 (API level 28) and higher support App Standby Buckets. App Standby Buckets help the system prioritize apps’ requests for resources based on how recently and how frequently the apps are used. Based on app usage patterns, each app is placed in one of five priority buckets. The system limits the device resources available to each app based on which bucket the app is in.

The expedited job API is available through WorkManager since version 2.7. Google has recommended using WorkManager for expedited jobs wherever possible. Basically, the library is unbundled from the OS, which makes it faster to supply updates and easier for you to react to future changes without tackling various Android versions.

WorkManager is an API that makes it easy to schedule reliable, asynchronous tasks that are expected to run even if the app exits or the device restarts. The WorkManager API is a suitable and recommended replacement for all previous WorkManager incorporates the features of its predecessors in a modern, consistent API that works back to API level 14 while also being conscious of battery life

The right time for starting a foreground Service

First, while your app is visible to the user, you can be able to start a foreground service, as your app is in the foreground already. This is the same as the background activity restriction that has been introduced in Android 10. This foreground service can remain running when your Android app is put in the background afterwards. Second, you can also start a foreground service on other user interactions, such as a tap on the notification or launch our widget. In other words, you can start the foreground service as a direct response to a user interaction with your app. Finally, some special system broadcasts and callbacks have been exempted, as an example, the broadcasts BOOT_COMPLETED and MY_PACKAGE_REPLACED will allow you to start a foreground service. There are also exempted callbacks, such as geofencing callbacks and high-priority FCM messages are still allowed to start a foreground service.

Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention. For use cases such as instant messaging, a message can transfer a payload of up to 4000 bytes to a client app.

As a matter of fact, for foreground service that the user starts from the UI, a foreground service is still the best solution. For instance, Navigation, Music Players, and Fitness trackers should still use a foreground service in order to continue the process in the background. When an email app requires to send a large attachment, starting a foreground service from the UI is also the best approach. In contrast, for most of background work, Work Manager has been suggested and recommended. If your work is time sensitive and will take less than a few minutes, an Expedited Job could probably useful. If not, consider using a non-expedited job that allows the system to schedule it effectively.

In conclusion

As it is obvious, it is vital to make balance between the needs of an Android app and the best user experience approach by removing unnecessary distractions. To improve the efficiency of background tasks, Google has introduced some effective changes to starting and running foreground services from the background. This essay considered some advanced best practices for running Android background tasks based on Google documents and resources.

--

--

Kayvan Kaseb
Software Development

Senior Android Developer, Technical Writer, Researcher, Artist, Founder of PURE SOFTWARE YAZILIM LİMİTED ŞİRKETİ https://www.linkedin.com/in/kayvan-kaseb