Chapter 5. Queuing Work with IntentService

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:

  • Introducing Service and IntentService
  • Building responsive apps with IntentService
  • Returning results with PendingIntent
  • Posting results as system notifications
  • Applications of IntentService
  • Reporting progress from IntentService

Introducing Service and 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:

  • A Service does not provide a user interface
  • There can be many services active at the same time within an application
  • A Service 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 time
  • Because the system is aware of services running within a process, it can avoid killing those processes unless absolutely necessary, allowing the background work to continue

In 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.96.163