Threads, Handlers, and Programmatic Movement

advertisement
CHAPTER 6
Threads,
Handlers,
and
Programmatic Movement
Chapter objectives:
• Understand the benefits of multithreading on
Android
• Understand multi-threading fundamentals.
• Know the Thread class and the Runnable
interface
• Understand an AsyncTask
• Learn to implement canvas movement using
surface views
• Learn to communicate between threads.
6.1 Multithreading and Multi-core
Processing
• Android uses processes and thread management
models to manage running applications, services,
and the other elements of the system
• When an application does several things at once
it is called multithreading
• Other terms are used for multithreading, such as
parallelism and concurrency
• A multithreaded Android application contains
two or more threads
• Multithreading enables programmers to
write very efficient applications because it
allows the utilization idle time that may
accrue while other segments of code are
being processed
• Each thread runs as a separate path of
execution that is managed by its own stack,
the call stack
• The call stack is used to manage method
calling, parameter passing, and storage for
a called method’s local variables
• Multitasking can be subdivided into two
categories: process-based multitasking and
thread-based multitasking
• Process-based multitasking is the feature
that allows a device to execute two or more
programs concurrently.
• In process-based multitasking, an app is the
smallest unit of code that can be dispatched
by the scheduler.
• In a thread-based multitasking
environment, the thread is the smallest
unit of dispatchable code
• This means that a single program can
perform two or more tasks at once
• This single thread is responsible for
handling all the UI events
• Even a simple single-threaded application
can benefit from parallel processing on
different cores
• Categories of operations that can be
carried out on separate background
threads are as follows:
• Heavy calculations
• An Object’s long initialization
• Networking
• Database operations
6.2 Main Thread and Background
Thread
• Android UI threads are distinct from
background threads
• When an activity is created, it runs by default
in the UI thread of the application
• All the commands issued by the Android
operating system, such as onClick, onCreate,
etc., are sent to and processed by this UI
thread.
• When a substantial amount of processing is
performed on the UI thread, the
application may be too busy to respond to
messages sent by the Android operating
system
• If an application frequently computes an
elaborate game move on the UI thread, the
I/O operations of the system, such as
processing incoming user input events, may
perform sluggishly or can be blocked.
• When writing multithreaded applications in
Android, it is a good idea to keep several
things in mind about the UI thread:
• The UI thread should not perform tasks that
take longer than a few seconds
• The user interface cannot be updated from a
background thread.
• An Android application can be entered from
an Activity, Service or a Broadcast Receiver,
all of which run on the UI thread.
6.3 Thread Approaches
• From the main UI thread, programmers can
create other threads
• This is done by instantiating an object of type
Thread
• The Thread class encapsulates an object that is
runnable. There are two ways in which a
runnable object can be created:
• 1) Implement the Runnable interface
• 2) Extend the Thread class
• The Runnable interface abstracts a unit of
executable code
• You can construct a thread on any object
that implements the Runnable interface
• Runnable defines only one method called
run().
• An application that creates an instance of
Thread must provide the code that will run
in that thread
• A Thread class can also be constructed
that implements the Runnable interface
• The Thread class itself implements
Runnable, through its run() method
6.4 UI Modification and the Handler
Class
• A Handler is part of the Android system’s framework for
managing threads and is designed for inter-thread
communication
• It combines features from a BlockingQueue and a message
listener.
• Interaction between an Android thread and the UI thread is
accomplished using a UI thread Handler object and posting
Messages and Runnable objects to a message queue
• A Handler object created on the UI thread exposes a
thread-safe message queue on which background threads
can asynchronously add either messages or requests for
foreground runnables to act on their behalf
• When a Handler is created for a new
thread, it is bound to the message queue of
the thread in which it is created
• The Handler will deliver messages and
runnables to this message queue and
execute them as they are retrieved off the
queue.
6.5 Loopers
• Looper is a class within the Android user
interface that can be used in tandem with the
Handler class to provide a framework for
implementing a concurrency pattern
• Background threads can push new units of
work onto the MessageQueue at any time
• The UI thread processes the queued units of
work one after another
• If there are no work units on the
MessageQueue it waits until one appears in
the queue
• Processing the MessageQueue can be quit
at any time and units of work can be
removed from the queue
• A Looper is the mechanism that allows
these units of work to be executed or
processed sequentially on a single thread
• A Handler is used to schedule those units of
work for execution by pushing them onto a
MessageQueue.
6.6 Canvas Movement and Views
• Programatic animation can be achieved
through the use of a canvas
• A canvas is provided by View.onDraw()
• The most convenient aspect of this feature is
the provision of the pre-defined Canvas, which
is automatically supplied by the Android
framework
6.7 SurfaceViews
• Android provides a SurfaceView class to
construct objects with a dedicated drawing
surface that can be updated on a background
thread
• SurfaceViews contain a rendering mechanism
that allows threads to update the surface’s
content without the use of a Handler
• SurfaceView is derived from the View class.
It provides more resources than Views and
was created with the objective of delivering
a drawing surface for a background thread
6.8 Efficient Threading
• There are obvious advantages of
multithreading, such as the provision of
greater responsiveness by using idle time to
perform background tasks
• The employment too many threads can lead
to a sluggish application.
• The impact of having too many threads in
an application can result in the following
two conditions
• First, partitioning a fixed amount of work
among too many threads gives each
thread too little work
• Second, having too many threads running
incurs overhead in the way they share
finite processing resources
• When designing applications that require
multiple threads, it is advisable to strategize
the detection of possible deadlocks
• Deadlocks will occur when a given thread is
waiting for another thread to finish, while
that thread is waiting for the previous one to
complete
• These deadlocks must be avoided, or
resolved when they occur
• The most common thread
communication between threads occurs
between the UI thread and background
threads
• The UI thread offloads long tasks by
sending data messages to be processed
on background threads
• Multithreaded applications should follow
an efficient message passing mechanism
6.9 Materials and Functionality
• With the release of Lollipop new visual
enhancement features were added to the
platform and given the name Material Design
• A specific feature that stood out was fluid
animations
• Surfaces and edges of material provide visual
cues
• The use of familiar tactile attributes helps
users quickly comprehend how to maneuver
• Applying material design to an application
requires the android:Theme attribute in
AndroidManifest.xml to be set to Material
• This specification provides a collection of
default animations for touch feedback and
activity transitions
6.10 Async Tasks
• In general, when performing parallel tasks
running longer than a few seconds, it is best to
use Java threads rather than the UI thread
• As an alternate solution, Android provides an
AsyncTask class as a convenient way to
execute work units in parallel.
• The AsyncTask class is similar to a thread in
that it allows background work to execute
outside the UI thread
• AsyncTask is designed to be a helper class
for Thread and Handler and does not
constitute a generic threading mechanism
• AsyncTask operations should not be used
for long running work
• AsyncTask is an abstract class that is designed
to work with the UI
• An asynchronous process is defined by the
following four steps, each implemented as a
callback method:
• onPreExecute():
• doInBackground():
• onProgressUpdate():
• onPostExecute():
Download