% Generated by Sphinx.
\def\sphinxdocclass{report}
\documentclass[letterpaper,10pt,english]{sphinxmanual}
\usepackage[utf8]{inputenc}
\DeclareUnicodeCharacter{00A0}{\nobreakspace}
\usepackage{cmap}
\usepackage[T1]{fontenc}
\usepackage{babel}
\usepackage{times}
\usepackage[Bjarne]{fncychap}
\usepackage{longtable}
\usepackage{sphinx}
\usepackage{multirow}

%\usepackage[papersize={7in,9.25in}]{geometry}
\setcounter{secnumdepth}{1}


\title{Concurrency: A User-Centric Approach}
\date{June 10, 2014}
\release{1.0}
\author{Konstantin Läufer and George K. Thiruvathukal}
\newcommand{\sphinxlogo}{}
\renewcommand{\releasename}{Release}
\makeindex

\makeatletter
\def\PYG@reset{\let\PYG@it=\relax \let\PYG@bf=\relax%
    \let\PYG@ul=\relax \let\PYG@tc=\relax%
    \let\PYG@bc=\relax \let\PYG@ff=\relax}
\def\PYG@tok#1{\csname PYG@tok@#1\endcsname}
\def\PYG@toks#1+{\ifx\relax#1\empty\else%
    \PYG@tok{#1}\expandafter\PYG@toks\fi}
\def\PYG@do#1{\PYG@bc{\PYG@tc{\PYG@ul{%
    \PYG@it{\PYG@bf{\PYG@ff{#1}}}}}}}
\def\PYG#1#2{\PYG@reset\PYG@toks#1+\relax+\PYG@do{#2}}

\expandafter\def\csname PYG@tok@nd\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.33,0.33,0.33}{##1}}}
\expandafter\def\csname PYG@tok@sr\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.14,0.33,0.53}{##1}}}
\expandafter\def\csname PYG@tok@mf\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@ni\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.84,0.33,0.22}{##1}}}
\expandafter\def\csname PYG@tok@ge\endcsname{\let\PYG@it=\textit}
\expandafter\def\csname PYG@tok@mh\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@gu\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.50,0.00,0.50}{##1}}}
\expandafter\def\csname PYG@tok@s1\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@err\endcsname{\def\PYG@bc##1{\setlength{\fboxsep}{0pt}\fcolorbox[rgb]{1.00,0.00,0.00}{1,1,1}{\strut ##1}}}
\expandafter\def\csname PYG@tok@w\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.73,0.73}{##1}}}
\expandafter\def\csname PYG@tok@kt\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.56,0.13,0.00}{##1}}}
\expandafter\def\csname PYG@tok@no\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.38,0.68,0.84}{##1}}}
\expandafter\def\csname PYG@tok@kr\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@il\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@m\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@sc\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@cs\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}\def\PYG@bc##1{\setlength{\fboxsep}{0pt}\colorbox[rgb]{1.00,0.94,0.94}{\strut ##1}}}
\expandafter\def\csname PYG@tok@cp\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@mo\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@vi\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
\expandafter\def\csname PYG@tok@gd\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.63,0.00,0.00}{##1}}}
\expandafter\def\csname PYG@tok@mi\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@o\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
\expandafter\def\csname PYG@tok@nf\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.02,0.16,0.49}{##1}}}
\expandafter\def\csname PYG@tok@kn\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@ne\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@nt\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.02,0.16,0.45}{##1}}}
\expandafter\def\csname PYG@tok@vc\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
\expandafter\def\csname PYG@tok@go\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.20,0.20,0.20}{##1}}}
\expandafter\def\csname PYG@tok@k\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@sb\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@kp\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@ow\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@kd\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@nv\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
\expandafter\def\csname PYG@tok@nb\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@gp\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.78,0.36,0.04}{##1}}}
\expandafter\def\csname PYG@tok@vg\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
\expandafter\def\csname PYG@tok@c1\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}}
\expandafter\def\csname PYG@tok@nc\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.05,0.52,0.71}{##1}}}
\expandafter\def\csname PYG@tok@bp\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@ss\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.32,0.47,0.09}{##1}}}
\expandafter\def\csname PYG@tok@nn\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.05,0.52,0.71}{##1}}}
\expandafter\def\csname PYG@tok@cm\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}}
\expandafter\def\csname PYG@tok@kc\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@sd\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@na\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@s2\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@gi\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.63,0.00}{##1}}}
\expandafter\def\csname PYG@tok@sx\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.78,0.36,0.04}{##1}}}
\expandafter\def\csname PYG@tok@nl\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.13,0.44}{##1}}}
\expandafter\def\csname PYG@tok@gr\endcsname{\def\PYG@tc##1{\textcolor[rgb]{1.00,0.00,0.00}{##1}}}
\expandafter\def\csname PYG@tok@c\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}}
\expandafter\def\csname PYG@tok@se\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@s\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@gs\endcsname{\let\PYG@bf=\textbf}
\expandafter\def\csname PYG@tok@si\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.44,0.63,0.82}{##1}}}
\expandafter\def\csname PYG@tok@gt\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.27,0.87}{##1}}}
\expandafter\def\csname PYG@tok@sh\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@gh\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,0.50}{##1}}}

\def\PYGZbs{\char`\\}
\def\PYGZus{\char`\_}
\def\PYGZob{\char`\{}
\def\PYGZcb{\char`\}}
\def\PYGZca{\char`\^}
\def\PYGZam{\char`\&}
\def\PYGZlt{\char`\<}
\def\PYGZgt{\char`\>}
\def\PYGZsh{\char`\#}
\def\PYGZpc{\char`\%}
\def\PYGZdl{\char`\$}
\def\PYGZhy{\char`\-}
\def\PYGZsq{\char`\'}
\def\PYGZdq{\char`\"}
\def\PYGZti{\char`\~}
% for compatibility with earlier versions
\def\PYGZat{@}
\def\PYGZlb{[}
\def\PYGZrb{]}
\makeatother

\begin{document}

\maketitle
\tableofcontents
\phantomsection\label{index::doc}



\chapter{Concurrency: A User-Centric Approach}
\label{chapter:cder-book-chapter-draft}\label{chapter::doc}\label{chapter:concurrency-a-user-centric-approach}

\section{Introduction}
\label{chapter:introduction}
In this chapter, we study parallel and distributed computing topics from a
user-centric software development angle, focusing on the authors' research and
experience in concurrency. While the focus of this chapter is largely within
the device itself, the online source code for our examples goes beyond the on-device
experience by providing versions that connect to RESTful web services
(optionally hosted in the cloud) {\hyperref[chapter:christensen2009]{{[}Christensen2009{]}}}.
We've deliberately focused this chapter
around the on-device experience, consistent with  ``mobile first'' thinking,
which more generally is the way the ``internet of things'' also works {\hyperref[chapter:ashton2009]{{[}Ashton2009{]}}}. This
thinking results in proper separation of concerns when it comes to the user
experience, local computation, and remote interactions (mediated using
web services).

It is worth taking a few moments to ponder why mobile platforms are
interesting from the standpoint of parallel and distributed computing, even if
at first glance it is obvious. From an architectural point of view, the
landscape of mobile devices has followed a similar trajectory to that of
traditional multiprocessing systems. The early mobile device offerings,
especially when it came to smartphones, were single core. At the time of
writing, the typical smartphone  or tablet is equipped with at least two cores
but four are becoming common. In this vein, it almost goes without saying that
today's devices are well on their way to being serious parallel systems in
their own right. (In fact, in the embedded space, there has been a corresponding
emergence of parallel boards, similar to the Raspberry Pi.)

The state of parallel computing today largely requires the mastery of two
styles, often appearing in a hybrid form. task parallelism and data
parallelism. The emerging mobile devices are following desktop and server
architecture by supporting both of these. In the case of task parallelism, to
get good performance, especially when it comes to the user experience,
concurrency must be \emph{disciplined}. An additional constaint placed on mobile
devices, compared to parallel computing, is that unbounded concurrency
(threading) makes the device unusable/unresponsive, even to a greater  extent
than on desktops and servers (where there is better I/O performance  in
general). We posit that learning to program concurrency in a resource-constrained
environment (e.g. Android smartphones) can be greatly helpful for
writing better concurrent, parallel, and distributed code in general. More
importantly, today's students really want to learn emerging platforms, so
it is a great way to develop new talent in languages/systems that are likely
to be used in future parallel/distributed programming environments.

In this chapter, we begin by examining with a simple interactive behavior and
explore how to implement this using the Android mobile application development
framework. To the end of making our presentation relevant to problem solvers,
our running example is a bounded click counter application (much more
interactive and exciting than the examples commonly found in concurrency
textbooks, e.g., atomic counters, bounded buffers, dining philosophers) that
can be used to keep track of the capacity of, say, a movie theater.

We then focus on providing a richer experience by introducing timers and
internal events,  which allow for more interesting scenarios to be explored. For
example, a countdown timer can be used for notification of elapsed time, a
concept that has almost uniquely emerged in the mobile space but has
applications in embedded and parallel computing in general, where asynchronous
paradigms have been present for some time, dating to  job scheduling,
especially for longer-running jobs.

We close by exploring longer-running, CPU-bound activities. In mobile, a
crucial design goal is to ensure UI responsiveness and appropriate progress
reporting. We demonstrate strategies for ensuring computation proceeds but can
be interrupted. The methods shown here are generalized to offline code (beyond
the scope of this chapter) for interfacing with cloud-hosted web services.


\section{Basic Event-Based User Interaction}
\label{chapter:basic-event-based-user-interaction}\label{chapter:sec-events}

\subsection{Learning objectives}
\label{chapter:learning-objectives}\begin{itemize}
\item {} 
User interaction in console applications (C)

\item {} 
User interaction in GUI applications (C)

\item {} 
State-dependent behavior and user interaction (C)

\item {} 
Basics of the Android GUI framework (A)

\item {} 
Understanding user interaction as events (C)

\item {} 
The Dependency Inversion Principle (DIP) (C)

\item {} 
The Observer design pattern (C)

\item {} 
Modeling simple behaviors with UML State Machine diagrams (A)

\item {} 
Modeling execution scenarios with UML Sequence diagrams (A)

\item {} 
The Model-View-Adapter (MVA) architectural pattern (C)

\item {} 
Testing interactive applications (A)

\end{itemize}


\subsection{Introduction}
\label{chapter:id3}
In this section, we'll start with a simple interactive behavior and
explore how to implement this using the Android mobile application
development framework {\hyperref[chapter:android]{{[}Android{]}}}. Our running example will be a
bounded click counter application that can be used to keep track of
the capacity of, say, a movie theater.


\subsection{The bounded counter abstraction}
\label{chapter:the-bounded-counter-abstraction}
A \emph{bounded counter} {\hyperref[chapter:os]{{[}OS{]}}}, the concept underlying this application, is an
integer counter that is guaranteed to stay between a preconfigured
minimum and maximum value. This is called the \emph{data invariant} of the
bounded counter.
\begin{gather}
\begin{split}min \leq counter \leq max\end{split}\notag
\end{gather}
We can represent this abstraction as a simple, passive object with,
say, the following interface:

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k+kd}{public} \PYG{k+kd}{interface} \PYG{n+nc}{BoundedCounter} \PYG{o}{\PYGZob{}}
    \PYG{k+kt}{void} \PYG{n+nf}{increment}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
    \PYG{k+kt}{void} \PYG{n+nf}{decrement}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
    \PYG{k+kt}{int} \PYG{n+nf}{get}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
    \PYG{k+kt}{boolean} \PYG{n+nf}{isFull}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
    \PYG{k+kt}{boolean} \PYG{n+nf}{isEmpty}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

In following a test-driven mindset {\hyperref[chapter:tdd]{{[}TDD{]}}}, we would test implementations of
this interface using methods such as this one, which ensures that
incrementing the counter works properly:

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{n+nd}{@Test}
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{testIncrement}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{decrementIfFull}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertFalse}\PYG{o}{(}\PYG{n}{counter}\PYG{o}{.}\PYG{n+na}{isFull}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{k+kd}{final} \PYG{k+kt}{int} \PYG{n}{v} \PYG{o}{=} \PYG{n}{counter}\PYG{o}{.}\PYG{n+na}{get}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{counter}\PYG{o}{.}\PYG{n+na}{increment}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{n}{v} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{,} \PYG{n}{counter}\PYG{o}{.}\PYG{n+na}{get}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
\end{Verbatim}

In the remainder of this section, we'll put this abstraction to good
use by building an interactive application on top of it.


\subsection{The functional requirements for click counter device}
\label{chapter:the-functional-requirements-for-click-counter-device}
Next, let's imagine a device that realizes this bounded counter
concept. For example, a bouncer positioned at the door of a movie
theater to prevent overcrowding, would require a device with the
following behavior:
\begin{itemize}
\item {} 
The device is preconfigured to the capacity of the venue.

\item {} 
The device always displays the current counter value, initially
zero.

\item {} 
Whenever a person enters the movie theater, the bouncer presses the
\emph{increment} button; if there is still capacity, the counter value
goes up by one.

\item {} 
Whenever a person leaves the theater, the bouncer presses the
\emph{decrement} button; the counter value goes down by one (but not
below zero).

\item {} 
If the maximum has been reached, the \emph{increment} button either
becomes unavailable (or, as an alternative design choice, attempts
to press it cause an error). This behavior continues until the
counter value falls below the maximum again.

\item {} 
There is a \emph{reset} button for resetting the counter value directly
to zero.

\end{itemize}


\subsection{A simple graphical user interface (GUI) for a click counter}
\label{chapter:a-simple-graphical-user-interface-gui-for-a-click-counter}
Let's now flesh out the user interface of this click counter
device. In the case of a dedicated hardware device, the interface
could have tactile inputs and visual outputs, along with, say, audio
and haptic outputs.

As a minimum, we would require these interface elements:
\begin{itemize}
\item {} 
Three buttons, for incrementing and decrementing the counter value
and for resetting it to zero.

\item {} 
A numeric display of the current counter value.

\end{itemize}

Optionally, we would benefit from different types of feedback:
\begin{itemize}
\item {} 
Beep and/or vibrate when reaching the maximum counter value.

\item {} 
Show the percentage of capacity as a numeric percentage or color
thermometer.

\end{itemize}

Instead of a hardware device, we'll now implement this behavior as a
mobile software app, so let's focus first on the minimum interface
elements. In addition, we'll make the design choice that operations
that would violate the counter's data invariant are disabled.

These decisions lead to the three \emph{view states} for the bounded click
counter Android app: In the initial (minimum) view state, the
decrement button is disabled (see figure
{\hyperref[chapter:fig-boundedcounterviewstatemin]{\emph{Minimum view state}}}). In the counting view state of
the, all buttons are enabled (see figure
{\hyperref[chapter:fig-boundedcounterviewstatecounting]{\emph{Counting view state}}}). Finally, in the maximum
view state, the increment button is disabled (see figure
{\hyperref[chapter:fig-boundedcounterviewstatemax]{\emph{Maximum view state}}}; we assume a maximum value of
10). In our design, the reset button is always enabled.
\begin{figure}[htbp]
\centering
\capstart

\scalebox{0.500000}{\includegraphics{BoundedCounterViewStateMin.png}}
\caption{Minimum view state}\label{chapter:fig-boundedcounterviewstatemin}\end{figure}
\begin{figure}[htbp]
\centering
\capstart

\scalebox{0.500000}{\includegraphics{BoundedCounterViewStateCounting.png}}
\caption{Counting view state}\label{chapter:fig-boundedcounterviewstatecounting}\end{figure}
\begin{figure}[htbp]
\centering
\capstart

\scalebox{0.500000}{\includegraphics{BoundedCounterViewStateMax.png}}
\caption{Maximum view state}\label{chapter:fig-boundedcounterviewstatemax}\end{figure}


\subsection{Understanding user interaction as events}
\label{chapter:understanding-user-interaction-as-events}
It was fairly easy to express the familiar bounded counter abstraction
and to envision a possible user interface for putting this abstraction
to practical use. The remaining challenge is to tie the two together
in a meaningful way, such that the interface uses the abstraction to
provide the required behavior. In this section, we'll work on bridging
this gap.


\subsubsection{Modeling the interactive behavior}
\label{chapter:modeling-the-interactive-behavior}
As a first step, let's abstract away the concrete aspects of the user
interface:
\begin{itemize}
\item {} 
Instead of touch buttons, we'll have \emph{input events}.

\item {} 
Instead of setting a visual display, we'll \emph{modify a counter value}.

\end{itemize}

After we take this step, we can use a UML state machine diagram {\hyperref[chapter:uml]{{[}UML{]}}}
to model the dynamic behavior we described at the beginning of this
section more formally. Note how the touch buttons correspond to
\emph{events} (triggers of \emph{transitions}, i.e., arrows) with the matching
names.

The behavior starts with the \emph{initial pseudostate} represented by the
black circle. From there, the counter value gets its initial value,
and we start in the minimum state. Assuming that the minimum and
maximum values are at least two apart, we can increment
unconditionally and reach the counting state. As we keep incrementing,
we stay here as long as we are at least two away from the maximum
state. As soon as we are exactly one away from the maximum state, the
next increment takes us to that state, and now we can no longer
increment, just decrement. The system mirrors this behavior in
response to the decrement event. There is a surrounding global state
to support a single reset transition back to the minimum state.
\begin{figure}[htbp]
\centering
\capstart

\includegraphics{BoundedCounterStates.png}
\caption{The UML state machine diagram modeling the dynamic behavior of the
bounded counter application.}\end{figure}

As you can see, the three model states map directly to the view states
from the previous subsection, and the transitions enabled in each
model state map to the buttons enabled in each view state. This is not
always the case, though, and we will see examples in a later section
of an application with multiple model states but only a single view
state.

\begin{notice}{note}{Note:}
A full introduction to the Unified Modeling Language (UML)
{\hyperref[chapter:uml]{{[}UML{]}}} would go far beyond the scope of this
chapter. Therefore, we aim to introduce the key elements of
UML needed here in an informal and pragmatic manner. Various
UML resources, including the official specification, are
available at \href{http://www.uml.org/}{http://www.uml.org/}. Third-party tutorials are
available online and in book form.
\end{notice}


\subsubsection{GUI widgets as event sources}
\label{chapter:gui-widgets-as-event-sources}
For developing GUI applications, it can be quite convenient to use an
integrated development environment (IDE) with support for the GUI
framework we are targeting. In the case of Android, owner Google
provides \emph{Android Studio}, a freely available customized version of
JetBrains IntelliJIDEA
(\href{http://developer.android.com/sdk/installing/studio.html}{http://developer.android.com/sdk/installing/studio.html}).

Besides the usual IDE features, such as code comprehension,
navigation, editing, building, and testing, there is support for the
visual design of the interface by direct manipulation of components
such as buttons, labels, text fields, layouts, etc. In Android Studio,
this includes a view component editor with a graphical view,
underlying XML source view, and corresponding component tree
view. There is also an editor for setting a view component's specific
visual and behavioral properties.

Figure {\hyperref[chapter:fig-androidstudioguieditor]{\emph{Component editor view}}} shows the visual interface of
the click counter application in the Android Studio view component
editor with the increment button selected. Figure {\hyperref[chapter:fig-androidstudiocomponenttree]{\emph{Component tree view}}} shows the corresponding
hierarchy of view components as a tree.
\begin{figure}[htbp]
\centering
\capstart

\scalebox{0.500000}{\includegraphics{AndroidStudioGUIEditor.png}}
\caption{Component editor view}\label{chapter:fig-androidstudioguieditor}\end{figure}
\begin{figure}[htbp]
\centering
\capstart

\scalebox{0.500000}{\includegraphics{ComponentTree.png}}
\caption{Component tree view}\label{chapter:fig-androidstudiocomponenttree}\end{figure}

Our next step is to bring the app to life by connecting the visual
interface with the interactive behavior. For example, when pressing
the increment button in a non-full counter state, we expect the
displayed value to go up by one. In general, the user can trigger
certain events by interacting with view components and other event
sources. For example, one can press a button, swiping one's finger
across the screen, rotate the device, etc.


\subsubsection{Event listeners and the Observer pattern}
\label{chapter:event-listeners-and-the-observer-pattern}
We now discuss what an event is and what happens after it gets
triggered. We will continue focusing on our running example of
pressing the increment button.

This figure shows the selected increment button in the view component
property editor. Most importantly, the \code{onClick} event, which occurs
when the user presses this button, maps to invocations of the
\code{onIncrement} method in the associated activity instance.
\begin{figure}[htbp]
\centering
\capstart

\scalebox{0.500000}{\includegraphics{AndroidStudioButtonProperties.png}}
\caption{The increment button in the Android Studio view component editor.}\end{figure}

The visual representation of an Android GUI is generated from an XML
source. For example, the source element for our increment button looks
like this. It textually maps the \code{onClick} attribute to the
\code{onIncrement} method in the associated activity instance.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
 \PYG{n+nt}{\PYGZlt{}Button}
     \PYG{n+na}{android:id=}\PYG{l+s}{\PYGZdq{}@+id/button\PYGZus{}increment\PYGZdq{}}
     \PYG{n+na}{android:layout\PYGZus{}width=}\PYG{l+s}{\PYGZdq{}fill\PYGZus{}parent\PYGZdq{}}
     \PYG{n+na}{android:layout\PYGZus{}height=}\PYG{l+s}{\PYGZdq{}wrap\PYGZus{}content\PYGZdq{}}
     \PYG{n+na}{android:onClick=}\PYG{l+s}{\PYGZdq{}onIncrement\PYGZdq{}}
     \PYG{n+na}{android:text=}\PYG{l+s}{\PYGZdq{}@string/label\PYGZus{}increment\PYGZdq{}} \PYG{n+nt}{/\PYGZgt{}}
\end{Verbatim}

The association with an instance of a particular activity class is
declared separately in the app's \emph{Android manifest}. The top-level
\code{manifest} element specifies the Java package of the activity class,
and the \code{activity} element on line 5 specifies the name of the
activity class, \code{ClickCounterActivity}.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYGZlt{}manifest xmlns:android=\PYGZdq{}http://schemas.android.com/apk/res/android\PYGZdq{}
    package=\PYGZdq{}edu.luc.etl.cs313.android.clickcounter\PYGZdq{} ...\PYGZgt{}
    ...
    \PYGZlt{}application ...\PYGZgt{}
        \PYGZlt{}activity android:name=\PYGZdq{}.ClickCounterActivity\PYGZdq{} ...\PYGZgt{}
            \PYGZlt{}intent\PYGZhy{}filter\PYGZgt{}
                \PYGZlt{}action android:name=\PYGZdq{}android.intent.action.MAIN\PYGZdq{} /\PYGZgt{}
                \PYGZlt{}category android:name=\PYGZdq{}android.intent.category.LAUNCHER\PYGZdq{} /\PYGZgt{}
            \PYGZlt{}/intent\PYGZhy{}filter\PYGZgt{}
        \PYGZlt{}/activity\PYGZgt{}
    \PYGZlt{}/application\PYGZgt{}
\PYGZlt{}/manifest\PYGZgt{}
\end{Verbatim}

So an \emph{event} is just an invocation of an \emph{event listener} method,
possibly with an argument describing the event. We first need to
establish the association between an event source and one (or possibly
several) event listener(s) by \emph{subscribing} the listener to the
source. Once we do that, every time this source emits an event,
normally triggered by the user, the appropriate event listener method
gets called on each subscribed listener.

Unlike ordinary method invocations, where the caller knows the
identity of the callee, the (observable) event source provides a
general mechanism for subscribing a listener to a source. This
technique is widely known as the \emph{Observer} design pattern {\hyperref[chapter:gof]{{[}GOF{]}}}.

Many GUI frameworks follow this approach. In Android, for example, the
general component superclass is \code{View}, and there are various types
of listener interfaces, including \code{OnClickListener}. In following
the \emph{Dependency Inversion Principle (DIP)} {\hyperref[chapter:appp]{{[}APPP{]}}}, the \code{View} class
owns the interfaces its listeners must implement.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k+kd}{public} \PYG{k+kd}{class} \PYG{n+nc}{View} \PYG{o}{\PYGZob{}}
    \PYG{o}{.}\PYG{o}{.}\PYG{o}{.}
    \PYG{k+kd}{public} \PYG{k+kd}{static} \PYG{k+kd}{interface} \PYG{n+nc}{OnClickListener} \PYG{o}{\PYGZob{}}
        \PYG{k+kt}{void} \PYG{n+nf}{onClick}\PYG{o}{(}\PYG{n}{View} \PYG{n}{source}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{setOnClickListener}\PYG{o}{(}\PYG{k+kd}{final} \PYG{n}{OnClickListener} \PYG{n}{listener}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \PYG{o}{\PYGZcb{}}
    \PYG{o}{.}\PYG{o}{.}\PYG{o}{.}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

Android follows an event source/listener naming idiom loosely based on
the Javabeans specification {\hyperref[chapter:javabeans]{{[}JavaBeans{]}}}. Listeners of, say, the \code{onX} of
event implement the \code{OnXListener} interface with the \code{onX(Source
source)} method. Sources of this kind of event implement the
\code{setOnXListener} method. An actual event instance corresponds to an
invocation of the \code{onX} method with the source component passed as
the \code{source} argument.

\begin{notice}{note}{Note:}
Those readers who have worked with GUI framework that
supports multiple listeners, such as Swing, might initially
find it restrictive of Android to allow only one. We'll
leave it as an exercise to figure out which well-known
software design pattern can be used to work around this
restriction.
\end{notice}


\subsubsection{Processing events triggered by the user}
\label{chapter:processing-events-triggered-by-the-user}
The Android activity is responsible for mediating between the view
components and the POJO (plain old Java object) bounded counter model
we saw above. The full cycle of each event-based interaction goes like
this. By pressing the increment button, the user triggers the
\code{onClick} event on that button, and the \code{onIncrement} method gets
called. This method interacts with the model instance by invoking the
\code{increment} method and then requests a view update of the activity
itself. The corresponding \code{updateView} method also interacts with
the model instance by retrieving the current counter value using the
\code{get} method, displays this value in the corresponding GUI element
with unique ID \code{textview\_value}, and finally updates the view states
as necessary.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{onIncrement}\PYG{o}{(}\PYG{k+kd}{final} \PYG{n}{View} \PYG{n}{view}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{model}\PYG{o}{.}\PYG{n+na}{increment}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{updateView}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
\end{Verbatim}

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{k+kd}{protected} \PYG{k+kt}{void} \PYG{n+nf}{updateView}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{k+kd}{final} \PYG{n}{TextView} \PYG{n}{valueView} \PYG{o}{=} \PYG{o}{(}\PYG{n}{TextView}\PYG{o}{)} \PYG{n}{findViewById}\PYG{o}{(}\PYG{n}{R}\PYG{o}{.}\PYG{n+na}{id}\PYG{o}{.}\PYG{n+na}{textview\PYGZus{}value}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{valueView}\PYG{o}{.}\PYG{n+na}{setText}\PYG{o}{(}\PYG{n}{Integer}\PYG{o}{.}\PYG{n+na}{toString}\PYG{o}{(}\PYG{n}{model}\PYG{o}{.}\PYG{n+na}{get}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{c+c1}{// afford controls according to model state}
        \PYG{o}{(}\PYG{o}{(}\PYG{n}{Button}\PYG{o}{)} \PYG{n}{findViewById}\PYG{o}{(}\PYG{n}{R}\PYG{o}{.}\PYG{n+na}{id}\PYG{o}{.}\PYG{n+na}{button\PYGZus{}increment}\PYG{o}{)}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{setEnabled}\PYG{o}{(}\PYG{o}{!}\PYG{n}{model}\PYG{o}{.}\PYG{n+na}{isFull}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{o}{(}\PYG{o}{(}\PYG{n}{Button}\PYG{o}{)} \PYG{n}{findViewById}\PYG{o}{(}\PYG{n}{R}\PYG{o}{.}\PYG{n+na}{id}\PYG{o}{.}\PYG{n+na}{button\PYGZus{}decrement}\PYG{o}{)}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{setEnabled}\PYG{o}{(}\PYG{o}{!}\PYG{n}{model}\PYG{o}{.}\PYG{n+na}{isEmpty}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
\end{Verbatim}
\begin{figure}[htbp]
\centering
\capstart

\scalebox{1.000000}{\includegraphics{ClickCounterSequenceDiagram.png}}
\caption{This UML sequence diagram shows the full event-based interaction
cycle in response to a press of the increment button. Stick arrow
heads represent events, while solid arrow heads represent method
invocations.}\end{figure}

\emph{What happens if the user presses two buttons at the same time?} The
GUI framework responds to at most one button press or other event
trigger at any given time. While the GUI framework is processing an
event, it places additional incoming event triggers on a queue and
fully processes each one in turn. Specifically, only after the event
listener method handling the current event returns will the framework
process the next event. (Accordingly, activation boxes of different
event listener method invocations in the UML sequence diagram must not
overlap.) This approach is called \emph{single-threaded event handling}. It
keeps the programming model simple and avoids problems such as race
conditions or deadlocks that can arise in multithreaded approaches.


\subsection{Application architecture}
\label{chapter:application-architecture}
This overall application architecture, where a component mediates
between view components and model components, is known as
\emph{model-view-adapter (MVA)} {\hyperref[chapter:mva]{{[}MVA{]}}}, where the adapter component mediates all
interactions between the view and the model. (By contrast, the
\emph{model-view-controller (MVC)} architecture has a triangular shape and
allows the model to update the view(s) directly via update events.)
The figure below illustrates this architecture. The solid arrows
represent ordinary method invocations, and the dashed arrow represents
event-based interaction. View and adapter play the roles of observable
and observer, respectively, in the Observer pattern that describes the
top half of this architecture.
\begin{figure}[htbp]
\centering
\capstart

\scalebox{1.000000}{\includegraphics{ModelViewAdapter.png}}
\caption{This UML class diagram shows the Model-View-Adapter (MVA)
architecture of the bounded click counter Android app. Solid arrows
represent method invocation, and dashed arrows represent event
flow.}\end{figure}


\subsection{System-testing GUI applications}
\label{chapter:system-testing-gui-applications}
Automated system testing of entire GUI applications is a broad and
important topic that goes beyond the scope of this chapter. Here, we
complete our running example by focusing on a few key concepts and
techniques.

We distinguish between our application code, usually referred to as
the \emph{system under test} (SUT), and the test code. \emph{Test coverage}
describes the extent to which our test code exercises the SUT, and
there are several ways to measure test coverage. We generally want
test coverage to be as close to 100\% as possible and can measure this
using suitable tools.

At the beginning of this section, we already saw an example of a
simple component-level unit test method for the POJO bounded counter
model. Because Android view components support triggering events
programmatically, we can also write system-level test methods that
mimic the way a human user would interact with the application.


\subsubsection{System-testing the click counter}
\label{chapter:system-testing-the-click-counter}
The following test handles a simple scenario of pressing the reset
button, verifying that we are in the minimum view state, then pressing
the increment button, verifying that the value has gone up and we are
in the counting state, pressing the reset button again, and finally
verifying that we are back in the minimum state.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{n+nd}{@Test}
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{testActivityScenarioIncReset}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getResetButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{performClick}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{n}{getDisplayedValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getIncButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{isEnabled}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertFalse}\PYG{o}{(}\PYG{n}{getDecButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{isEnabled}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getResetButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{isEnabled}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getIncButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{performClick}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{n}{getDisplayedValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getIncButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{isEnabled}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getDecButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{isEnabled}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getResetButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{isEnabled}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getResetButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{performClick}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{n}{getDisplayedValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getIncButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{isEnabled}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertFalse}\PYG{o}{(}\PYG{n}{getDecButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{isEnabled}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getResetButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{isEnabled}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getResetButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{performClick}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
\end{Verbatim}

The next test ensures that the visible application state is preserved
under device rotation. This is an important and effective test because
an Android application goes through its entire lifecycle under
rotation.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{n+nd}{@Test}
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{testActivityScenarioRotation}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getResetButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{performClick}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{n}{getDisplayedValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getIncButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{performClick}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getIncButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{performClick}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getIncButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{performClick}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{,} \PYG{n}{getDisplayedValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{getActivity}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{setRequestedOrientation}\PYG{o}{(}\PYG{n}{ActivityInfo}\PYG{o}{.}\PYG{n+na}{SCREEN\PYGZus{}ORIENTATION\PYGZus{}LANDSCAPE}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{,} \PYG{n}{getDisplayedValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{getActivity}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{setRequestedOrientation}\PYG{o}{(}\PYG{n}{ActivityInfo}\PYG{o}{.}\PYG{n+na}{SCREEN\PYGZus{}ORIENTATION\PYGZus{}PORTRAIT}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{,} \PYG{n}{getDisplayedValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getResetButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{performClick}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
\end{Verbatim}


\subsubsection{System testing in and out of container}
\label{chapter:system-testing-in-and-out-of-container}
We have two main choices for system-testing our app:
\begin{itemize}
\item {} 
In-container/instrumentation testing in the presence of the target
execution environment, such as an actual Android phone or tablet
emulator (or physical device). This requires deploying both the SUT
and the test code to the emulator and tends to be quite slow. So
far, Android's build tools officially support only this mode.

\item {} 
Out-of-container testing on the development workstation using a test
framework such as \emph{Robolectric} that simulates an Android runtime
environment tends to be considerably faster. This and other
non-instrumentation types of testing can be integrated in the
Android build process with a bit of extra effort.

\end{itemize}

Although the Android build process does not officially support this or
other types of non-instrumentation testing, they can be integrated in
the Android build process with a bit of extra effort.


\subsubsection{Structuring test code for flexibility and reuse}
\label{chapter:structuring-test-code-for-flexibility-and-reuse}
Typically, we'll want to run the exact same test logic in both cases,
starting with the simulated environment and occasionally targeting the
emulator or device. An effective way to structure our test code for
this purpose is the xUnit pattern \emph{Testcase Superclass}. As the
pattern name suggests, we pull up the common test code into an
abstract superclass, and each of the two concrete test classes
inherits the common code and runs it in the desired environment.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{n+nd}{@RunWith}\PYG{o}{(}\PYG{n}{RobolectricTestRunner}\PYG{o}{.}\PYG{n+na}{class}\PYG{o}{)}
\PYG{k+kd}{public} \PYG{k+kd}{class} \PYG{n+nc}{ClickCounterActivityRobolectric} \PYG{k+kd}{extends} \PYG{n}{AbstractClickCounterActivityTest} \PYG{o}{\PYGZob{}}
    \PYG{c+c1}{// some minimal Robolectric\PYGZhy{}specific code}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

The official Android test support, however, requires inheriting from a
specific superclass called \code{ActivityInstrumentationTestCase2}. This
class now takes up the only superclass slot, so we cannot use the
Testcase Superclass pattern literally. Instead, we need to approximate
inheriting from our \code{AbstractClickCounterActivityTest} using
delegation to a subobject. This gets the job done but can get quite
tedious when a lot of test methods are involved.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k+kd}{public} \PYG{k+kd}{class} \PYG{n+nc}{ClickCounterActivityTest}
  \PYG{k+kd}{extends} \PYG{n}{ActivityInstrumentationTestCase2}\PYG{o}{\PYGZlt{}}\PYG{n}{ClickCounterActivity}\PYG{o}{\PYGZgt{}} \PYG{o}{\PYGZob{}}
    \PYG{o}{.}\PYG{o}{.}\PYG{o}{.}
    \PYG{c+c1}{// test subclass instance to delegate to}
    \PYG{k+kd}{private} \PYG{n}{AbstractClickCounterActivityTest} \PYG{n}{actualTest}\PYG{o}{;}

    \PYG{n+nd}{@UiThreadTest}
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{testActivityScenarioIncReset}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{actualTest}\PYG{o}{.}\PYG{n+na}{testActivityScenarioIncReset}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
    \PYG{o}{.}\PYG{o}{.}\PYG{o}{.}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

Having a modular architecture, such as model-view-adapter, enables us
to test most of the application components in isolation. For example,
our simple unit tests for the POJO bounded counter model still work in
the context of the overall Android app.


\section{Interactive Behaviors and Implicit Concurrency with Internal Timers}
\label{chapter:interactive-behaviors-and-implicit-concurrency-with-internal-timers}

\subsection{Learning objectives}
\label{chapter:id13}\begin{itemize}
\item {} 
Internal events from autonomous timer-based behavior (C)

\item {} 
Modeling recurring and one-shot timers in UML State Machine diagrams (A)

\item {} 
Modeling execution scenarios with UML Collaboration diagrams (A)

\item {} 
Distinguishing between view states and (behavioral) model states (C)

\item {} 
Implementing state-dependent behavior using the State pattern (A)

\item {} 
Managing complexity in application architecture (C)

\item {} 
Distinguishing among passive, reactive, and autonomous model
components (C)

\item {} 
The Model-View-Adapter pattern with autonomous model behavior (C)

\item {} 
Testing components with autonomous behavior and dependencies (A)

\end{itemize}


\subsection{Introduction}
\label{chapter:id14}
In this section, we'll study an application that has richer,
timer-based behaviors compared to the click counter example from the
previous section. Our example will be a countdown timer for cooking
and similar scenarios where we want to be notified when a set amount
of time has elapsed.


\subsection{The functional requirements for a countdown timer}
\label{chapter:the-functional-requirements-for-a-countdown-timer}
Let's start with the functional requirements for the countdown timer,
amounting to a fairly abstract description of its controls and
behavior.

The timer exposes the following controls:
\begin{itemize}
\item {} 
One two-digit display of the form 88.

\item {} 
One multi-function button.

\end{itemize}

The timer behaves as follows:
\begin{itemize}
\item {} 
The timer always displays the remaining time in seconds.

\item {} 
Initially, the timer is stopped and the (remaining) time is zero.

\item {} 
If the button is pressed when the timer is stopped, the time is
incremented by one up to a preset maximum of 99. (The button acts as
an increment button.)

\item {} 
If the time is greater than zero and three seconds elapse from the
most recent time the button was pressed, then the timer beeps once
and starts running.

\item {} 
While running, the timer subtracts one from the time for every
second that elapses.

\item {} 
If the timer is running and the button is pressed, the timer stops
and the time is reset to zero. (The button acts as a cancel button.)

\item {} 
If the timer is running and the time reaches zero by itself (without
the button being pressed), then the timer stops counting down, and
the alarm starts beeping continually and indefinitely.

\item {} 
If the alarm is sounding and the button is pressed, the alarm stops
sounding; the timer is now stopped and the (remaining) time is
zero. (The button acts as a stop button.)

\end{itemize}


\subsection{A graphical user interface (GUI) for a countdown timer}
\label{chapter:a-graphical-user-interface-gui-for-a-countdown-timer}
Our next step is to flesh out the GUI for our timer. For usability,
we'll label the multifunction button with its current function. We'll
also indicate which state the timer is currently in.

The following screenshots show the default scenario where we start up
the timer, add a few seconds, wait for it to start counting down, and
ultimately reach the alarm state.
\begin{figure}[htbp]
\centering
\capstart

\scalebox{0.500000}{\includegraphics{CountdownTimerStoppedZero.png}}
\caption{The countdown timer in the initial stopped state with zero time.}\end{figure}
\begin{figure}[htbp]
\centering
\capstart

\scalebox{0.500000}{\includegraphics{CountdownTimerStoppedNonzero.png}}
\caption{The countdown timer in the stopped state after adding some time.}\end{figure}
\begin{figure}[htbp]
\centering
\capstart

\scalebox{0.500000}{\includegraphics{CountdownTimerRunning.png}}
\caption{The countdown timer in the running state.}\end{figure}
\begin{figure}[htbp]
\centering
\capstart

\scalebox{0.500000}{\includegraphics{CountdownTimerRinging.png}}
\caption{The countdown timer in the alarm ringing state.}\end{figure}


\subsection{Modeling the interactive behavior}
\label{chapter:id15}\begin{figure}[htbp]
\centering
\capstart

\includegraphics{CountdownTimerStates.png}
\caption{The UML state machine diagram modeling the dynamic behavior of the
countdown timer application.}\end{figure}

Let's again try to describe the abstract behavior of the countdown
timer using a UML state machine diagram. As usual, there are various
ways to do this, and our guiding principle is to keep things simple
and close to the informal description of the behavior.

It is easy to see that we need to represent the current counter
value. Once we accept this, we really don't need to distinguish
between the stopped state (with counter value zero) and the counting
state (with counter value greater than zero). The other states that
arise naturally are the running state and the alarm state.

As in the click counter example, these model states map directly to
the view states shown above. Again, the differences among the view
states are very minor and are aimed mostly at usability: A properly
labeled button is a much more effective affordance than an unlabeled
or generically labeled one.

Note that there are two types of (internal) timers at work here:
\begin{itemize}
\item {} 
\emph{one-shot timers}, such as the three-second timer in the stopped
state that gets restarted every time we press the multifunction
button to add time

\item {} 
\emph{recurring timers}, such as the one-second timer in the running
state that fires continually for every second that goes by

\end{itemize}


\subsection{Implementing time-based autonomous behavior}
\label{chapter:implementing-time-based-autonomous-behavior}
While the entirely passive bounded counter behavior from the previous
section was straightforward to implement, the countdown timer includes
autonomous timer-based behaviors that give rise to another level of
complexity.

There are different ways to deal with this behavioral
complexity. Given that we have already expressed the behavior as a
state machine, we can use the \emph{State} software design pattern to
separate state-dependent behavior from overarching handling of
external and internal triggers and actions.

We start by defining a state abstraction. Besides the same common
methods and reference to its surrounding state machine, each state has
a unique identifier.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k+kd}{abstract} \PYG{k+kd}{class} \PYG{n+nc}{TimerState} \PYG{k+kd}{implements} \PYG{n}{TimerUIListener}\PYG{o}{,} \PYG{n}{ClockListener} \PYG{o}{\PYGZob{}}

    \PYG{k+kd}{public} \PYG{n+nf}{TimerState}\PYG{o}{(}\PYG{k+kd}{final} \PYG{n}{TimerStateMachine} \PYG{n}{sm}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{k}{this}\PYG{o}{.}\PYG{n+na}{sm} \PYG{o}{=} \PYG{n}{sm}\PYG{o}{;} \PYG{o}{\PYGZcb{}}

    \PYG{k+kd}{protected} \PYG{k+kd}{final} \PYG{n}{TimerStateMachine} \PYG{n}{sm}\PYG{o}{;}

    \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kd}{final} \PYG{k+kt}{void} \PYG{n}{onStart}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{onEntry}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{onEntry}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{onExit}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{onButtonPress}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{onTick}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{onTimeout}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{public} \PYG{k+kd}{abstract} \PYG{k+kt}{int} \PYG{n+nf}{getId}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

In addition, a state receives UI events and clock ticks. Accordingly,
it implements the corresponding interfaces, which are defined as
follows:

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k+kd}{public} \PYG{k+kd}{interface} \PYG{n+nc}{TimerUIListener} \PYG{o}{\PYGZob{}}
    \PYG{k+kt}{void} \PYG{n+nf}{onStart}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
    \PYG{k+kt}{void} \PYG{n+nf}{onButtonPress}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k+kd}{public} \PYG{k+kd}{interface} \PYG{n+nc}{ClockListener} \PYG{o}{\PYGZob{}}
    \PYG{k+kt}{void} \PYG{n+nf}{onTick}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
    \PYG{k+kt}{void} \PYG{n+nf}{onTimeout}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

As we discussed in section {\hyperref[chapter:sec-events]{\emph{Basic Event-Based User Interaction}}}, Android follows an
event source/listener naming idiom. As our examples illustrate, it is
straightforward to define custom app-specific events that follow this
same convention. Our \code{ClockListener}, for example, combines two
kinds of events within a single interface.

Concrete state classes implement the abstract \code{TimerState}
class. The key parts of the state machine implementation follow:

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{k+kd}{private} \PYG{n}{TimerState} \PYG{n}{state} \PYG{o}{=} \PYG{k}{new} \PYG{n}{TimerState}\PYG{o}{(}\PYG{k}{this}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{c+c1}{// intial pseudo\PYGZhy{}state}
        \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{int} \PYG{n}{getId}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{k}{throw} \PYG{k}{new} \PYG{n}{IllegalStateException}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
    \PYG{o}{\PYGZcb{}}\PYG{o}{;}

    \PYG{k+kd}{protected} \PYG{k+kt}{void} \PYG{n+nf}{setState}\PYG{o}{(}\PYG{k+kd}{final} \PYG{n}{TimerState} \PYG{n}{nextState}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{state}\PYG{o}{.}\PYG{n+na}{onExit}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{state} \PYG{o}{=} \PYG{n}{nextState}\PYG{o}{;}
        \PYG{n}{uiUpdateListener}\PYG{o}{.}\PYG{n+na}{updateState}\PYG{o}{(}\PYG{n}{state}\PYG{o}{.}\PYG{n+na}{getId}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{state}\PYG{o}{.}\PYG{n+na}{onEntry}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
\end{Verbatim}

Let's focus on the stopped state first. In this state, neither is the
clock ticking, nor is the alarm ringing. On every button press, the
remaining running time goes up by one second and the one-shot
three-second idle timeout starts from zero. If three seconds elapse
before another button press, we transition to the running state.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{k+kd}{private} \PYG{k+kd}{final} \PYG{n}{TimerState} \PYG{n}{STOPPED} \PYG{o}{=} \PYG{k}{new} \PYG{n}{TimerState}\PYG{o}{(}\PYG{k}{this}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{onEntry}\PYG{o}{(}\PYG{o}{)}       \PYG{o}{\PYGZob{}} \PYG{n}{timeModel}\PYG{o}{.}\PYG{n+na}{reset}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;} \PYG{n}{updateUIRuntime}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
        \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{onButtonPress}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
            \PYG{n}{clockModel}\PYG{o}{.}\PYG{n+na}{restartTimeout}\PYG{o}{(}\PYG{l+m+mi}{3} \PYG{c+cm}{/* seconds */}\PYG{o}{)}\PYG{o}{;}
            \PYG{n}{timeModel}\PYG{o}{.}\PYG{n+na}{inc}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;} \PYG{n}{updateUIRuntime}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
        \PYG{o}{\PYGZcb{}}
        \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{onTimeout}\PYG{o}{(}\PYG{o}{)}     \PYG{o}{\PYGZob{}} \PYG{n}{setState}\PYG{o}{(}\PYG{n}{RUNNING}\PYG{o}{)}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
        \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{int}  \PYG{n}{getId}\PYG{o}{(}\PYG{o}{)}         \PYG{o}{\PYGZob{}} \PYG{k}{return} \PYG{n}{R}\PYG{o}{.}\PYG{n+na}{string}\PYG{o}{.}\PYG{n+na}{STOPPED}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
    \PYG{o}{\PYGZcb{}}\PYG{o}{;}
\end{Verbatim}

Let's now take a look at the running state. In this state, the clock is
ticking but the alarm is not ringing. With every recurring clock tick,
the remaining running time goes down by one second. If it reaches
zero, we transition to the ringing state. If a button press occurs, we
stop the clock and transition to the stopped state.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{k+kd}{private} \PYG{k+kd}{final} \PYG{n}{TimerState} \PYG{n}{RUNNING} \PYG{o}{=} \PYG{k}{new} \PYG{n}{TimerState}\PYG{o}{(}\PYG{k}{this}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{onEntry}\PYG{o}{(}\PYG{o}{)}       \PYG{o}{\PYGZob{}} \PYG{n}{clockModel}\PYG{o}{.}\PYG{n+na}{startTick}\PYG{o}{(}\PYG{l+m+mi}{1} \PYG{c+cm}{/* second */}\PYG{o}{)}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
        \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{onExit}\PYG{o}{(}\PYG{o}{)}        \PYG{o}{\PYGZob{}} \PYG{n}{clockModel}\PYG{o}{.}\PYG{n+na}{stopTick}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
        \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{onButtonPress}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{setState}\PYG{o}{(}\PYG{n}{STOPPED}\PYG{o}{)}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
        \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{onTick}\PYG{o}{(}\PYG{o}{)}        \PYG{o}{\PYGZob{}}
            \PYG{n}{timeModel}\PYG{o}{.}\PYG{n+na}{dec}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;} \PYG{n}{updateUIRuntime}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
            \PYG{k}{if} \PYG{o}{(}\PYG{n}{timeModel}\PYG{o}{.}\PYG{n+na}{get}\PYG{o}{(}\PYG{o}{)} \PYG{o}{=}\PYG{o}{=} \PYG{l+m+mi}{0}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{setState}\PYG{o}{(}\PYG{n}{RINGING}\PYG{o}{)}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
        \PYG{o}{\PYGZcb{}}
        \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{int}  \PYG{n}{getId}\PYG{o}{(}\PYG{o}{)}         \PYG{o}{\PYGZob{}} \PYG{k}{return} \PYG{n}{R}\PYG{o}{.}\PYG{n+na}{string}\PYG{o}{.}\PYG{n+na}{RUNNING}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
    \PYG{o}{\PYGZcb{}}\PYG{o}{;}
\end{Verbatim}

Finally, in the ringing state, nothing is happening other than the
alarm ringing. If a button press occurs, we stop the alarm and
transition to the stopped state.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{k+kd}{private} \PYG{k+kd}{final} \PYG{n}{TimerState} \PYG{n}{RINGING} \PYG{o}{=} \PYG{k}{new} \PYG{n}{TimerState}\PYG{o}{(}\PYG{k}{this}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{onEntry}\PYG{o}{(}\PYG{o}{)}       \PYG{o}{\PYGZob{}} \PYG{n}{uiUpdateListener}\PYG{o}{.}\PYG{n+na}{ringAlarm}\PYG{o}{(}\PYG{k+kc}{true}\PYG{o}{)}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
        \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{onExit}\PYG{o}{(}\PYG{o}{)}        \PYG{o}{\PYGZob{}} \PYG{n}{uiUpdateListener}\PYG{o}{.}\PYG{n+na}{ringAlarm}\PYG{o}{(}\PYG{k+kc}{false}\PYG{o}{)}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
        \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{onButtonPress}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{setState}\PYG{o}{(}\PYG{n}{STOPPED}\PYG{o}{)}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
        \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{int}  \PYG{n}{getId}\PYG{o}{(}\PYG{o}{)}         \PYG{o}{\PYGZob{}} \PYG{k}{return} \PYG{n}{R}\PYG{o}{.}\PYG{n+na}{string}\PYG{o}{.}\PYG{n+na}{RINGING}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
    \PYG{o}{\PYGZcb{}}\PYG{o}{;}
\end{Verbatim}


\subsection{Managing structural complexity}
\label{chapter:managing-structural-complexity}
We can again describe the architecture of the countdown timer Android
app as an instance of the Model-View-Adapter (MVA) architectural
pattern. In figure {\hyperref[chapter:fig-autonomousmodelviewadapter]{\emph{Countdown timer: Model-View-Adapter architecture}}}, solid arrows
represent (synchronous) method invocation, and dashed arrows represent
(asynchronous) events. Here, both the view components and the model's
autonomous timer send events to the adapter.

Figures {\hyperref[chapter:fig-countdowntimermvacollab1]{\emph{Countdown timer: user input scenario}}} and
{\hyperref[chapter:fig-countdowntimermvacollab2]{\emph{Countdown timer: autonomous scenario}}} illustrate the two main
interaction scenarios side-by-side.

The user input scenario illustrates the system's end-to-end response
to a button press. The internal timeout gets set in response to a
button press. When the timeout event actually occurs, corresponding to
an invocation of the \emph{onTimeout} method, the system responds by
transitioning to the running state.

By contrast, the autonomous scenario shows the system's end-to-end
response to a recurring internal clock tick, corresponding to an
invocation of the \emph{onTick} method. When the remaining time reaches
zero, the system responds by transitioning to the alarm-ringing state.
\begin{figure}[htbp]
\centering
\capstart

\scalebox{1.000000}{\includegraphics{AutonomousModelViewAdapter.png}}
\caption{Countdown timer: Model-View-Adapter architecture}\label{chapter:fig-autonomousmodelviewadapter}\end{figure}
\begin{figure}[htbp]
\centering
\capstart

\scalebox{1.000000}{\includegraphics{CountdownTimerMVACollab1.png}}
\caption{Countdown timer: user input scenario}\label{chapter:fig-countdowntimermvacollab1}\end{figure}
\begin{figure}[htbp]
\centering
\capstart

\scalebox{1.000000}{\includegraphics{CountdownTimerMVACollab2.png}}
\caption{Countdown timer: autonomous scenario}\label{chapter:fig-countdowntimermvacollab2}\end{figure}


\subsection{Testing more complex GUI applications}
\label{chapter:testing-more-complex-gui-applications}
As we develop more complex applications, we increasingly benefit from
thorough automated testing. In particular, there are different
structural levels of testing: component-level unit testing,
integration testing, and system testing.

In addition, as our application grows in complexity, so does our test
code, so it makes sense to use good software engineering practice in
the development of our test code. Accordingly, software design
patterns for test code have emerged, such as the \emph{Testclass
Superclass} pattern {[}XUnitPatterns{]} we use in section {\hyperref[chapter:sec-events]{\emph{Basic Event-Based User Interaction}}}.


\subsubsection{Unit-testing passive model components}
\label{chapter:unit-testing-passive-model-components}
The time model is simple passive component, so we can test it very
similarly as the bounded counter model in section {\hyperref[chapter:sec-events]{\emph{Basic Event-Based User Interaction}}}.


\subsubsection{Unit-testing components with autonomous behavior}
\label{chapter:unit-testing-components-with-autonomous-behavior}
Testing components with autonomous behavior is more challenging
because we have to attach some kind of probe to observe the
behavior.

Let's try this on our clock model. The following test verifies that a
stopped clock does not emit any tick events.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{n+nd}{@Test}
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{testStopped}\PYG{o}{(}\PYG{o}{)} \PYG{k+kd}{throws} \PYG{n}{InterruptedException} \PYG{o}{\PYGZob{}}
        \PYG{k+kd}{final} \PYG{n}{AtomicInteger} \PYG{n}{i} \PYG{o}{=} \PYG{k}{new} \PYG{n}{AtomicInteger}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{model}\PYG{o}{.}\PYG{n+na}{setClockListener}\PYG{o}{(}\PYG{k}{new} \PYG{n}{ClockListener}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
            \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{onTick}\PYG{o}{(}\PYG{o}{)}    \PYG{o}{\PYGZob{}} \PYG{n}{i}\PYG{o}{.}\PYG{n+na}{incrementAndGet}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
            \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{onTimeout}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{\PYGZcb{}}
        \PYG{o}{\PYGZcb{}}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{Thread}\PYG{o}{.}\PYG{n+na}{sleep}\PYG{o}{(}\PYG{l+m+mi}{5500}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{n}{i}\PYG{o}{.}\PYG{n+na}{get}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
\end{Verbatim}

And this one verifies that a running clock emits roughly one tick
event per second.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{n+nd}{@Test}
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{testRunning}\PYG{o}{(}\PYG{o}{)} \PYG{k+kd}{throws} \PYG{n}{InterruptedException} \PYG{o}{\PYGZob{}}
        \PYG{k+kd}{final} \PYG{n}{AtomicInteger} \PYG{n}{i} \PYG{o}{=} \PYG{k}{new} \PYG{n}{AtomicInteger}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{model}\PYG{o}{.}\PYG{n+na}{setClockListener}\PYG{o}{(}\PYG{k}{new} \PYG{n}{ClockListener}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
            \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{onTick}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{i}\PYG{o}{.}\PYG{n+na}{incrementAndGet}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
            \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{onTimeout}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{\PYGZcb{}}
        \PYG{o}{\PYGZcb{}}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{model}\PYG{o}{.}\PYG{n+na}{startTick}\PYG{o}{(}\PYG{l+m+mi}{1} \PYG{c+cm}{/* second */}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{Thread}\PYG{o}{.}\PYG{n+na}{sleep}\PYG{o}{(}\PYG{l+m+mi}{5500}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{model}\PYG{o}{.}\PYG{n+na}{stopTick}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{5}\PYG{o}{,} \PYG{n}{i}\PYG{o}{.}\PYG{n+na}{get}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
\end{Verbatim}


\subsubsection{Unit-testing components with complex dependencies}
\label{chapter:unit-testing-components-with-complex-dependencies}
Some model components have complex dependencies. Our timer's state
machine model, e.g., expects implementations of the interfaces
\code{TimeModel}, \code{ClockModel}, and \code{TimerUIUpdateListener} to be
present.  We can achieve this by manually implementing a so-called
\emph{mock object} that unifies these three dependencies of the timer state
machine model, corresponding to the three interfaces this mock object
implements.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k+kd}{class} \PYG{n+nc}{UnifiedMockDependency} \PYG{k+kd}{implements} \PYG{n}{TimeModel}\PYG{o}{,} \PYG{n}{ClockModel}\PYG{o}{,} \PYG{n}{TimerUIUpdateListener} \PYG{o}{\PYGZob{}}

    \PYG{k+kd}{private} \PYG{k+kt}{int} \PYG{n}{timeValue} \PYG{o}{=} \PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{n}{stateId} \PYG{o}{=} \PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{;}
    \PYG{k+kd}{private} \PYG{k+kt}{int} \PYG{n}{runningTime} \PYG{o}{=} \PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{n}{idleTime} \PYG{o}{=} \PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{;}
    \PYG{k+kd}{private} \PYG{k+kt}{boolean} \PYG{n}{started} \PYG{o}{=} \PYG{k+kc}{false}\PYG{o}{,} \PYG{n}{ringing} \PYG{o}{=} \PYG{k+kc}{false}\PYG{o}{;}

    \PYG{k+kd}{public} \PYG{k+kt}{int}     \PYG{n+nf}{getTime}\PYG{o}{(}\PYG{o}{)}   \PYG{o}{\PYGZob{}} \PYG{k}{return} \PYG{n}{timeValue}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{public} \PYG{k+kt}{int}     \PYG{n+nf}{getState}\PYG{o}{(}\PYG{o}{)}  \PYG{o}{\PYGZob{}} \PYG{k}{return} \PYG{n}{stateId}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{public} \PYG{k+kt}{boolean} \PYG{n+nf}{isStarted}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{k}{return} \PYG{n}{started}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{public} \PYG{k+kt}{boolean} \PYG{n+nf}{isRinging}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{k}{return} \PYG{n}{ringing}\PYG{o}{;} \PYG{o}{\PYGZcb{}}

    \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{updateTime}\PYG{o}{(}\PYG{k+kd}{final} \PYG{k+kt}{int} \PYG{n}{timeValue}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{k}{this}\PYG{o}{.}\PYG{n+na}{timeValue} \PYG{o}{=} \PYG{n}{timeValue}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
    \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{updateState}\PYG{o}{(}\PYG{k+kd}{final} \PYG{k+kt}{int} \PYG{n}{stateId}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{k}{this}\PYG{o}{.}\PYG{n+na}{stateId} \PYG{o}{=} \PYG{n}{stateId}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
    \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{ringAlarm}\PYG{o}{(}\PYG{k+kt}{boolean} \PYG{n}{b}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{ringing} \PYG{o}{=} \PYG{n}{b}\PYG{o}{;} \PYG{o}{\PYGZcb{}}

    \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{setClockListener}\PYG{o}{(}\PYG{n}{ClockListener} \PYG{n}{listener}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{k}{throw} \PYG{k}{new} \PYG{n+nf}{UnsupportedOperationException}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
    \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{startTick}\PYG{o}{(}\PYG{k+kd}{final} \PYG{k+kt}{int} \PYG{n}{period}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{started} \PYG{o}{=} \PYG{k+kc}{true}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
    \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{stopTick}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{started} \PYG{o}{=} \PYG{k+kc}{false}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
    \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{restartTimeout}\PYG{o}{(}\PYG{k+kd}{final} \PYG{k+kt}{int} \PYG{n}{period}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{\PYGZcb{}}

    \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{reset}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{runningTime} \PYG{o}{=} \PYG{l+m+mi}{0}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
    \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{inc}\PYG{o}{(}\PYG{o}{)}   \PYG{o}{\PYGZob{}} \PYG{k}{if} \PYG{o}{(}\PYG{n}{runningTime} \PYG{o}{!}\PYG{o}{=} \PYG{l+m+mi}{99}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{runningTime}\PYG{o}{+}\PYG{o}{+}\PYG{o}{;} \PYG{o}{\PYGZcb{}} \PYG{o}{\PYGZcb{}}
    \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{dec}\PYG{o}{(}\PYG{o}{)}   \PYG{o}{\PYGZob{}} \PYG{k}{if} \PYG{o}{(}\PYG{n}{runningTime} \PYG{o}{!}\PYG{o}{=} \PYG{l+m+mi}{0}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{runningTime}\PYG{o}{\PYGZhy{}}\PYG{o}{\PYGZhy{}}\PYG{o}{;} \PYG{o}{\PYGZcb{}} \PYG{o}{\PYGZcb{}}
    \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{int}  \PYG{n}{get}\PYG{o}{(}\PYG{o}{)}   \PYG{o}{\PYGZob{}} \PYG{k}{return} \PYG{n}{runningTime}\PYG{o}{;} \PYG{o}{\PYGZcb{}}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

The instance variables and corresponding getters enable us to test
whether the SUT produced the expected state changes in the mock
object. The three remaining blocks of methods correspond to the three
implemented interfaces, respectively.

Now we can write tests to verify actual scenarios. In the following
scenario, time is 0, press button once, expect time 1, press button
198 times (the max time is 99), expect time 99, wait 3 seconds, check
if running, wait 50 seconds, expect time 49 (99-50), wait 49 seconds,
expect time 0, check if ringing, wait 3 more seconds (just in case),
check if still ringing, press button to turn off ring, make sure
ringing stopped and state is stopped.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{n+nd}{@Test}
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{testScenarioRun2}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{n}{R}\PYG{o}{.}\PYG{n+na}{string}\PYG{o}{.}\PYG{n+na}{STOPPED}\PYG{o}{,} \PYG{n}{dependency}\PYG{o}{.}\PYG{n+na}{getState}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{model}\PYG{o}{.}\PYG{n+na}{onButtonPress}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTimeEquals}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{n}{R}\PYG{o}{.}\PYG{n+na}{string}\PYG{o}{.}\PYG{n+na}{STOPPED}\PYG{o}{,} \PYG{n}{dependency}\PYG{o}{.}\PYG{n+na}{getState}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{onButtonRepeat}\PYG{o}{(}\PYG{n}{MAX\PYGZus{}TIME} \PYG{o}{*} \PYG{l+m+mi}{2}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTimeEquals}\PYG{o}{(}\PYG{n}{MAX\PYGZus{}TIME}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{onTickRepeat}\PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{n}{R}\PYG{o}{.}\PYG{n+na}{string}\PYG{o}{.}\PYG{n+na}{RUNNING}\PYG{o}{,} \PYG{n}{dependency}\PYG{o}{.}\PYG{n+na}{getState}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{onTickRepeat}\PYG{o}{(}\PYG{l+m+mi}{50}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTimeEquals}\PYG{o}{(}\PYG{n}{MAX\PYGZus{}TIME} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{50}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{onTickRepeat}\PYG{o}{(}\PYG{l+m+mi}{49}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTimeEquals}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{n}{R}\PYG{o}{.}\PYG{n+na}{string}\PYG{o}{.}\PYG{n+na}{RINGING}\PYG{o}{,} \PYG{n}{dependency}\PYG{o}{.}\PYG{n+na}{getState}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{dependency}\PYG{o}{.}\PYG{n+na}{isRinging}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{onTickRepeat}\PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{n}{R}\PYG{o}{.}\PYG{n+na}{string}\PYG{o}{.}\PYG{n+na}{RINGING}\PYG{o}{,} \PYG{n}{dependency}\PYG{o}{.}\PYG{n+na}{getState}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{dependency}\PYG{o}{.}\PYG{n+na}{isRinging}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{model}\PYG{o}{.}\PYG{n+na}{onButtonPress}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertFalse}\PYG{o}{(}\PYG{n}{dependency}\PYG{o}{.}\PYG{n+na}{isRinging}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{assertEquals}\PYG{o}{(}\PYG{n}{R}\PYG{o}{.}\PYG{n+na}{string}\PYG{o}{.}\PYG{n+na}{STOPPED}\PYG{o}{,} \PYG{n}{dependency}\PYG{o}{.}\PYG{n+na}{getState}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
\end{Verbatim}

Note that this happens \emph{in fake time} (fast-forward) because we can
make the rate of the clock ticks as fast as the state machine can keep
up.

\begin{notice}{note}{Note:}
There are also various mocking frameworks, such as Mockito
and JMockit, which can automatically generate mock objects
that represent component dependencies from interfaces and
provide APIs or domain-specific languages for specifying
test expectations.
\end{notice}


\subsubsection{Programmatic system testing of the app}
\label{chapter:programmatic-system-testing-of-the-app}
The following is a system test of the application with all of its real
component present. It verifies the following scenario \emph{in real time}:
time is 0, press button five times, expect time 5, wait 3 seconds,
expect time 5, wait 3 more seconds, expect time 2, press stopTick
button to reset time, expect time 0. (includes all state transitions
as assertions).

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{n+nd}{@Test}
    \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{testScenarioRun2}\PYG{o}{(}\PYG{o}{)} \PYG{k+kd}{throws} \PYG{n}{Throwable} \PYG{o}{\PYGZob{}}
        \PYG{n}{getActivity}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{runOnUiThread}\PYG{o}{(}\PYG{k}{new} \PYG{n}{Runnable}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{run}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
            \PYG{n}{assertEquals}\PYG{o}{(}\PYG{n}{STOPPED}\PYG{o}{,} \PYG{n}{getStateValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
            \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{n}{getDisplayedValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
            \PYG{k}{for} \PYG{o}{(}\PYG{k+kt}{int} \PYG{n}{i} \PYG{o}{=} \PYG{l+m+mi}{0}\PYG{o}{;} \PYG{n}{i} \PYG{o}{\PYGZlt{}} \PYG{l+m+mi}{5}\PYG{o}{;} \PYG{n}{i}\PYG{o}{+}\PYG{o}{+}\PYG{o}{)} \PYG{o}{\PYGZob{}}
                \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{performClick}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
            \PYG{o}{\PYGZcb{}}
            \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{5}\PYG{o}{,} \PYG{n}{getDisplayedValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{o}{\PYGZcb{}}\PYG{o}{\PYGZcb{}}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{Thread}\PYG{o}{.}\PYG{n+na}{sleep}\PYG{o}{(}\PYG{l+m+mi}{3200}\PYG{o}{)}\PYG{o}{;} \PYG{c+c1}{// \PYGZlt{}\PYGZhy{}\PYGZhy{} do not run this in the UI thread!}
        \PYG{n}{runUiThreadTasks}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{getActivity}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{runOnUiThread}\PYG{o}{(}\PYG{k}{new} \PYG{n}{Runnable}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{run}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
            \PYG{n}{assertEquals}\PYG{o}{(}\PYG{n}{RUNNING}\PYG{o}{,} \PYG{n}{getStateValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
            \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{5}\PYG{o}{,} \PYG{n}{getDisplayedValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{o}{\PYGZcb{}}\PYG{o}{\PYGZcb{}}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{Thread}\PYG{o}{.}\PYG{n+na}{sleep}\PYG{o}{(}\PYG{l+m+mi}{3200}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{runUiThreadTasks}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{getActivity}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{runOnUiThread}\PYG{o}{(}\PYG{k}{new} \PYG{n}{Runnable}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n+nd}{@Override} \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n}{run}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
            \PYG{n}{assertEquals}\PYG{o}{(}\PYG{n}{RUNNING}\PYG{o}{,} \PYG{n}{getStateValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
            \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{2}\PYG{o}{,} \PYG{n}{getDisplayedValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
            \PYG{n}{assertTrue}\PYG{o}{(}\PYG{n}{getButton}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{performClick}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
            \PYG{n}{assertEquals}\PYG{o}{(}\PYG{n}{STOPPED}\PYG{o}{,} \PYG{n}{getStateValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{o}{\PYGZcb{}}\PYG{o}{\PYGZcb{}}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
\end{Verbatim}

As in section {\hyperref[chapter:sec-events]{\emph{Basic Event-Based User Interaction}}}, we can run this test as an
in-container instrumentation test or out-of-container using a
simulated environment such as Robolectric.


\section{Keeping the User Interface Responsive with Asynchronous Activities}
\label{chapter:keeping-the-user-interface-responsive-with-asynchronous-activities}

\subsection{Learning objectives}
\label{chapter:id16}\begin{itemize}
\item {} 
Designing responsive interactive applications (A)

\item {} 
Design choices for user interface toolkits such as Android (C)

\item {} 
The difference between events and activities (C)

\item {} 
Using asynchronous tasks for long-running activities (A)

\item {} 
Reporting progress to the user (A)

\item {} 
Responding to cancelation requests (A)

\end{itemize}


\subsection{Introduction}
\label{chapter:id17}
In this section, we'll explore the issues that arise when we use a GUI
to control long-running, processor-bound activities. In particular,
we'll want to make sure the GUI stays responsive even in such
scenarios and the activity supports progress reporting and
cancelation. Our running example will be a simple app for checking
whether a number is prime.


\subsection{The functional requirements for the prime checker app}
\label{chapter:the-functional-requirements-for-the-prime-checker-app}
The functional requirements for this app are as follows: \emph{The app
allows us to enter a number in a text field. When we press the ``check''
button, the app checks whether the number we entered is prime. When we
press the ``cancel'' button, the ongoing check(s) are discontinued.}
\begin{figure}[htbp]
\centering
\capstart

\scalebox{0.500000}{\includegraphics{PrimecheckerAndroid.png}}
\caption{Screenshot of an Android app for checking prime numbers}\end{figure}

To check whether a number is prime, we can use this brute-force
algorithm.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{k+kd}{protected} \PYG{k+kt}{boolean} \PYG{n+nf}{isPrime}\PYG{o}{(}\PYG{k+kd}{final} \PYG{k+kt}{long} \PYG{n}{i}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{k}{if} \PYG{o}{(}\PYG{n}{i} \PYG{o}{\PYGZlt{}} \PYG{l+m+mi}{2}\PYG{o}{)} \PYG{k}{return} \PYG{k+kc}{false}\PYG{o}{;}
        \PYG{k+kd}{final} \PYG{k+kt}{long} \PYG{n}{half} \PYG{o}{=} \PYG{n}{i} \PYG{o}{/} \PYG{l+m+mi}{2}\PYG{o}{;}
        \PYG{k}{for} \PYG{o}{(}\PYG{k+kt}{long} \PYG{n}{k} \PYG{o}{=} \PYG{l+m+mi}{2}\PYG{o}{;} \PYG{n}{k} \PYG{o}{\PYGZlt{}}\PYG{o}{=} \PYG{n}{half}\PYG{o}{;} \PYG{n}{k} \PYG{o}{+}\PYG{o}{=} \PYG{l+m+mi}{1}\PYG{o}{)} \PYG{o}{\PYGZob{}}
            \PYG{k}{if} \PYG{o}{(}\PYG{n}{isCancelled}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\textbar{}}\PYG{o}{\textbar{}} \PYG{n}{i} \PYG{o}{\PYGZpc{}} \PYG{n}{k} \PYG{o}{=}\PYG{o}{=} \PYG{l+m+mi}{0}\PYG{o}{)} \PYG{k}{return} \PYG{k+kc}{false}\PYG{o}{;}
            \PYG{n}{publishProgress}\PYG{o}{(}\PYG{o}{(}\PYG{k+kt}{int}\PYG{o}{)} \PYG{o}{(}\PYG{n}{k} \PYG{o}{*} \PYG{l+m+mi}{100} \PYG{o}{/} \PYG{n}{half}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
        \PYG{o}{\PYGZcb{}}
        \PYG{k}{return} \PYG{k+kc}{true}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
\end{Verbatim}

For now, let's ignore the \code{isCancelled} and \code{updateProgress}
methods and agree to discuss their significance later in this section.

While this is not a good prime checker implementation, the app will
allow us to explore and discuss different ways to run one or more such
checks. In particular, the fact that the algorithm hogs the processor
makes it an effective running example for discussing whether to move
processor-bound activities to the background (or remote servers).

\begin{notice}{note}{Note:}
In this chapter, we focus on tasks that run locally in the
foreground or background. In a future submission, we will
explore the possibility of offloading compute- and
storage-intensive tasks to remote web services.
\end{notice}


\subsection{The problem with foreground tasks}
\label{chapter:the-problem-with-foreground-tasks}
As a first attempt, we now can run the \code{isPrime} method from within
our event listener in the current thread of execution (the main GUI
thread).

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
                \PYG{k+kd}{final} \PYG{n}{PrimeCheckerTask} \PYG{n}{t} \PYG{o}{=} \PYG{k}{new} \PYG{n}{PrimeCheckerTask}\PYG{o}{(}\PYG{n}{progressBars}\PYG{o}{[}\PYG{l+m+mi}{0}\PYG{o}{]}\PYG{o}{,} \PYG{n}{input}\PYG{o}{)}\PYG{o}{;}
                \PYG{n}{localTasks}\PYG{o}{.}\PYG{n+na}{add}\PYG{o}{(}\PYG{n}{t}\PYG{o}{)}\PYG{o}{;}
                \PYG{n}{t}\PYG{o}{.}\PYG{n+na}{onPreExecute}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
                \PYG{k+kd}{final} \PYG{k+kt}{boolean} \PYG{n}{result} \PYG{o}{=} \PYG{n}{t}\PYG{o}{.}\PYG{n+na}{isPrime}\PYG{o}{(}\PYG{n}{number}\PYG{o}{)}\PYG{o}{;}
                \PYG{n}{t}\PYG{o}{.}\PYG{n+na}{onPostExecute}\PYG{o}{(}\PYG{n}{result}\PYG{o}{)}\PYG{o}{;}
                \PYG{n}{localTasks}\PYG{o}{.}\PYG{n+na}{clear}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
\end{Verbatim}

The methods \code{onPreExecute} and \code{onPostExecute} are for resetting
the user interface and displaying the result.

This approach works for very small numbers. For larger numbers,
however, the user interface freezes noticeably while the prime number
check is going on, so it does not respond to pressing the cancel
button. There is no progress reporting either: The progress bar jumps
from zero to 100 when the check finishes.


\subsection{The single-threaded user interface model}
\label{chapter:the-single-threaded-user-interface-model}
The behavior we are observing is a consequence of Android's design
decision to keep the user interface single-threaded. In this design,
all UI events, including user inputs such as button presses and mouse
moves, outputs such as changes to text fields, progress bar updates,
and other component repaints, and internal timers, are processed
sequentially by a single thread, known in Android as the \emph{main thread}
(or UI thread). We will say \emph{UI thread} for greater clarity.

To process an event completely, the UI thread needs to dispatch the
event to any event listener(s) attached to the event source
component. Accordingly, single-threaded UI designs typically come with
two rules:
\begin{enumerate}
\item {} 
To ensure responsiveness, code running on the UI thread must never
block.

\item {} 
To ensure thread-safety, only code running on the UI thread is
allowed to access the UI components.

\end{enumerate}

In interactive applications, running for a long time is almost as bad
as blocking indefinitely on, say, user input. To understand exactly
what is happening, let's focus on the point that events are processed
sequentially in our scenario of entering a number and attempting to
cancel the ongoing check.
\begin{itemize}
\item {} 
The user enters the number to be checked.

\item {} 
The user presses the check button.

\item {} 
To process this event, the UI thread runs the attached listener,
which checks whether the number is prime.

\item {} 
While the UI thread running the listener, all other incoming UI
events---pressing the cancel button, updating the progress bar,
changing the background color of the input field, etc.---are
\emph{queued} sequentially.

\item {} 
Once the UI thread is done running the listener, it will process the
remaining events on the queue. At this point, the cancel button has
no effect anymore, and we will instantly see the progress bar jump
to 100\% and the background color of the input field change according
to the result of the check.

\end{itemize}

So why doesn't Android simply handle incoming events concurrently,
say, each in its own thread? The main reason not to do this is that it
greatly complicates the design while at the same time sending us back
to square one in most scenarios: Because the UI components are a
shared resource, to ensure thread safety in the presence of race
conditions to access the UI, we would now have to use mutual exclusion
in every event listener that accesses a UI component. Because that is
what event listener typically do, in practice, mutual exclusion would
amount to bringing back a sequential order. So we would have greatly
complicated the whole model without achieving significantly greater
concurrency in our system.

\begin{notice}{note}{Note:}
Many other GUI toolkits, such as Java Swing, are also based
on a single-threaded design for similar reasons as
Android. There are also single-threaded server designs. The
software design pattern common to these designs is known as
\emph{Reactor} {[}POSA2{]}.
\end{notice}

There are two main approaches to keeping the UI from freezing while a
long-running activity is going on.


\subsection{Breaking up an activity into small units of work}
\label{chapter:breaking-up-an-activity-into-small-units-of-work}\label{chapter:sec-singlethreaded}
The first approach is still single-threaded: We break up the
long-running activity into very small units of work to be executed
directly by the event-handling thread. When the current chunk is about
to finish, it schedules the next unit of work for execution on the
event-handling thread. Once the next unit of work runs, it first
checks whether a cancelation request has come in. If so, it simply
will not continue, otherwise it will do its work and then schedule its
successor. This approach allows other events, such as reporting
progress or pressing the cancel button, to get in between two
consecutive units of work and will keep the UI responsive as long as
each unit executes fast enough.

Now, in the same scenario as above---entering a number and attempting
to cancel the ongoing check---the behavior will be much more
responsive:
\begin{itemize}
\item {} 
The user enters the number to be checked.

\item {} 
The user presses the check button.

\item {} 
To process this event, the UI thread runs the attached listener,
which makes a little bit of progress toward checking whether the
number is prime and then schedules the next unit of work on the
event queue.

\item {} 
Meanwhile, the user has pressed the cancel button, so this event is
on the event queue \emph{before} the next unit of work toward checking
the number.

\item {} 
Once the UI thread is done running the first (very short) unit of
work, it will run the event listener attached to the cancel button,
which will prevent further units of work from running.

\end{itemize}


\subsection{Asynchronous tasks to the rescue}
\label{chapter:asynchronous-tasks-to-the-rescue}
The second approach is typically multi-threaded: We represent the
entire activity as a separate asynchronous task. Because this is such
a common scenario, Android provides the abstract class \code{AsyncTask}
for this purpose.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k+kd}{public} \PYG{k+kd}{abstract} \PYG{k+kd}{class} \PYG{n+nc}{AsyncTask}\PYG{o}{\PYGZlt{}}\PYG{n}{Params}\PYG{o}{,} \PYG{n}{Progress}\PYG{o}{,} \PYG{n}{Result}\PYG{o}{\PYGZgt{}} \PYG{o}{\PYGZob{}}
    \PYG{k+kd}{protected} \PYG{k+kt}{void} \PYG{n+nf}{onPreExecute}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{protected} \PYG{k+kd}{abstract} \PYG{n}{Result} \PYG{n+nf}{doInBackground}\PYG{o}{(}\PYG{n}{Params}\PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \PYG{n}{params}\PYG{o}{)}\PYG{o}{;}
    \PYG{k+kd}{protected} \PYG{k+kt}{void} \PYG{n+nf}{onProgressUpdate}\PYG{o}{(}\PYG{n}{Progress}\PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \PYG{n}{values}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{protected} \PYG{k+kt}{void} \PYG{n+nf}{onPostExecute}\PYG{o}{(}\PYG{n}{Result} \PYG{n}{result}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{protected} \PYG{k+kt}{void} \PYG{n+nf}{onCancelled}\PYG{o}{(}\PYG{n}{Result} \PYG{n}{result}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{protected} \PYG{k+kd}{final} \PYG{k+kt}{void} \PYG{n+nf}{publishProgress}\PYG{o}{(}\PYG{n}{Progress}\PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \PYG{n}{values}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{public} \PYG{k+kd}{final} \PYG{k+kt}{boolean} \PYG{n+nf}{isCancelled}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{public} \PYG{k+kd}{final} \PYG{n}{AsyncTask}\PYG{o}{\PYGZlt{}}\PYG{o}{.}\PYG{o}{.}\PYG{o}{.}\PYG{o}{\PYGZgt{}} \PYG{n+nf}{executeOnExecutor}\PYG{o}{(}\PYG{n}{Executor} \PYG{n}{exec}\PYG{o}{,} \PYG{n}{Params}\PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \PYG{n}{params}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \PYG{o}{\PYGZcb{}}
    \PYG{k+kd}{public} \PYG{k+kd}{final} \PYG{k+kt}{boolean} \PYG{n+nf}{cancel}\PYG{o}{(}\PYG{k+kt}{boolean} \PYG{n}{mayInterruptIfRunning}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \PYG{o}{\PYGZcb{}}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

The three generic type parameters are \code{Params}, the type of the
arguments of the activity; \code{Progress}, they type of the progress
values reported while the activity runs in the background, and
\code{Result}, the result type of the background activity. Not all three
type parameters have to be used, and we can use the type \code{Void} to
mark a type parameter as unused.

When an asynchronous task is executed, the task goes through the
following lifecycle:
\begin{itemize}
\item {} 
\code{onPreExecute} runs on the UI thread and is used to set up
the task in a thread-safe manner.

\item {} 
\code{doInBackground(Params...)} performs the actual task. Within
this method, we can report progress using
\code{publishProgress(Progress...)} and check for cancelation using \code{isCancelled()}.

\item {} 
\code{onProgressUpdate(Progress...)} is scheduled on the UI thread
whenever the background task reports progress and runs whenever
the UI thread gets to this event. Typically, we use this method
to advance the progress bar or display progress to the user in
some other form.

\item {} 
\code{onPostExecute(Result)}, receives the result of the background
task as an argument and runs on the UI thread after the
background task finishes.

\end{itemize}


\subsection{Using \texttt{AsyncTask} in the prime number checker}
\label{chapter:using-asynctask-in-the-prime-number-checker}
We set up the corresponding asynchronous task with an input of type
\code{Long}, progress of type \code{Integer}, and result of type
\code{Boolean}.  In addition, the task has access to the progress bar and
input text field in the Android GUI for reporting progress and
results, respectively.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k+kd}{public} \PYG{k+kd}{class} \PYG{n+nc}{PrimeCheckerTask} \PYG{k+kd}{extends} \PYG{n}{AsyncTask}\PYG{o}{\PYGZlt{}}\PYG{n}{Long}\PYG{o}{,} \PYG{n}{Integer}\PYG{o}{,} \PYG{n}{Boolean}\PYG{o}{\PYGZgt{}} \PYG{o}{\PYGZob{}}

    \PYG{k+kd}{private} \PYG{k+kd}{final} \PYG{n}{ProgressBar} \PYG{n}{progressBar}\PYG{o}{;}

    \PYG{k+kd}{private} \PYG{k+kd}{final} \PYG{n}{TextView} \PYG{n}{input}\PYG{o}{;}

    \PYG{k+kd}{public} \PYG{n+nf}{PrimeCheckerTask}\PYG{o}{(}\PYG{k+kd}{final} \PYG{n}{ProgressBar} \PYG{n}{progressBar}\PYG{o}{,} \PYG{k+kd}{final} \PYG{n}{TextView} \PYG{n}{input}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{k}{this}\PYG{o}{.}\PYG{n+na}{progressBar} \PYG{o}{=} \PYG{n}{progressBar}\PYG{o}{;}
        \PYG{k}{this}\PYG{o}{.}\PYG{n+na}{input} \PYG{o}{=} \PYG{n}{input}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
\end{Verbatim}

The centerpiece of our solution is to invoke the \code{isPrime} method
from the main method of the task, \code{doInBackground}.  The auxiliary
methods \code{isCancelled} and \code{publishProgress} we saw earlier in the
implementation of \code{isPrime} are for checking for requests to cancel
the current task and updating the progress bar,
respectively. \code{doInBackground} and the other lifecycle methods are
implemented here:

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
    \PYG{n+nd}{@Override} \PYG{k+kd}{protected} \PYG{k+kt}{void} \PYG{n}{onPreExecute}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{progressBar}\PYG{o}{.}\PYG{n+na}{setMax}\PYG{o}{(}\PYG{l+m+mi}{100}\PYG{o}{)}\PYG{o}{;}
        \PYG{n}{input}\PYG{o}{.}\PYG{n+na}{setBackgroundColor}\PYG{o}{(}\PYG{n}{Color}\PYG{o}{.}\PYG{n+na}{YELLOW}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}

    \PYG{n+nd}{@Override} \PYG{k+kd}{protected} \PYG{n}{Boolean} \PYG{n}{doInBackground}\PYG{o}{(}\PYG{k+kd}{final} \PYG{n}{Long}\PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \PYG{n}{params}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{k}{if} \PYG{o}{(}\PYG{n}{params}\PYG{o}{.}\PYG{n+na}{length} \PYG{o}{!}\PYG{o}{=} \PYG{l+m+mi}{1}\PYG{o}{)}
            \PYG{k}{throw} \PYG{k}{new} \PYG{n+nf}{IllegalArgumentException}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}exactly one argument expected\PYGZdq{}}\PYG{o}{)}\PYG{o}{;}
        \PYG{k}{return} \PYG{n+nf}{isPrime}\PYG{o}{(}\PYG{n}{params}\PYG{o}{[}\PYG{l+m+mi}{0}\PYG{o}{]}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}

    \PYG{n+nd}{@Override} \PYG{k+kd}{protected} \PYG{k+kt}{void} \PYG{n}{onProgressUpdate}\PYG{o}{(}\PYG{k+kd}{final} \PYG{n}{Integer}\PYG{o}{.}\PYG{o}{.}\PYG{o}{.} \PYG{n}{values}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{progressBar}\PYG{o}{.}\PYG{n+na}{setProgress}\PYG{o}{(}\PYG{n}{values}\PYG{o}{[}\PYG{l+m+mi}{0}\PYG{o}{]}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}

    \PYG{n+nd}{@Override} \PYG{k+kd}{protected} \PYG{k+kt}{void} \PYG{n}{onPostExecute}\PYG{o}{(}\PYG{k+kd}{final} \PYG{n}{Boolean} \PYG{n}{result}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{input}\PYG{o}{.}\PYG{n+na}{setBackgroundColor}\PYG{o}{(}\PYG{n}{result} \PYG{o}{?} \PYG{n}{Color}\PYG{o}{.}\PYG{n+na}{GREEN} \PYG{o}{:} \PYG{n}{Color}\PYG{o}{.}\PYG{n+na}{RED}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}

    \PYG{n+nd}{@Override} \PYG{k+kd}{protected} \PYG{k+kt}{void} \PYG{n}{onCancelled}\PYG{o}{(}\PYG{k+kd}{final} \PYG{n}{Boolean} \PYG{n}{result}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{input}\PYG{o}{.}\PYG{n+na}{setBackgroundColor}\PYG{o}{(}\PYG{n}{Color}\PYG{o}{.}\PYG{n+na}{WHITE}\PYG{o}{)}\PYG{o}{;}
    \PYG{o}{\PYGZcb{}}
\end{Verbatim}

When the user presses the cancel button in the UI, any currently
running tasks are canceled using the control method
\code{cancel(boolean)}, and subsequent invocations of \code{isCancelled}
return false; as a result, the \code{isPrime} method returns on the next
iteration.

How often to check for cancelation attempts is a matter of
experimentation: Typically, it is sufficient to check only every so
many iterations to ensure that the task can make progress on the
actual computation. Note how this design decision is closely related
to the granularity of the units of work in the single-threaded design
discussed in \emph{\_sec\_SingleThreaded} above.

What remains is to schedule the resulting \code{AsyncTask} on a suitable
executor object:

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
                        \PYG{k+kd}{final} \PYG{n}{PrimeCheckerTask} \PYG{n}{t} \PYG{o}{=}
                                \PYG{k}{new} \PYG{n+nf}{PrimeCheckerTask}\PYG{o}{(}\PYG{n}{progressBars}\PYG{o}{[}\PYG{n}{i}\PYG{o}{]}\PYG{o}{,} \PYG{n}{input}\PYG{o}{)}\PYG{o}{;}
                        \PYG{n}{localTasks}\PYG{o}{.}\PYG{n+na}{add}\PYG{o}{(}\PYG{n}{t}\PYG{o}{)}\PYG{o}{;}
                        \PYG{n}{t}\PYG{o}{.}\PYG{n+na}{executeOnExecutor}\PYG{o}{(}\PYG{n}{AsyncTask}\PYG{o}{.}\PYG{n+na}{THREAD\PYGZus{}POOL\PYGZus{}EXECUTOR}\PYG{o}{,} \PYG{n}{number}\PYG{o}{)}\PYG{o}{;}
\end{Verbatim}

This completes the picture of moving long-running activities out of
the UI thread but in a way that they can still be controlled by the UI
thread.


\section{Summary}
\label{chapter:summary}
In this chapter, we have studied various parallel and distributed
computing topics from a user-centric software development
angle. Specifically, in the context of mobile application development,
we have studied the basic building blocks of interactive applications
in the form of events, timers, and asynchronous activities, along with
related software modeling, architecture, and design topics.

The complete source code for the examples from this chapter is
available from {\hyperref[chapter:cs313ex]{{[}CS313Ex{]}}}. For further reading on designing concurrent
object-oriented software, have a look at {\hyperref[chapter:hpjpc]{{[}HPJPC{]}}}, {\hyperref[chapter:cpj2e]{{[}CPJ2E{]}}}, and
{\hyperref[chapter:jcp]{{[}JCP{]}}}.

\begin{notice}{note}{Todo}

end of section summaries, Q\&A/FAQ, questions to ponder/exercises?
\end{notice}

\begin{notice}{note}{Todo}

Key takeaways: derive from stated learning outcomes.
\end{notice}
\paragraph{Acknowledgments}

We are grateful to our graduate students Michael Dotson and Audrey
Redovan for having contributed their countdown timer implementation.

\begin{thebibliography}{Christensen2009}
\bibitem[Android]{Android}{\phantomsection\label{chapter:android} 
Google. 2009-2014. \emph{Android Developer Reference}. \href{http://developer.android.com/develop}{http://developer.android.com/develop}.
}
\bibitem[APPP]{APPP}{\phantomsection\label{chapter:appp} 
Robert C. Martin and Micah Martin. 2006. \emph{Agile Principles, Patterns, and Practices in C\# (Robert C. Martin).} Prentice Hall PTR, Upper Saddle River, NJ, USA.
}
\bibitem[Ashton2009]{Ashton2009}{\phantomsection\label{chapter:ashton2009} 
Kevin Ashton. 2009. That `Internet of Things' Thing. \emph{RFID Journal}, 22. Juli 2009. \href{http://www.rfidjournal.com/articles/view?4986}{http://www.rfidjournal.com/articles/view?4986}
}
\bibitem[Christensen2009]{Christensen2009}{\phantomsection\label{chapter:christensen2009} 
Jason H. Christensen. 2009. Using RESTful web-services and cloud computing to create next generation mobile applications. In \emph{Proceedings of the 24th ACM SIGPLAN conference companion on Object oriented programming systems languages and applications} (OOPSLA `09). ACM, New York, NY, USA, 627-634. DOI=10.1145/1639950.1639958 \href{http://doi.acm.org/10.1145/1639950.1639958}{http://doi.acm.org/10.1145/1639950.1639958}
}
\bibitem[CPJ2E]{CPJ2E}{\phantomsection\label{chapter:cpj2e} 
Doug Lea. 1999. \emph{Concurrent Programming in Java. Second Edition: Design Principles and Patterns} (2nd ed.). Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA.
}
\bibitem[CS313Ex]{CS313Ex}{\phantomsection\label{chapter:cs313ex} 
Konstantin Läufer, George K. Thiruvathukal, and Robert H. Yacobellis. \emph{LUC CS COMP 313/413 Examples}. \href{https://bitbucket.org/loyolachicagocs\_comp313}{https://bitbucket.org/loyolachicagocs\_comp313}.
}
\bibitem[GOF]{GOF}{\phantomsection\label{chapter:gof} 
Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. 1995. \emph{Design Patterns: Elements of Reusable Object-Oriented Software.} Addison-Wesley Professional.
}
\bibitem[HPJPC]{HPJPC}{\phantomsection\label{chapter:hpjpc} 
Thomas W. Christopher and George K. Thiruvathukal, \emph{High Performance Java Platform Computing}, Prentice Hall PTR and Sun Microsystems Press, 2000.
}
\bibitem[JCP]{JCP}{\phantomsection\label{chapter:jcp} 
Tim Peierls, Brian Goetz, Joshua Bloch, Joseph Bowbeer, Doug Lea, and David Holmes. 2005. \emph{Java Concurrency in Practice.} Addison-Wesley Professional.
}
\bibitem[JavaBeans]{JavaBeans}{\phantomsection\label{chapter:javabeans} 
Oracle Inc. JavaBeans 1.0.1 Specification. \href{http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html}{http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html}
}
\bibitem[MVA]{MVA}{\phantomsection\label{chapter:mva} 
Palantir. \emph{Model-View-Adapter}. \href{http://www.palantir.com/2009/04/model-view-adapter/}{http://www.palantir.com/2009/04/model-view-adapter/}
}
\bibitem[OS]{OS}{\phantomsection\label{chapter:os} 
Per Brinch Hansen. 1973. \emph{Operating System Principles.} Prentice-Hall, Inc., Upper Saddle River, NJ, USA.
}
\bibitem[POSA2]{POSA2}{\phantomsection\label{chapter:posa2} 
Douglas C. Schmidt, Michael Stal, Hans Rohnert, and Frank Buschmann. 2000. \emph{Pattern-Oriented Software Architecture: Patterns for Concurrent and Networked Objects} (2nd ed.). John Wiley \& Sons, Inc., New York, NY, USA.
}
\bibitem[TDD]{TDD}{\phantomsection\label{chapter:tdd} 
Beck, Kent. 2002. \emph{Test Driven Development: By Example.} Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA.
}
\bibitem[UML]{UML}{\phantomsection\label{chapter:uml} 
James Rumbaugh, Ivar Jacobson, and Grady Booch. 2010. \emph{Unified Modeling Language Reference Manual} (2nd ed.). Addison-Wesley Professional.
}
\bibitem[XUnitPatterns]{XUnitPatterns}{\phantomsection\label{chapter:xunitpatterns} 
Gerard Meszaros. 2007. \emph{xUnit Test Patterns: Refactoring Test Code.} Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA.
}
\end{thebibliography}



\renewcommand{\indexname}{Index}
\printindex
\end{document}
