Prioritizing Background Services

As you learned in Chapter 3, Android uses a dynamic approach to manage resources that can result in your applications, Activities, and Services being terminated by the run time with little or no warning.

When calculating which applications and application components should be killed, Android assigns running Services the second-highest priority. Only active, foreground Activities are considered a higher priority in terms of system resources.

In extreme cases, in which your Service is interacting directly with the user, it may be appropriate to lift its priority to the equivalent of a foreground Activity's. You do this by setting your Service to run in the foreground using the startForeground method.

It is expected that Services running in the foreground will be interacting directly with the user (for example, by playing music). Because of this, the user should always be aware of a foreground Service. To ensure this, calls to startForeground must specify an ongoing Notification (described in more detail later in this chapter), as shown in Listing 9-7. This notification will continue for at least as long as the Service is running in the foreground.

By moving your Service to the foreground you effectively make it impossible for the run time to kill in order to free resources. Having multiple unkillable Services running simultaneously can make it extremely difficult for the system to recover from resource-starved situations.

Use this technique only if it is necessary in order for your Service to function properly, and even then keep the Service in the foreground only as long as absolutely necessary.

Was this article helpful?

0 0
Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide

Post a comment