Reader small image

You're reading from  Asynchronous Android Programming - Second Edition

Product typeBook
Published inJul 2016
Reading LevelBeginner
PublisherPackt
ISBN-139781785883248
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Steve Liles
Steve Liles
author image
Steve Liles

Steve Liles is a self-confessed geek and has been an Android fan since the launch day of the G1. When he isn't at work building publishing systems and apps for newspapers and magazines, you'll find him tinkering with his own apps, building 3D printers, or playing RTS games. He is currently working with a start-up to build an advertising system that links the print and digital worlds using computer vision on Android and iOS devices.
Read more about Steve Liles

Right arrow

Chapter 5. Interacting with Services

In the previous chapters we focused our attention on the basic, high-level, Android-specific constructs to load data asynchronously on an independent line of execution (background thread); android.os.AsyncTask and android.content.Loader.

What if we want to provide a common set of operations that implement any kind of business logic over a centralized single entity that could be re-used by different clients and has a lifecycle that is not bound to the client lifecycle? By clients, in Android, we mean any kind of UI entity, such as an Activity or Fragment object, a BroadcastReceiver, or any kind of object that wants to exercise business logic.

The solution for this pattern in Android is available in the form of android.app.Service.

In Android, the Service programming pattern, well-known in enterprise architectures, does not necessarily mean background work, so to avoid any kind of responsiveness degradation in the UI we should try keep the main Thread execution...

Introducing Service


A Service in Android, as referred to before, is an entity that runs without a user interface that could be used to execute any kind of business logic which the application requires during the execution.

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, that are always invoked on the application's main thread. Here are the most important callbacks that the user must define when it creates a service by extending the Service base class:

void onCreate();
void onDestroy()
void onStartCommand(Intent intent, int flags, int startId)  
IBinder onBind(Intent intent)   
boolean onUnbind(Intent intent)

The onCreate() is the lifecycle callback that is called once when the service...

Started service


As described previously, a started Service is a service that is initiated when the Context method startService() is invoked by any entity on the system that has access to a Context object or is a Context itself, such as an Activity:

         ComponentName startService(Intent service)

Note

An Intent is a messaging object that can carry data (action, category, extras, and so on) and that you can use to request an action from another Android component.

The startService() function basically starts a service with an intent, and returns to the user a component name that can be used to verify that the correct service was resolved and invoked.

To simplify the Service resolution, we pass an Intent created from the current context with the Service class that needs to be started:

     startService(new Intent(this,MyStartedService.class));

When the system receives the first startService(intent) request, it builds up the Service by calling onCreate() and forwards the intent from the first startService...

Bound Service


A Bound Service is an Android Service that defines a client interface and allows several entities to bind it by invoking bindService() and creating a relation between each order that facilitates the interaction with a request-response model.

The Service instance will be created when the first client attempts to connect to it and will be alive until the last client disconnects from it using the unbindService() function.

In order to create the connection between the client and the server, the service must implement the onBind() function and return an IBinder object that implements a lightweight remote procedure mechanism to perform in-process or cross-process calls:

IBinder onBind(Intent intent)

When all the clients disconnect from the Service, calling unbindService(), the service onUnbind() member method is called:

boolean onUnbind (Intent intent)

A Bound Service might reside in the same process (LS), in a different process that belongs to the application (LIS), or in an another application...

Applications of Services


With a little bit of work, Services give us the means to perform long-running background tasks, and free us from the tyranny of the Activity lifecycle. As opposed to IntentService, directly sub-classing a Service also gives us the ability to control the level of concurrency.

With the ability to run as many tasks as we need and to take as long as is necessary to complete those tasks, a world of new possibilities opens up.

The only real constraint on how and when we use Services comes from the need to communicate results to a user-interface component, such as a Fragment or Activity, and the complexity this entails.

Ideal use cases for Services tend to have the following characteristics:

  • Long-running (a few hundred milliseconds and upward):

  • Not specific to a single Activity or Fragment class

  • Must complete, even if the user leaves the application

  • Does not require user intervention to complete

  • Operations that require state between different calls

  • Requires more concurrency than...

Summary


In this chapter, we explored the very powerful Service component, putting it to use to execute long-running background tasks with or without a configurable level of concurrency.

We explored the incredibly useful IntentService—an ideal construct for performing long-running background tasks off the main thread, surviving well beyond the lifecycle of the initiating Activity, and even continuing to do useful work when the application is no longer in the foreground.

We learned how to send work to an IntentService with parameterized Intents, how to process that work in the background by implementing onHandleIntent, and how to send results back to the originating Activity using a PendingIntent.

For cases where the application is no longer in the foreground or an operation is particularly long-running, we saw how to post notifications to the notification drawer, complete with progress updates.

We also saw the wide range of communication mechanisms available for delivering results back to the...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Asynchronous Android Programming - Second Edition
Published in: Jul 2016Publisher: PacktISBN-13: 9781785883248
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Steve Liles

Steve Liles is a self-confessed geek and has been an Android fan since the launch day of the G1. When he isn't at work building publishing systems and apps for newspapers and magazines, you'll find him tinkering with his own apps, building 3D printers, or playing RTS games. He is currently working with a start-up to build an advertising system that links the print and digital worlds using computer vision on Android and iOS devices.
Read more about Steve Liles