Book Image

Asynchronous Android

By : Steve Liles
Book Image

Asynchronous Android

By: Steve Liles

Overview of this book

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.
Table of Contents (14 chapters)
Asynchronous Android
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Preface

Programming is the most fun a person can have on their own. This is a fact well-known to programmers, though it seems the rest of the world is yet to catch on. You already know this or you wouldn't be reading this book, but it constantly amazes me that more people aren't falling over themselves to learn to code.

Meanwhile, mobile devices have made computers fun even for non-coders. We carry in our pockets small machines with incredible processing power and a giddying array of sensors and interfaces.

Android takes these fun machines and makes them accessible to programmers through a fabulously well-crafted platform and tool chain, in a programming language that has stood the test of time yet continues to develop and evolve.

What could possibly be better than programming fun machines to do cool things, in a powerful language, on a well-crafted platform, with a world-class tool chain? For me, the answer is doing so with a good enough understanding of those things to make the difference between a good app and a great one.

There are many things that must come together to make a great app. You need a great idea—I can't help you there. You need a pretty user interface—sorry, wrong book. You need a great user experience—aha! Now we're getting somewhere. Among the many things that contribute to a great user experience, responsiveness is right up there near the top of the list.

It's easiest to define responsiveness with examples of its lack: pauses and glitches while scrolling content, user interfaces that freeze while loading data from storage, applications that don't give progress updates to let us know what's happening, failing to complete work that we initiated, staring at a spinner while data is fetched from the network, and the list goes on.

This book is about making the difference between a good app and a great one; smoothing out the glitches, keeping the UI responsive, telling the user how things are going, making sure we finish what we started, using those powerful multicore processors, and doing it all without wasting the battery. Let's have some fun!

What this book covers

Chapter 1, Building Responsive Android Applications, gives an overview of the Android process and thread model, and describes some of the challenges and benefits of concurrency in general, before discussing issues specific to Android.

Chapter 2, Staying Responsive with AsyncTask, covers the poster child of concurrent programming in Android. We learn how AsyncTask works, how to use it correctly, and how to avoid the common pitfalls that catch out even experienced developers.

Chapter 3, Distributing Work with Handler and HandlerThread, details the fundamental and related topics of Handler, HandlerThread, and Looper, and illustrates how they can be used to schedule tasks on the main thread, and to coordinate and communicate work between cooperating background threads.

Chapter 4, Asynchronous I/O with Loader, introduces the Loader framework and tackles the important task of loading data asynchronously to keep the user interface responsive and glitch free.

Chapter 5, Queuing Work with IntentService, gives us the means to perform background operations beyond the scope of a single Activity lifecycle and to ensure that our work is completed even if the user leaves the application.

Chapter 6, Long-running Tasks with Service, extends the capabilities we discovered with IntentService and gives us control over the level of concurrency applied to our long-running background tasks.

Chapter 7, Scheduling Work with AlarmManager, completes our toolkit by enabling us to arrange for work to be done far into the future and on repeating schedules. It also enables us to build apps that alert users to new content and start instantly with fresh data.

What you need for this book

To follow along and experiment with the examples, you will need a development computer with a Java 6 (or 7) SE Development Kit and the Android Software Development Kit Version 7 or above (you will need at least Version 19 to try all of the examples).

You will also need an Integrated Development Environment such as Android Studio or Eclipse. The examples have been developed using Google's new Android Studio IDE and use its integrated build system, Gradle.

While you can run the examples using the emulator provided by the Android SDK, it is a poor substitute for the real thing. A physical Android device is a much faster and more pleasurable way to develop and test Android applications!

Many of the examples will work on a device running any version of Android since 2.1, Éclair. Some examples demonstrate newer APIs and as a result, require a more recent Android version—up to Android 4.4, KitKat.

You can also download a prebuilt application containing all of the examples from Google Play; search for "Asynchronous Android".

Who this book is for

This book is for developers who have mastered the basics of Android and are ready to take the next big step to improve the quality of your apps—not just behind the scenes engineering quality, but real perceivable improvements that make a difference to end users.

A reasonable understanding of core Android development is assumed. If you have built Android apps before and are comfortable with the Activity class and its lifecycle, XML layout files, and the Android manifest, you should have no problem understanding the topics in this book.

Familiarity with Java's concurrency primitives and higher-level constructs will aid and deepen understanding, but is not a prerequisite.

Android developers with no prior experience of concurrency and asynchronous programming will learn when, why, and how to apply Android's concurrency constructs to build responsive apps.

Java experts new to Android will be equipped to properly apply their existing knowledge in the Android environment and will discover elegant solutions to familiar problems in Android's high-level concurrency constructs.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

protected void onPause() {
    super.onPause();
    if (task != null)
        task.cancel(false);
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

protected void onPause() {
    super.onPause();
    if (task != null)
        task.cancel(false);
}

Any command-line input or output is written as follows:

> telnet 192.168.0.4 4444 

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "clicking on the Next button moves you to the next screen."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.