We're building up quite a toolkit for asynchronous Android programming. We can perform work off the main thread and update the user interface using HandlerThread
and Handler
. If we're working in the context of a single Activity and want to show progress as we go, we can use AsyncTask
. When we need to load data asynchronously and have it survive across Activity restarts, we can turn to Loaders.
What if we want to perform some background work that must complete even if the user exits the application?
Applications usually don't get killed immediately by the system, so we could just start a background thread and hope that the system doesn't kill our application before the work is completed.
However, this would be quite unreliable, and we can be sure that it won't work well on a large percentage of Android devices in the wild. Luckily, there is a solution available in the form of Service
and its more specialized subclass IntentService
.
In this chapter, we will cover the following topics:
Service
and IntentService
IntentService
PendingIntent
IntentService
IntentService
If the basic unit of a visible application is Activity
, its equivalent unit for non-visible components is Service
. Just like activities, services must be declared in the AndroidManifest
file so that the system is aware of them and can manage them for us.
<service android:name=".MyService"/>
Service
has lifecycle callback methods similar to those of Activity
, which are always invoked on the application's main thread.
Also, just like Activity
, Service
does not automatically entail a separate background thread or process, and performing intensive or blocking operations in a Service
callback method can lead to an Application Not Responding dialog.
However, there are several ways in which services are different to activities, listed as follows:
Service
does not provide a user interfaceService
can remain active even if the application hosting it is not the current foreground application, which means that there can be many services of many apps all active at the same timeIn this chapter, we will focus on the
IntentService
class, a special-purpose subclass of Service
that makes it very easy to implement a task queue to process work on a single background thread.
3.145.96.163