Listing 98 Moving a Service back to the background

Available for download on // Move to the background and remove the Notification stopForeground(true);

Prior to Android 2.0 it was possible to set a Service to the foreground using the setForeground method. This method has now been deprecated and will result in a no-op, effectively doing nothing.


To ensure that your applications remain responsive, it's good practice to move all slow, time-consuming operations off the main application thread and onto a child thread.

All Android application components —including Activities, Services, and Broadcast Receivers —start on the main application thread. As a result, time-consuming processing in any component will block all other components including Services and the visible Activity.

Android offers two alternatives for backgrounding your processing. The AsyncTask class lets you define an operation to be performed in the background, then provides event handlers you can use to monitor progress and post the results on the GUI thread.

Alternatively, you can implement your own Threads and use the Handler class to synchronize with the GUI thread before updating the UI. Both techniques are described in this section.

Using background threads is vital for avoiding the ''Force Close'' dialog box described in Chapter 2. In Android, Activities that don't respond to an input event (such as a key press) within five seconds, and Broadcast Receivers that don't complete theionReceive handlers within 10 seconds, are considered unresponsive.

Not only do you want to avoid this scenario, you don't want to even get close. Use background threads for all time-consuming processing, including file operations, network lookups, database transactions, and complex calculations.

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