Asynchronous Android Programming Helder Vasconcelos download
Asynchronous Android Programming Helder Vasconcelos download
Vasconcelos download
https://textbookfull.com/product/asynchronous-android-
programming-helder-vasconcelos/
https://textbookfull.com/product/combine-asynchronous-
programming-with-swift-first-edition-scott-gardner/
https://textbookfull.com/product/combine-asynchronous-
programming-with-swift-first-edition-scott-gardner-2/
https://textbookfull.com/product/asynchronous-programming-in-
rust-1st-edition-carl-fredrik-samson/
Asynchronous Programming in Rust 1 / converted Edition
Carl Fredrik Samson
https://textbookfull.com/product/asynchronous-programming-in-
rust-1-converted-edition-carl-fredrik-samson/
https://textbookfull.com/product/using-asyncio-in-python-
understanding-python-s-asynchronous-programming-features-caleb-
hattingh/
https://textbookfull.com/product/learning-embedded-android-n-
programming-1st-edition-ivan-morgillo/
https://textbookfull.com/product/expert-twisted-event-driven-and-
asynchronous-programming-with-python-1st-edition-mark-williams/
https://textbookfull.com/product/concurrency-in-c-cookbook-
asynchronous-parallel-and-multithreaded-programming-2nd-edition-
stephen-cleary/
[1]
Asynchronous Android
Programming
Second Edition
Helder Vasconcelos
BIRMINGHAM - MUMBAI
Asynchronous Android Programming
Second Edition
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
ISBN 978-1-78588-324-8
www.packtpub.com
Credits
Reviewer Proofreader
Gavin Matthews Safis Editing
Copy Editor
Vibha Shukla
About the Author
At www.PacktPub.com, you can also read a collection of free technical articles, sign
up for a range of free newsletters and receive exclusive discounts and offers on Packt
books and eBooks.
TM
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser
Table of Contents
Preface vii
Chapter 1: Asynchronous Programming in Android 1
Android software stack 2
Dalvik runtime 2
ART runtime 3
Memory sharing and Zygote 4
Android process model 5
Process ranks 5
Process sandboxing 6
Android thread model 6
The main thread 7
The Application Not Responding (ANR) dialog 9
Maintaining responsiveness 10
Concurrency in Android 12
Correctness issues in concurrent programs 14
Liveness issues in concurrent programs 16
Thread coordination 16
Concurrent package constructs 19
Executor framework 20
Android primary building blocks 21
Activity concurrent issues 21
Manipulating the user interface 23
Service concurrent issues 25
Started services issues 25
Bound services issues 26
Service in a separate process 27
Broadcast receiver concurrent issues 28
Android concurrency constructs 28
Summary 29
[i]
Table of Contents
[ ii ]
Table of Contents
Loader Manager 98
LoaderManager.LoaderCallbacks 99
Loader lifecycle 100
Loading data with Loader 101
Building responsive apps with AsyncTaskLoader 107
Building responsive apps with CursorLoader 116
Combining Loaders 119
Applications of Loader 125
Summary 125
Chapter 5: Interacting with Services 127
Introducing Service 128
Started service 131
Building responsive apps with IntentService 136
Handling results 139
Posting results with PendingIntent 139
Posting results as system notifications 142
Applications of IntentService 143
HTTP uploads with IntentService 144
Reporting progress 146
Bound Service 149
Communicating with a Local Service 150
Broadcasting results with intents 158
Detecting unhandled broadcasts 160
Applications of Services 163
Summary 164
Chapter 6: Scheduling Work with AlarmManager 165
Introducing AlarmManager 166
Scheduling alarms with AlarmManager 167
Setting alarms in recent Android versions 169
Testing your alarms in Doze Mode 172
Setting a Window alarm 173
Debugging AlarmManager alarms 173
Canceling alarms 175
Scheduling repeating alarms 176
Scheduling an alarm clock 178
Handling alarms 179
Handling alarms with Activities 180
Handling alarms with BroadcastReceiver 181
Working with BroadcastReceiver 183
Asynchronous work with goAsync 186
[ iii ]
Table of Contents
[ iv ]
Table of Contents
[v]
Table of Contents
[ vi ]
Preface
Whether you are Android beginner developer or an Android seasoned programmer,
this book will explore how to achieve efficient and reliable multithreaded Android
applications.
Using step-by-step guidelines and code examples, you will learn how manage
interactions between several threads and avoid concurrency and synchronization
problems that might occur when two or more threads access a shared resource to
complete a background job, to update the UI or retrieve the latest application data.
At the end of this journey you will know how build well-behaved applications with
smooth, responsive user-interfaces that delight users with speedy results and data
that's always fresh.
[ vii ]
Preface
Chapter 2, Performing Work with Looper, 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 3, Exploring the AsyncTask, covers the most common concurrent construct of
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 4, Exploring the 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, Interacting with Services, we explored the very powerful Service Android
component, putting it to use to execute long-running background tasks with or
without a configurable level of concurrency. This component 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 7, Exploring the JobScheduler API, covers a job scheduling system API
introduced with Android Lollipop that allows us to start background work
when a set of device conditions, such as energy or network, are fulfilled.
Chapter 9, Asynchronous Work on the Native layer, introduces the JNI interface, an
Java standard interface that will allow us to execute concurrent tasks on native
code (C/C++), interact with the Java code from the native layer or update the
UI from the native code.
Chapter 10, Network Interactions with GCM, we will learn how to use the Google GCM
to efficiently push and pull efficiently realtime messages from your server and how
to schedule work with Google Play Services framework.
Chapter 11, Exploring Bus-based Communications, we will introduce to the reader the
publish-subscribe messaging pattern and the Event Bus Library, a publish-subscribe
implementation that allow us to deliver asynchronous messages between Android
application components.
[ viii ]
Preface
Chapter 12, Asynchronous Programing with RxJava, we will introduce RxJava, a library
used to easily compose asynchronous and event-based tasks on Java by using
observable data streams.
You will also need Android Studio IDE. 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.3, GingerBread. Some examples demonstrate newer APIs and as a result, require a
more recent Android version—up to Android 5, Lollipop.
They want to learn this technology because they want learn how to build efficient
applications that are able to interact orderly with internal/external services and
frameworks using Android standard constructs and APIs.
Conventions
In this book, you will find a number of text styles that distinguish between different
kinds of information. Here are some examples of these styles and an explanation of
their meaning.
[ ix ]
Preface
Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"We can include other contexts through the use of the include directive."
When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
[default]
exten => s,1,Dial(Zap/1|30)
exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)
New terms and important words are shown in bold. Words that you see on the
screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking
the Next button moves you to the next screen."
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or disliked. Reader feedback is important for us as it helps
us develop titles that you will really get the most out of.
[x]
Preface
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 at 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.
1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box.
5. Select the book for which you're looking to download the code files.
6. Choose from the drop-down menu where you purchased this book from.
7. Click on Code Download.
You can also download the code files by clicking on the Code Files button on the
book's webpage at the Packt Publishing website. This page can be accessed by
entering the book's name in the Search box. Please note that you need to be logged in
to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder
using the latest version of:
[ xi ]
Preface
The code bundle for the book is also hosted on GitHub at https://github.com/
PacktPublishing/Asynchronous-Android-Programming. We also have other code
bundles from our rich catalog of books and videos available at https://github.
com/PacktPublishing/. Check them out!
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 could 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 to our website or added
to any list of existing errata under the Errata section of that title.
Piracy
Piracy of copyrighted 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.
We appreciate your help in protecting our authors and our ability to bring you
valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at
questions@packtpub.com, and we will do our best to address the problem.
[ xii ]
Asynchronous Programming
in Android
Asynchronous programming has become an important topic of discussion in the past
few years, especially when using the concurrent processing capabilities available on
the most recent mobile hardware.
Android applications, since they mostly run on devices with multiple units of
processing, should take advantage of asynchronous programming to scale and
improve the application performance when blocking operations, and when
CPU-intensive tasks are required.
Android is an open source operating system (OS) based on Linux kernel that was
devised in 2003 by Andy Rubin, Nick Sears, Chris White, and Rick Miner, and then
acquired by Google in July, 2005.
The Android OS, actually maintained by Google and the Open Handset Alliance,
was created to provide an open mobile-device platform for devices with limited
resources of computation, memory, and energy.
The platform has been incorporating advanced mobile devices standards, such as
NFC and Bluetooth LE, and its scope has grown from a pure smartphone platform to
a broader software platform for smart watches, TVs, tablets, and consoles.
[1]
Asynchronous Programming in Android
The maintainers have been regularly updating the platform with great features and
some improvements over minor and major releases since the first release.
The Android application compiled code (bytecode), typically a Java compiled code,
runs on a virtual machine based on Dalvik or ART.
Dalvik runtime
The Dalvik VM (DVM) runtime, created by Dan Borstein, was the first runtime for
the platform and is a register-based virtual machine that was created to run the Java
code efficiently in a constrained runtime with a limited amount of power processing,
RAM, and electric power.
[2]
Chapter 1
Dalvik's creators claim that the DVM is, on an average, around 30% more efficient
than the standard Java VM (Oracle). According to Bornstein, it requires 30% less
instructions and 35 % less coding units.
Clearly, Google has gone to great lengths to squeeze every drop of performance out
of each mobile device to help developers build responsive applications.
The virtual machine, which runs the Java code compiled and transformed to the dex
format over the dx tool, runs on a Linux process with its own memory space and file
descriptors. It also manages its own group of threads.
The dex file and application resources are packed in an Android application
package (APK) by the AAPT and installed over Google Play in the end user devices.
Since Android 2.2 the DVM comes with a trace-based Just-In-Time (JIT) compilation
feature that actively optimizes every time the application runs some short segments
of frequently used bytecode called traces.
ART runtime
The ART runtime is a new version of the DVM and was introduced to improve the
runtime performance and memory consumption. The new runtime was introduced
in Android 4.4 KitKat as an experimental runtime, and since the Android 5.0
Lollipop, it has become the main Android runtime.
This new runtime, making use of the ahead-of-time (AOT) compilation, brings new
app-performance optimizations on startup time and application execution. The AOT,
as opposed to DVM JIT (Just in Time), compiles the dex files during the installation
time using the device dex2oat tool. The compiled code generated from the dex2oat
tool generates system-dependent code for the target device and removes the delay
introduced by the JIT compilation during each application execution.
[3]
Asynchronous Programming in Android
The AOT compiler also reduces the number of processor cycles used by the
application as it removes the time spent by the JIT compiler to convert the
code into machine code, and then uses less battery power to run the application.
One of the drawbacks of the AOT compilation is the larger memory footprint in
comparison with the JIT used by DVM.
With the new runtime, some improvements were also introduced in the memory
allocation and on Garbage Collection (GC), resulting in a more responsive UI and
better application experience.
A special process called the Zygote (first life cell in an animal's reproduction)—
the process that all the Android applications are based on—is launched when an
Android device initially boots.
The Zygote starts up a virtual machine, preloads the core libraries, and initializes
various shared structures. It then waits for instructions by listening on a socket.
The COW technique, available on most Unix systems, only allocates new memory
on the child process when the process tries to change the memory cloned from the
parent process.
• First, the virtual machine and core libraries are already loaded into the
memory. Not having to read this significant chunk of data from the filesystem
to initialize the virtual machine drastically reduces the startup overhead.
• Second, the memory in which these core libraries and common structures
reside is shared by the Zygote with all other applications, resulting in saving
a lot of memory when the user is running multiple apps.
[4]
Chapter 1
The Linux kernel will fairly allocate small amounts of CPU time for application
execution called CPU time slices. This time-slicing approach means that even
a single-processor device can appear to be actively working in more than one
application at the same time, when in fact, each application is taking very short
turns on the CPU.
Process ranks
The Android operating system tries to maintain the application running for as long
as possible, but when the available memory is low, it will try to free resources in the
system by killing the processes with lower importance first.
This is when process ranking comes into the picture; the Android processes are
ranked in the next five categories from the higher priority to the lower priorities:
When the system reaches a point that it needs to release resources, the processes
available to be killed will be sorted, taking into account the process rank, last used
processes, and components running.
[5]
Asynchronous Programming in Android
Process sandboxing
The Android application always runs under a unique Linux user ID (UID) assigned
to the application during the application installation so that the process runs on a
sandboxed environment, which by default, isolates your data and code execution
from other apps.
In some cases, a user could explicitly be required to share the UID with another
application to have access to their data:
USER PID PPID VSIZE RSS PC NAME
root 319 1 1537236 31324 S zygote
….
u0_a221 5993 319 1731636 41504 S com.whatsapp
u0_a96 3018 319 1640252 29540 S com.dropbox.android
u0_a255 4892 319 1583828 34552 S com.accuweather.android…
The preceding table that results from running the adb shell ps command in the
computer with Android SDK Table is a list of Android running processes.
The first column shows the user identifier (UID) assigned at the time of installation,
the second column is the process ID (PID), the third column shows the parent
process ID (PPID) that for Android applications is the Zygote process, and the last
column shows the application package.
From this list, we can assure that the WhatsApp application is running under the
user ID u0_a221 with the process ID 5993 and the parent process is the Zygote
process with the PID 319.
While the application process is started by the system and prevented from directly
interfering with data in the memory address space of other processes, the threads
may be started by an application code and can communicate and share data with
other threads within the same process. Apart from the shared data that all the
threads share in the same process, a thread can use its own memory cache to store its
data in its own memory space.
[6]
Chapter 1
The main thread, also known as UI Thread, is also the thread where your UI event
handling occurs, so to keep your application as responsible as possible, you should:
• Avoid any kind of long execution task, such as input/output (I/O) that could
block the processing for an indefinite amount of time
• Avoid CPU-intensive tasks that could make this thread occupied for a
long time
[7]
Asynchronous Programming in Android
The following diagram displays the main interactions and components involved in
the Looper line of execution thread:
The UI/Main thread, which has a Looper facility attached to it, holds a queue of
messages (MessageQueue) with some unit of work to be executed sequentially.
When a message is ready to be processed on the queue, the Looper Thread pops
the message from the queue and forwards it synchronously to the target handler
specified on the message.
When the target Handler finishes its work with the current message, the Looper
thread will be ready to process the next message available on the queue. Hence, if the
Handler spent a noticeable amount of time processing the message, it will prevent
Looper from processing other pending messages.
For example, when we write the code in an onCreate() method in the Activity
class, it will be executed on the main thread. Likewise, when we attach listeners to
user-interface components to handle taps and other user-input gestures, the listener
callback executes on the main thread.
[8]
Chapter 1
For apps that do little I/O or processing, such as applications that don't do complex
math calculations, don't use the network to implement features, or don't use
filesystem resources, this single thread model is fine. However, if we need to perform
CPU-intensive calculations, read or write files from permanent storage, or talk to
a web service, any further events that arrive while we're doing this work will be
blocked until we're finished.
If an app does not respond to user input within five seconds, the
user will see the Application Not Responding (ANR) dialog and
will be offered the option to quit the application.
Android works hard to synchronize the user interface redraws with the
hardware-refresh rate. This means that it aims to redraw at the rate of 60 frames per
second—that's just 16.67 ms per frame. If we do work on the main thread that takes
anywhere near 16 ms, we risk affecting the frame rate, resulting in jank—stuttering
animations, jerky scrolling, and so on.
[9]
Asynchronous Programming in Android
Further protection was added to the platform in Honeycomb (API level 11) with the
introduction of a new Exception class, NetworkOnMainThreadException, a subclass
of RuntimeException that is thrown if the system detects network activity initiated
on the main thread.
Maintaining responsiveness
Ideally then, we may want to offload any long-running operations from the main
thread so that they can be handled in the background by another thread, and the
main thread can continue to process user-interface updates smoothly and respond in
a timely fashion to user interactions.
• Network communications
• Input and output file operations on the local filesystem
• Image and video processing
• Complex math calculations
• Text processing
• Data encoding and decoding
For this to be useful, we must be able to coordinate the work and safely pass data
between cooperating threads—especially between background threads and the main
thread, and it is exactly to solve this problem that asynchronous programming
is used.
[ 10 ]
Random documents with unrelated
content Scribd suggests to you:
Wolffert ... was cursing me with all the
eloquence of a rich vocabulary
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com