Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Asynchronous Android
Asynchronous Android

Asynchronous Android: As an Android developer you know you're in a competitive marketplace. This book can give you the edge by guiding you through the concurrency constructs and proper use of AsyncTask to create smooth user interfaces.

eBook
€22.99 €25.99
Paperback
€32.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Asynchronous Android

Chapter 2. Staying Responsive with AsyncTask

The first Android-specific concurrency construct we'll look at is android.os.AsyncTask, a neat construct that encapsulates the messy business of managing threads, performing background work, and publishing progress and results back to the main thread to update the user interface.

In this chapter we will cover the following topics:

  • Introducing AsyncTask

  • Declaring AsyncTask types

  • Executing AsyncTasks

  • Providing feedback to the user

  • Providing progress updates

  • Canceling AsyncTasks

  • Handling exceptions

  • Controlling the level of concurrency

  • Common AsyncTask issues

  • Applications of AsyncTask

Introducing AsyncTask


AsyncTask was introduced in Android at API level 3, Cupcake, with the express purpose of helping developers to avoid blocking the main thread. The Async part of the name of this class comes from the word asynchronous, which literally means not occurring at the same time.

AsyncTask is an abstract class, and as such, must be subclassed for use. At the minimum, our subclass must provide an implementation for the abstract doInBackground method, which defines the work that we want to get done off the main thread.

protected Result doInBackground(Params… params)

There are four other methods of AsyncTask which we may choose to override:

protected void onPreExecute()
protected void onProgressUpdate(Progress… values)
protected void onPostExecute(Result result)
protected void onCancelled(Result result)

Although we will override one or more of these five methods, we will not invoke them directly from our own code. These are callback methods, meaning that they will be invoked for us...

Declaring AsyncTask types


AsyncTask is a generically typed class, and exposes three type parameters:

abstract class AsyncTask<Params, Progress, Result>

When we declare an AsyncTask subclass, we'll specify types for Params, Progress, and Result; for example, if we want to pass a String parameter to doInBackground, report progress as a Float, and return a Boolean result, we would declare our AsyncTask subclass as follows:

public class MyTask extends AsyncTask<String, Float, Boolean>

If we don't need to pass any parameters, or don't want to report progress, a good type to use for those parameters is java.lang.Void, which signals our intent clearly, because Void is an uninstantiable class representing the void keyword.

Let's take a look at a first example, performing an expensive calculation in the background and reporting the result to the main thread:

public class PrimesTask
extends AsyncTask<Integer, Void, BigInteger> {
  private TextView resultView;

  public PrimesTask(TextView...

Executing AsyncTasks


Having implemented doInBackground and onPostExecute, we want to get our task running. There are two methods we can use for this, each offering different levels of control over the degree of concurrency with which our tasks are executed. Let's look at the simpler of the two methods first:

public final AsyncTask<Params, Progress, Result> execute(Params… params)

The return type is the type of our AsyncTask subclass, which is simply for convenience so that we can use method chaining to instantiate and start a task in a single line and still record a reference to the instance:

class MyTask implements AsyncTask<String,Void,String>{ … }
MyTask task = new MyTask().execute("hello");

The Params… params argument is the same Params type we used in our class declaration, because the values we supply to the execute method are later passed to our doInBackground method as its Params… params arguments. Notice that it is a varargs parameter, meaning that we can pass any number...

Providing feedback to the user


Having started what we know to be a potentially long-running task, we probably want to let the user know that something is happening. There are a lot of ways of doing this, but a common approach is to present a dialog displaying a relevant message.

A good place to present our dialog is from the onPreExecute method of AsyncTask, which executes on the main thread. Hence, it is allowed to interact with the user interface.

The modified PrimesTask will need a reference to a Context, so that it can prepare a ProgressDialog, which it will show and dismiss in onPreExecute and onPostExecute respectively. As doInBackground has not changed, it is not shown in the following code, for brevity:

public class PrimesTask extends AsyncTask<Integer, Void, BigInteger>{
  private Context ctx;
  private ProgressDialog progress;
  private TextView resultView;

  public PrimesTask(Context ctx, TextView resultView) {
    this.ctx = ctx;
      this.resultView = resultView;
  }

...

Canceling AsyncTask


Another nice usability touch we can provide for our users is the ability to cancel a task before it completes—for example, if the task depends on some user input and, after starting the execution, the user realizes that they have provided the wrong value. AsyncTask provides support for cancellation with the cancel method.

public final boolean cancel(boolean mayInterruptIfRunning)

The mayInterruptIfRunning parameter allows us to specify whether an AsyncTask thread that is in an interruptible state may actually be interrupted—for example, if our doInBackground code is performing interruptible I/O.

Simply invoking cancel is not sufficient to cause our task to finish early. We need to actively support cancellation by periodically checking the value returned from isCancelled and reacting appropriately in doInBackground.

First, let's set up our ProgressDialog to trigger the AsyncTask's cancel method by adding a few lines to onPreExecute:

progress.setCancelable(true);
progress.setOnCancelListener...

Handling exceptions


The callback methods defined by AsyncTask dictate that we cannot throw checked exceptions, so we must wrap any code that throws checked exceptions with try/catch blocks. Unchecked exceptions that propagate out of AsyncTask's methods will crash our application, so we must test carefully and handle these if necessary.

For the callback methods that run on the main thread—onPreExecute, onProgressUpdate, onPostExecute, and onCancelled—we can catch exceptions in the method and directly update the user interface to alert the user.

Of course, exceptions are likely to arise in our doInBackground method too, as this is where the bulk of the work of AsyncTask is done, but unfortunately, we can't update the user interface from doInBackground. A simple solution is to have doInBackground return an object that may contain either the result or an exception, as follows:

static class Result<T> {
  private T actual;
  private Exception exc;
}
@Override
protected final Result<T&gt...

Controlling the level of concurrency


So far, we've carefully avoided being too specific about what exactly happens when we invoke AsyncTask's execute method. We know that doInBackground will execute off the main thread, but what exactly does that mean?

The original goal of AsyncTask was to help developers avoid blocking the main thread. In its initial form at API level 3, AsyncTasks were queued and executed serially (that is, one after the other) on a single background thread, guaranteeing that they would complete in the order they were started.

This changed in API level 4 to use a pool of up to 128 threads to execute multiple AsyncTasks concurrently with each other—a level of concurrency of up to 128. At first glance, this seems like a good thing, since a common use case for AsyncTask is to perform blocking I/O, where the thread spends much of its time idly waiting for data.

However, as we saw in Chapter 1, Building Responsive Android Applications, there are many issues that commonly arise...

Common AsyncTask issues


As with any powerful programming abstraction, AsyncTask is not entirely free from issues and compromises.

Fragmentation issues

In the Controlling the level of concurrency section, we saw how AsyncTask has evolved with new releases of the Android platform, resulting in behavior that varies with the platform of the device running the task, which is a part of the wider issue of fragmentation.

The simple fact is that if we target a broad range of API levels, the execution characteristics of our AsyncTasks—and therefore, the behavior of our apps—can vary considerably on different devices. So what can we do to reduce the likelihood of encountering AsyncTask issues due to fragmentation?

The most obvious approach is to deliberately target devices running at least Honeycomb, by setting a minSdkVersion of 11 in the Android Manifest file. This neatly puts us in the category of devices, which, by default, execute AsyncTasks serially, and therefore, much more predictably.

However,...

Applications of AsyncTask


Now that we have seen how to use AsyncTask, we might ask ourselves when we should use it.

Good candidate applications for AsyncTask tend to be relatively short-lived operations (at most, for a second or two), which pertain directly to a specific Fragment or Activity and need to update its user interface.

AsyncTask is ideal for running short, CPU-intensive tasks, such as number crunching or searching for words in large text strings, moving them off the main thread so that it can remain responsive to input and maintain high frame rates.

Blocking I/O operations such as reading and writing text files, or loading images from local files with BitmapFactory, are also good use cases for AsyncTask.

Of course, there are use cases for which AsyncTask is not ideally suited. For anything that requires more than a second or two, we should weigh the cost of performing this operation repeatedly if the user rotates the device, or switches between apps or activities, or whatever else...

Summary


In this chapter, we've taken a detailed look at AsyncTask and how to use it to write responsive applications that perform operations without blocking the main thread.

We saw how to keep the user informed of the progress, and even allow them to cancel operations early. We also learned how to deal with issues that can arise when the Activity lifecycle conspires against our background tasks.

Finally, we considered when to use AsyncTask, and when it might not be appropriate.

In the next chapter, we'll take a look at some lower-level constructs—fundamental building blocks on which the other concurrency mechanisms of the platform, including AsyncTask, are built.

Left arrow icon Right arrow icon

Key benefits

  • Learn how to use Android's high-level concurrency constructs to keep your applications smooth and responsive
  • Leverage the full power of multi-core mobile CPUs to get more work done in less time
  • From quick calculations to scheduled downloads, each chapter explains the available mechanisms of asynchronous programming in detail

Description

With more than a million apps available from Google Play, it is more important than ever to build apps that stand out from the crowd. To be successful, apps must react quickly to user input, deliver results in a flash, and sync data in the background. The key to this is understanding the right way to implement asynchronous operations that work with the platform, instead of against it. Asynchronous Android is a practical book that guides you through the concurrency constructs provided by the Android platform, illustrating the applications, benefits, and pitfalls of each.Learn to use AsyncTask correctly to perform operations in the background, keeping user-interfaces running smoothly while avoiding treacherous memory leaks. Discover Handler, HandlerThread and Looper, the related and fundamental building blocks of asynchronous programming in Android. Escape from the constraints of the Activity lifecycle to load and cache data efficiently across your entire application with the Loader framework. Keep your data fresh with scheduled tasks, and understand how Services let your application continue to run in the background, even when the user is busy with something else.Asynchronous Android will help you to build well-behaved apps with smooth, responsive user-interfaces that delight users with speedy results and data that's always fresh, and keep the system happy and the battery charged by playing by the rules.

Who is this book for?

This book is for Android developers who want to learn about the advanced concepts of Android programming. No prior knowledge of concurrency and asynchronous programming is required. This book is also targeted towards Java experts who are new to Android.

What you will learn

  • Understand Android s process model and its implications on your applications
  • Exercise multithreading to build well-behaved Android applications that work with the platform
  • Apply and control concurrency to deliver results quickly and keep your applications responsive to user input
  • Discover Android-specific constructs that make asynchronous programming easy and efficient
  • Learn how to apply Android s concurrency constructs to build smooth and responsive applications

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 24, 2013
Length: 146 pages
Edition : 1st
Language : English
ISBN-13 : 9781783286874
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Dec 24, 2013
Length: 146 pages
Edition : 1st
Language : English
ISBN-13 : 9781783286874
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 102.97
Android Application Security Essentials
€36.99
Asynchronous Android
€32.99
Creating Dynamic UI with Android Fragments
€32.99
Total 102.97 Stars icon

Table of Contents

7 Chapters
Building Responsive Android Applications Chevron down icon Chevron up icon
Staying Responsive with AsyncTask Chevron down icon Chevron up icon
Distributing Work with Handler and HandlerThread Chevron down icon Chevron up icon
Asynchronous I/O with Loader Chevron down icon Chevron up icon
Queuing Work with IntentService Chevron down icon Chevron up icon
Long-running Tasks with Service Chevron down icon Chevron up icon
Scheduling Work with AlarmManager Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(4 Ratings)
5 star 75%
4 star 25%
3 star 0%
2 star 0%
1 star 0%
Brett Sep 28, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is the best book to learn about the android framework's async features. There are other broader books on android that will give a chapter or two to the various pieces of the framework that are provided to help you run tasks asynchronously but they always seem to leave you wanting and wandering Google for a little more information. The author gives a thorough introduction to each of the tools provided by android to help its developers run tasks in parallel.I would recommend reading the entire book but it is organized nicely and each component gets its own chapter. If you are simply dealing with asynctasks and life cycle issues related to asynctasks you can open this book to that chapter and be happily on your way.Overall because of the importance that android places on not blocking an application's main thread means that every android developer should read this book to get the best performance and stability from their apps.
Amazon Verified review Amazon
Philip Arad Apr 07, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
With more than a million apps available from Google Play, Android has quickly become one of the most popular mobile operating system in use. Nowadays it is more important than ever to build apps that react quickly to user input, deliver results in a flash, and sync data in the background. Among the many things that contribute to a great user experience, responsiveness is the most important. Before making your app available to your users you must eliminate pauses and glitches while scrolling content, remove user interfaces that freeze while loading data from storage, add progress updates to let us know what's happening, and so on. In order to accomplish this task you must understand how to implement asynchronous operations that work with the Android platformTo address this problem efficiently, I recommend reading the book 'Asynchronous Android' from 'Packt Publishing' (see [...] )'Asynchronous Android' is a practical book that guides you through the concurrency constructs provided by the Android platform, illustrating the applications, benefits, and pitfalls of each.Reading the book, you will learn to use AsyncTask correctly to perform operations in the background, keeping user-interfaces running smoothly while avoiding treacherous memory leaks. Discover Handler, HandlerThread and Looper, the related and fundamental building blocks of asynchronous programming in Android. Escape from the constraints of the Activity lifecycle to load and cache data efficiently across your entire application with the Loader framework. Keep your data fresh with scheduled tasks, and understand how Services let your application continue to run in the background, even when the user is busy with something else.Asynchronous Android will help you to build well-behaved apps with smooth, responsive user-interfaces that delight users with speedy results and data that’s always fresh, and keep the system happy and the battery charged by playing by the rules.
Amazon Verified review Amazon
Liang Ma Sep 14, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very concise, but informative and helpful. Well worth the money. Sincerely recommend this great book to all Android developers.
Amazon Verified review Amazon
R. Williams Mar 24, 2014
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Give this book a little bit of credit for doing a decent job of covering the waterfront which is kind of vast. You can figure most of the same things out reading the documentation, but this is a good single source, for example, to figure out if you want to use Handlers or AsyncTasks, etc. Frankly, this is one of the best things books can provide when their topic is as wide ranging as an operating system, and the Android docs do not do this very well. The section on Services is really pretty good: there is discussion of IntentService vs. extending Service itself, and the rationale for doing services (which is actually quite broad).The negatives in this book is that the material is pretty thin. For instance, there is no in depth discussion of things like the looper. There is no discussion at all about testing. It all kind of has the feel of just 'if you're looking for x, go to door y.' Also, there are a few sections of the book that are completely absurd like the one where the author uses a file download as an example of something that ought be implemented as a service, then in the chapter summary he calls it the best example of a service. On earth? Huh??Just barely made 4 and that's because of the success in providing comparative summaries that the documentation lacks.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.