ANDROID
Programming
Concepts
TRISH CORNEZ
UNIVERSITY OF REDLANDS
RICHARD CORNEZ
UNIVERSITY OF REDLANDSWorld Headquarters
Jones & Bartlett Learning
‘5 Wall Sueet
Burlington, MA 01803,
978-443-5000
info@ jlearning.com
wo jlearning.com
Jones & Bartlet Learning books and products are available through most bookstores and online booksellers. To
contact Jones & Bartlet Learning directly, call 800-832-0034, fax 978-443-8000, of vst our Website, ww jblearning.com.
Substantial discounts on bulk quantities of Jones & Barlet Learning publications are available to corporations, profes-
sional associations, and other qualified organizations, Por details and specie discount information contact the special
sales department at Jones & Barlet Learning via the above contact information of send an email to specialsales@
jblearning.com.
Copyright © 2017 by Jones & Bartlett Learning, LLC. am Ascend Learning Company
llrightsreserved. No part ofthe material protected by this copyright may be reproduced or utilized im any form, electronic
‘or mechanical including photocopying, recording, or by any information storage and retrieval system, without written
permission from the copyright owner.
‘The conten. statements, views, and opinions herein ae the sole expression of the respective authors and not that of Jones dt
Bartlett Learning, LLC. Reference herein tony specific commercial product, process, o sevice by trade name, trademark,
manufacturer, or otherwise does not constitute or imply its endorsement or recommendation by Jones & Bartlet Learning,
LLC and such reference shall not be used for advertising or product endorsement purposes. All rademarks displayed are
the trademarks ofthe parties noted herein. Android Programming Concept isan independent publication and has not been
authorized, sponsored, or otherwise approved by the owners ofthe trademarks or service marks referenced in this product.
‘There may be images inthis book that Feature models; these models do not necessarily endorse. represent, or participate in
the activities represented in the images. Any screenshots in this product are for educational and instrwetive purposes only.
[Any individuals and scenarios featured inthe ease studies throughout this product may be real or fititious, but are used
for instructional purposes only
o7915-9
Production Credits ‘Composition: $4Carlisle Publishing Services
VP, Executive Publisher: David D. Cella ‘Cover Design: Kristin E, Parker
Publisher: Cathy L. Esperti Rights and Media Research Coordinator: Abigail Reip
Acquisitions Editor: Laura Paghuica ‘Media Development Assistant: Shannon Sheehan
Editorial Assistant: Taylor Ferracane ‘Cover Image: © Involved Channe/Shutterstock
Production Editor: Sara Kelly Printing and Binding: RR Donnelley
Senior Marketing Manager: Andrea DeFronzo ‘Cover Printing: RR: Donnelley
VP, Manufacturing and Inventory Control: Therese Connell
Library of Congress Cataloging-in-Publication Data
Come, Trish
Android programming concepts/Trish Corner, Universiy of Redlands, Redlands, California, [and] Richard Corne?,
University of Redlands, Redlands, California,
pages
Includes bibliographical references and index.
ISBN 978.1-284.07070-5 (pbk)
1. Android (Electronic resoutee) 2. Application software—Development. 3. Tablet computers —Proramining.
4. Smartphones—Programming. 1. Comez, Richard. I. Tite.
(QA76.774.453C67 2017
005.26°8—ae23
2015008371
oa
Printed in the United States of America
18 171615 10987654321Contents
Preface ix
Chapter 1 Introduction 1
Ld Android Platforms 1
1.2 Javavs. Android Java 5
1. Android Studio IDE 8
14 The Basics of App Design 9
1.5 The Anatomy of an Android Project 10
1.5.1 Android Manifest File 12
1.5.2 Java Source Code and Activity Class Files 13
1.5.3 Drawable Resources 13
1.54 Layout XML Files 14
1.5.5 Value Resources. 15
1.5.6 Gradle Scripts 16
1.6 Building Basic Applications in Android Studio 17
1.7 Model-View-Controller 67
1.8 Debugging Android Applications 77
1.9 Sharing your Android Applications 81
Exercises 87
Chapter 2 Building User Interfaces and Basie Appli 89
21 Android User Interface 89
22 Layouts 90
23 TheviewClass 96
24 — Text Input and Output 97
25 Soft Keyboards 100
2.6 Androids Form Widgets for User Interfaces 118
2.6.1 RadioButton and checkBox 118
2.6.2 ToggleButton 119
2.6.3 switch 120
2.64 ProgressBar 120
2.6.5 SeekBar 121Chapter 5
Chapter 6
Chapter 7
Graphics, Drawing, and Audio 373
5.1
52
53
54
55
6
Graphics in Android 373
Adding and Manipulating ImageViews 374
Drawing and the Canvas Class 392
Recursive Drawing 402
Frame-by-Frame and Film Loop
Animations 415
Animate Library 436
Audio 446
5.7.1 SounaPool 447
5.7.2 MediaPlayer 449
Exercises 459
hreads, Handlers, and Programmatic
Movement 461
61
62
63
64
65
66
67
68
69
6.10
a
72
73
14
75
16
WW
18
19
Multithreading and Multicore Processing 461
Main Thread and Background Thread 464
Thread Approaches 465
6.3.1 Implementing a Runnable Interface 465
6.3.2 Extend the Thread Class 466
UI Modification and the Handler Class. 466
Loopers 477
Canvas Movement and Views 490
SurfaceViews 499
Efficient Threading 512
Materials and Functionality 525
AsyncTasks 541
Exercises 553
pouch Gestures 555
Touchscreens 555
Touch Gestures 556
The Basics of Touch Events 557
Gesture Detector 559
The MotionEvent Class 570
‘The Drag-and-Drop Gesture 591
Fling Gesture 611
Fling Velocity 630
Multitouch Gestures 644
Exercises 656Conrenrs
Chapter 3
Chapter 4
a9
28
29
2.10
211
34
35
3.6
37
2.6.6 RavingBar 121
26.7 spinner 121
Unique ID of a View Object and the R Class 123
The ViewGroup 125
2.8.1 RadioGroup 126
Adaptive Design Concepts—Screens and Orientations 142
‘Tablebayout and TableRow 153
Container Views 170
2411 Listview, Griaview, and
ExpandableListview 171
2.11.2 Scrollview and Horizontalscroliview 171
2.113 searchview 171
214 videoview 172
Using an Adapter 172
Exercises 183
ities and Intents 185
Activity Lifecycle 185
Starting, Saving, and Restoring an Activity 191
Multiple Activities and the Intent Class 202
3.3.1 Explicit Intents 204
3.3.2 Implicit Intents 205
Handling Keyboard Visibility in an Activity 205
Passing Data between Activities 223
Basic Transitions between Activities 243
Scene Transitions 258
Exercises 276
Fragments, ActionBar, and Menus 279
41
42
43
44
45
46
47
48
Fragmentation and Android Fragments 279
The Fragment Lifecycle 280
Action Bar 284
ActionBar Configurations 298
4.4.1 Overflow on the Action Bar 302
4.4.2 Adding an Action View 304
Responsive Design with Fragments 318
Animation in Fragment Transactions 338
ListViews and Adapters 352
Handling Click Events in a ListView 363
Exercises 371Contents
Chapter 8
Chapter 9
Index
809
Sensors and Camera 687
81
8.2
83
84
85
8.6
87
88
8.9.
File Storage,
9
92
93
94
95
96
Sensors and Mobile Devices 657
Android Sensors 658
8.2.1 Motion Sensors 658
8.2.2. Environmental Sensors 660
8.2.3 Positional Sensors 661
Working with Sensors 661
Coordinate System 666
Accelerometer and Force 682
Sensor Batching 694
8.6.1 Step Counter and Step Detector 694
Composite Sensors 696
Camera 705
8.8.1 The Built-in Camera Application 707
Manipulating Photos 721
Exercises 740
hared Preferences, and SQLite 741
Storing Data 741
Shared Preferences 742
File Storage—Internal and External Storage 744
Android Database with SQLite 747
SQLiteOpenHelper 751
Adapters and Adapterviews 765
Exercises 807Preface
Mobile device users experience their environments through a variety of computing
sereens, The devices most often used are computers, tablets, and phones, Users today
increasingly expect a connected and highly personalized experi
across all connected devices, including television, home automation gadgets, wearable
computers, and cars. Android is the operating system that powers many of these con-
As of early 2015, Android is the largest installed base of any mobile
nce that is seamless
nected de
platform
Initially created by Android Inc. by a team led by Andy Rubin, the Android operat-
ing system was acquired by Google in 2005. The first commercial version of Android
was released in 2008 on an HTC phone named Dream; also known as the T-Mobile
GI. Since its initial release, the operating system has undergone an extreme metamor-
phosis, evolving quickly and frequently, with new and updated versions released at an
unprecedented rate.
‘Asa Linux-based system, Android is run as an open s
anyone can adapt the code for his or her own purposes. This permissive model makes
Android unique in that it allows companies and developers to modify and distribute
the software freely. Device manufacturers creating phones and tablets often customize
the Android operating system to the specific needs of their particular mobile devices.
In this text, readers will learn how to design and implement applications that will
run on a variety of Android-driven devices. Building sophisticated applications that
are optimized, responsive, and able to perform complex interactions at fast speeds
requires patience, skill, and practice. The concepts and techniques you will learn
this text will provide you with the building blocks needed to master the art of mobile
programming.
Text Objectives
This text was conceived with two types of individuals in mind: programming stu-
dents and professional software developers who wish to broaden their expertise. It
is essential that readers know how to program in an OOP language, preferably Java,PRrerace
before using this text. For non-Java programmers, familiarization with the Java API is
recommended.
This text is intended as a textbook, not as a tutorial. We have designed the text,
using an easy-to-understand andl straightforward approach, to integrate key concepts
relating to application development that students see daily on Android devices. Each
chapter presents Android concepts and methodologies with complete abbreviated ap-
plication examples that are relevant to current platforms.
How to Use This Text
‘The first three chapters provide an introduction to the foundation of application devel
‘opment. Chapter I incorporates two step-by-step tutorials to help readers get started
n creating basic applications. Chapters 2 and 3 provide key core concepts For build-
ing well-designed applications. It is important that readers are comfortable with these
‘early chapters before proceeding,
‘After reading the first three chapters, Chapters 4 through 9 do not need to be
read in sequential order. Readers wishing to acquire the most invaluable concepts first
should start with Chapter 4 and proceed to Chapters 7, 8, and 9; however, multithreading
‘concepts (discussed in Chapter 6) are a prerequisite for the last three chapters. A detailed
reading of Chapter 5 is not required for Chapter 6.
Instructor and Student Resource Material
‘The following ancillary materials are available on the text website:
g0,jbleaming.com/ComezAndroid
+ Source code fil
for lab example
+ Instructor's Manual containing solutions to end-of-chapter exerci
+ Lecture Slides in PowerPoint format
+ Test bank
Acknowledgments
We have received invaluable support from friends, students, and colleagues in the
preparation of the text. The University of Redlands has provided the resources and
means for us to complete the project. Jones & Bartlett Learning offered an excellent
team of professionals who handled the book from manuse
especially want (o thank Laura Pagluica, Taylor Ferracane, Sara KAcknowledgme
We are thankful to Jordan Vega and Sam Marrs for many useful suggestions. We
are indebted to Jim Bentley and Pani Chakrapani for giving us the opportunity to
schedule several mobile programming classes that allowed us to classroom-test por
tions of our text. Jim Bentley was kind enough to offer department funds for devices
for some of our students, who might not otherwise have been able to participate
We would like to thank the following reviewers, who offered us indispensable
pedagogical and content guidance for revision:
Sonia Arteaga
Hartnell College
Jeremy Blum, DSc
Associate Professor of Computer Scien:
Penn State Harrisburg
Georgia Brown, MS
Instructor
Northern Illinois Unive
ity
George Duda
Instructor in Computer Science and Software Engin
Penn State Erie, The Behrend College
ing
Robert Steinhoff, PhD.
rida Memorial University
Michael Ziray
Boise State University
Last but not least, thanks to our many students whose struggles, challenges, and
Suecesses gave us all the evidlen
we needed to improve the text.Introduction
Chapter Objectives
In this chapter you will:
* Understand the features of Android.
+ Learn the differences. between Java and Android Java.
+ Examine the Android project structure.
* Build a basic application using Android Studio.
+ Learn about the Model-View-Controller design.
@ 1.1 Android Platforms
When the first-generation Android phones were released in 2008, they did not include
many of the features that users are familiar with today. For example, the first commer-
cial version of Android seen on the HTC Dream did not incorporate multitouch capa-
bilities or even a virtual onscreen keyboard. Since 2008, Android has been enhanced in
4 multitude of ways, improving its performance, the user interface design, and adding
many features, such as voice searching. By October 2014, Google released a version
of Android comprising a powerful core of set standards that work on virtually every
device, along with a refined visual component, By 2015, Android applications were
including fluid animations, bold color palettes, and sophisticated multitasking menus
that featured voice interactions.
Table 1-1 shows the evolution of Android, beginning with Android 1.0, the first
jon used on the HTC Dream. With each subsequent version of An-
droid, features from previous versions were improved. and enhancements were made
that targeted overall performance.
AS each major version of Android is released, it is identified by a code name,
organized in alphabetical order; all of the code names are the names of desserts. The
first publicly code-named version of Android appeared in 2009 and was given the
name Cupeake. In addition to the code name, each version of Android is given an
API (application program interface) number and platform version number. Updates
commercial veCuarrer 1 INrRopucrion
‘TABLE 1-1. Common Android Platforms
Platform Version
Version _| API Levels) Name Important Features
5.0 23 Lollipop. Tuned to work on devices with
64-bit ARM, Intel, and MIPS
processors
44 19 2013 KitKat Optimized to run with a minimum of
‘512 MB of RAM
43 8 2013, [JellyBean | Efficient and refined user interface
42 7 2012 Google Voice Search
4 16
4.0.4, 4.03, 15 2012 Ice Cream Compatibility with most Android
402,401, | 14 2011 |Sandwich | 23x
4.0 API fixes and refinements
32 3 2011 [Honeycomb | Tablet-only support
34 12
3.0 W
234,233, 10 2011 Gingerbread | Enhancements for game developers
232,23.1,23 |9 2011 ‘Support for multicore processors
22 8 2010 | Froyo Android Cloud support
21 7 7010 | Eclair Google Maps Navigation
201 6 New camera features
20 5 Bluetooth
Speech-to-text
16 4 2009 Donut Integrated camera and camcorder
Expanded gestures
Introduction of Quick Search Box
18 3 2009 [Cupcake | Soft keyboard
Copy and paste
Video recording
wl 2 7009 Bug fixes to Android 1.0
10 1 7008 Gmail
Notifications
Widgets
are designed so that a new API remains compatible with earlier versions of the API.
‘The API identification is important to developers, as well as to Google Play, because
it allows the Google Play store to filter applications so that users can easily download
that are compatible with their devices. New versions of Android also bring
tion of new APIs for developers, such as notification controls or aids to make
applications more memory effAndroid Platforms
Google services have been integrated into the Android operating system since the
first installment, Two of the most substantial inclusions of Android 1.0 were Google
Maps and Notifications, which supported a pull-down window that revealed an-
nouncements
and messages. The Notifications feature remai
an important part of
the Android user interface. In current releases of Android, this feature has been refined
to include chat messages and calendar events that support synchroni
Android devices, as shown in Figure I-1
ation across all
0
‘new message
2now messages
| FIGURE 1-1 Android Lotlipop Notifications
By the time Cupeake appeared in 2009, such ref
self-refres
sis
ts as the inclusion of
1@ Widgets and copy-and-paste had been implemented. One of the most
ificant features that emerged with Cupeake was the introduction of a soft key-
board, which also brought the first forms of keyboard skins. Created by third-paCuaprer 1 INrRopucTioN
developers, keyboard skins provide enhancements to an existing soft keyboard. Unique
to Android, skins allow users to personalize their keyboards, for example, by choosing
abackground texture, an icon set, and a color palette. When Google releases its latest
version of Android, device manufacturers typically customize that software for t
brand of phone and tablets. Skins have evolved alongside Android and have shifted
beyond basic appearance and into more extensive behavior than originally seen in
Cupcake. Today, Android device manufacturers regularly offer skins that enhance the
user experience by adding functionality to the design.
Created in 2010, Android 2.2 was able to execute far faster than previous vers
because of the new Dalvik Just-In-Time (JIT) compiler, first seen on Froyo. Dalvik,
which will be discussed in more detail in the next section, allowed for better CPU per-
formance, which significantly enhanced processing power. Along with the bolstered
speed, Froyo’s browser came with a new JavaScript engine, making Internet browsing,
nearly three times faster than the previously released version of Android. Froyo also
brought native support for tethering, This built-in feature, along with mobile hotspot
support, gave users the ability to turn their phone into a wireless modem and a Wi-Fi
hotspot for the first time.
Gingerbread became the prevailing version of Android from 2011 through most
‘of 2012. [twas the first version of Android that backed multicore processing on mobile
devices. For application developers, Gingerbread brought support for new technolo-
gies, such as NFC (Near Field Communication) and SIP (Session Initiation Protocol).
‘The SIP API provides developers with tools to create applicatio
conferencing and instant messaging.
Honeycomb was released as the first version of Android specifically implemented
for tablets. Prior to Honeycomb, Android tablets were running on phone operating
systems that were stretched to fit the screen of a larger tablet.
With the release of [ce Cream Sandwich, Android was rebuilt to combine the best
‘characteristics of Gingerbread and Honeycomb into a single operating system that
would work for tablets and phones. Ice Cream Sandwich was able to bring many of
the design elements of Honeycomb to smartphones, while refining the Android experi-
‘ence. The Ul was notably more refined and stylish. In addition, navigation buttons be-
‘came available as soft keys, and the voice input engine provided an open-microphone
‘experience.
When Jelly Bean was released in 2012, it was the fas
Android versions. Along with its Google Voice Search feature, Jelly Bean was a jump
in magnitude of performance, This version of Android was often referred to as a turn-
ing point for Android, where services and customization optior onsive design
guidelines. KitKat looked similar to Jelly Bean; however, because of its size of 512
MB, it was able to run on a much larger array of devices. Previously, Android required
1GB 0 3 GBs to run,
cir
hat perform
and smoothest of all the
metresJava vs. Android Java
As of early 2015, Lollipop is the latest version of Android used by develope:
Lollipop and 64-bit chips provide enhanced performance with graphics, decoding and
encoding of high-resolution video, and algorithms for facial recognition and speech
nteraction.
With so many versions of Android currently being supported, itis often difficult to
choose the appropriate target version for which to compile an application. In fact, the
latest version of Android is not always the most common version installed on Android
phones and tablets. The ability to build an application that runs om multiple versions
of Android is an important requirement for developers. For example, in early 2015.
the most common version of Android was Jelly Bean, with KitKat a close second.
However, Ice Cream Sandwich and Gingerbread were still being used on a small,
but significant, number of the mobile devices worldwide. Targeting popular earlier
versions of Android therefore allows developers to reach a larger number of users, but
there can be tradeoffs. An application may require functionality that an older platform
cannot support. In this case, an application developer should target a newer platform
when building an application.
Java is the recommended Language for developing Android applications. In this text-
book, all Android apps will be developed with Java. It is essential that readers know
how to program and have a familiarity with Java libraries before continuing. A large
number of Java libraries are available in the Android platform. As any Java program-
mer knows, Java comes with a library of classes providing a collection of utility func
tions that most Java programs cannot do without. This class library, called the Java
API, has several thousand classes, with tens of thousands of methods that can be used
in Android programs.
Android applications use Java, along with the extension libraries that Android
provides in the Android software development kit (SDK). The SDK includes a com-
prehensive set of development tools, including a debugger, software libraries, and an
emulator for an Android devie
Important differences distinguish the Java API from the Android API. To understand
Android Java, we first need to understand what characterizes Java. Java differs from
other programming languages in several noteworthy ways; the crucial difference is plat-
form independence. One reason Java is so popular is that Java programs can be run on
any computer with an installed Java Runtime Environment (JRE). Figure 1-2 ilh
Java's platform independence. Java files are compiled to an i
jon rather than directly to a platform-specific machine code. This intermediate repre-
sentation, Java bytecode, is analogous to machine code. The major difference between
strate
ermediate representa-Cuaprer 1 INTRODUCTION
bytecode and machine code is that bytecode instructions are interpreted by a virtual ma-
‘chine (VM) written specifically for the host hardware, A virtual machine is a software
implementation of a machine (i.c., a computer) that executes programs like a physical
machine.
To run non-Android Java programs, a Java compiler must translate the source
code files into class files. These files can then be executed on a Java virtual machine
(VM), which interprets the intermediate language on a target computer. By preparing
a. IVM for each platform, a program translated into the intermediate language can be
run on many different computers. The Java virtual machine is called “virtual” because
it is am abstract computer defined by a specification. Each Java application runs inside
a runtime instance of some concrete implementation of the abstract specification of
the JVM. The JVM runs on all kinds of hardware executing the Java bytecode without
changing the Java execution code, Java bytecode runs in a JRE, which is composed of
the Java API and the JVM.
CE
ee
wee
FIGURE 1-2 Java programs are compiled into bytecode and run in Java Runtime Environments.
There
no Java virtual machine in the Android platform; instead, there is Dalvik,
which is a specialized virtual machine. Once Java has been compiled into bytecode
by the Java compiler, it is compiled again into a proprietary bytecode, as illustrated in
Figure 1-3. The bytecode loaded by the Dalvik virtual machine should not be confused.Java vs. Android Java
with Java bytecode. The dex bytecode is a compact Dalvik executable format designed
for Android systems, which are constrained in terms of memory and processor speed.
‘The Android Software Development Kit includes the Dalvik dx tool, used to translate
Java bytecode into Dalvik bytecode.
Dalvik is referred to a JIT (Just-In-Time) engine because it compiles bytecode
al time. A new Android Run Time (ART) was introduced in 2014 that takes
advantage of current hardware advances. ART relies on an AOT (Ahead of Time)
compiler, which compiles bytecode before execution. The ART virtual machine is
the default of Lollipop and compiles an application to native machine code when
installed on a user’s device. ART is designed to be fully compatible with Dalvik’s
existing bytecode format.
Dalvik and ART do not align to all Java class library profiles. Specifically,
Abstract Window Toolkit and Swing are not supported by Dalvik and ART.
Instead, Android user interfaces are built using the View framework, which is similar
to Swing. This framework will be discussed in detail in Chapter 2.
in
1 FIGURE 1-3 Java bytecode is compiled into Dalvik bytecode and executed on a Dalvk VM.Cuarrer | INrRopucrion
@ 13 Android Studio IDE
Android applications are often built to take several forms, such as phone, tablet, Wear,
and Google Glass. In addition, the project structure of an application consists of many
moveable pieces. These factors lead to a complex project structure. To make the de-
velopment pros 1, it is recommended that developers use an integrated d
velopment environment (IDE) to build applications. This textbook relies on Android
Studio.
Based on IntelliJ, Android Studio is the official IDE for building Android ap-
plications. Developed by Google, this environment focuses exclusively on Android
development and comes bundled with the Android Software Development Kit (SDK).
‘The SDK provides developers with a packaged set of developer tools and API libraries
for building complete applications, testing them on virtual devices, and performing
debugging and optimization.
For readers intent on finding an alternative to Android Studio, it is possible 10
install a stand-alone SDK tool set that does not include a complete development envi-
ronment. This option allows developers to access the core SDK tools from a command.
line or possibly from another IDE, such as Eclipse. This approach is not recommended
for first-time developers.
Android Studio is available for download from Android’s developer website:
developer.android.com/sdk/installing/studio.hum!
Updates and improvements are made frequently to Android Studio, as well as to
the required plug-ins. You may find that your version of Android Studio looks some-
what different from the images you will see in this text. The core functionality remains
the same.
Android Studio requires the Java Development Kit (JDK) for building appli
and components. One of the most important tools in the JDK is the ava compiler. Java
code featured in this textbook has been compiled with JDK 7.
The following development components are included in Android Studio, or must
be added, just as newly released versions of an SDK should be added:
Java ‘The Java programming language editor contains common IDE
Editor features, such as compile-time syntax checking, auto-completion,
and integrated documentation for the Android framework APIs.
Layout Android Studio includes a graphical layout editor for building
Editor and editing user interface files. Specifically, this graphical layout
editor allows for easy drag-and-drop functionality for designing
and previewing user interfaces.
Android The Android SDK is a collection of API libraries, tools, script
SDK and documentation. The SDK separates tools, platforms, andThe Basics of App Design
‘other components into packages that can be downloaded as
needed. As new SDK versions and tools become available, they
should be added to Android Studio.
The Android SDK archive initially contains the basic SDK tools.
It does not contain an Android platform or third-party libraries
In order to start developing applications, you must install the
platform tools and at least one version of the Android platform,
using the SDK Manager, Platform tools contain build tools that
are periodically updated to support new features in the Android
platform,
AVD ‘To run the Android Emulator, an Android Virtual Device (AVD)
is constructed to define the characteristies of the device on which
an application can be tested. This includes the system image and
sereen size, the hardware, data storage, etc. To test an application
‘on multiple Android devices, a unique AVD device must be cre-
ated for emulation. In Tutorial 1 of this chapter, you will create
an AVD to test a simple application.
Gradle Gradle is the build system used by Android Studio. Provided as
a plug-in to Android Studio, it can also be used to build Android
apps from the command line. The build configuration of a given
Android project is defined inside simple text files that use op-
tions from Gradle.
14 The Basics of App Design
In the early days of mobile devices, very few apps existed. A mildly interesting and
useful application had a fairly decent chance of becoming successful during the first
years of Android devices. Today, the competition is far more intense. It is not enough
‘o produce an interesting and useful app, particularly if similar apps are on the mar-
ket. In addition to a good idea, a promising Android application must perform well,
interesting than a competing application, and offer a user experience that is
ing.
ig an outstanding application involves considerable thought and analysis
of usability and user interface design. These two elements require attention both before
and during the development process. In addition to performance, usability and the user
experience can often be indicators of th. s or failure of an application.
The process for building an application, as depicted in Figure 1-4, begins with an
initial idea. Sometimes, research follows to determine the value and demand of an app
idea, The initial concept for an application can be somewhat vague at the beginning
stage, even if some specifications have been outlined. To evolve design concepts i
suce10
Cuarrer 1 INrRopucrion
a workable model, it is advisable to generate a user narrative that recreates a user's
experience, given the technical constraints of the application.
FIGURE 1-4 The process for building begins with an idea and ends with delivery.
Design ideas are generated from the exploration of user experiences. Ideas can
start with a simple sketch on paper and evolve into cutout prototypes. Sketches can
include design usage scenarios to explore ideas for structuring a navigation system
related to the aesthetic qualities of interaction. Cutout prototypes, as shown in Figure
1.5, can serve as micro experiments to explore strengths and weaknesses that involve
actual tactile handling. These can also influence technical decisions,
| FIGURE 1-5 Use of physical mockups can make application user experiences better understood
M15 The Anatomy of an Andr
Project
A certain amount of technical machinery is necessar to write even the sim-
plest applications. As you learn to develop apps, we will sometimes give you a prelimi-
nary explanation and you will have to wait for more complete detail in a later chapter.‘The Anatomy of an Android Project
‘The Android SDK tools expect that your project will follow a specific structure so
it can compile and package the application correctly, Gradle is atthe foundation of the
Android SDK build system and is used to automate the building, testing, publishing,
and deployment of Android apps.
A project built in Android Studio will be structured similarly to Figure 1-6. The
project structure is organized by source code, the application’ s resources, manifest set-
tings, and build files. All of these files are eventually packaged into an apk (Andi
application package) file, which represents the final application that will be installed
and then run on an Android-powered device,
sac ain
aap in a prenanl
© e000
‘pied bythe density Bema Sees fhe
= enotero Soeewrie
Speeoton oe
¥ Bie
Bean as
pea
Soe
Biermcarats
Soman
ites
ed ‘iene fe
Daum =
» Benno Bere
Berra Stetow man
Sus Gide bl Siren —""
Fi cetaing cle 2G sro
momento ‘Soa gan
font pence
Biesimce pasar
Binet
(lea prperees 0% Lc
1 FIGURE 1-6 Sample Android App Project Structure
Many of the application files and directories shown in Figure 1-6 are automatically
generated and contain default content, Additional files have been generated and hid
den from view. At this early stage, it is important that we understand the following
components found in the project structure. Once we understand the purpose of these
files, the development process will fit into a more comprehensible context and will be
‘easier to implement.
uwPreR 1 INTRODUCTION
1.5.1 Android Manifest File
An AndroidManifest .xml, is required for every Android application. This file
uses XML code to define specific application information. The information ean in-
clude general application-wide settings, such as the application’s style and launch
icon. In the example AndroidMani fest .xm1 code shown below, Line 6 sets the
launch icon to a graphic image stored in the drawable folder. Line 7 sets the style of
the application so that it has a black background and utilizes a full screen.
capplication
android: icon-"@drawable/icon"
ndroid::style/Thene. Black .NoTitleBar-Fullscreen"
‘The AndroidManifest file is also used to specify an application's hardware re-
‘quirements or special permissions, A permission system is part of the Android security
model. For example, permissions can be used to grant or deny services, such as loca-
tion services, access to external storage, and SMS.
‘The following example of XML code is used in an AndroidManifest file to require
that a device include a camera in order to run the application. In addition, two permis-
sions are requested: camera permission and the ability to write to extemal storage to
save a photograph.
android :nane="android.hardware.Camera" />
android:required="true" />
permission
android :nane="android.permiss ion.CAMERA"/>
permission
android :nane=
"android. permiseion.WRITE_EXTERNAL_STORAGE"/>‘The Anatomy of an Android Project
structure. A layout is the visual representation of a given interface screen containing
all the visual objects on display. As shown in Figure 1-8, the design and arrangement
of the elements on the screen are implemented using XML code in a layout fil
When a layout appears on the screen, it is managed by an Activity. An Activity is a
Java class that drives the actions and movements that will occur on the screen. Chapter
2 will explore techniques for designing various screen layouts.
activity. my.xma) —____
1 FIGURE 1-8 The User Interface ofan application is defined by an XML file
1.55 Value Resources
The res /values directory within an Android proj
sources for the application. This includes strings, colors, dimensions, and styles used
by the application. Value resources are implemented as XML files.
‘Android encourages the separation of functionality and resources. This philoso-
phy of keeping values separate from funetions can be very helpful for developers. For
example, when developing an application that will be translated into multiple foreign
Tanguages, string values can be changed without affecting the deployment of the app.
‘The application can be translated from the first language to a second language by recus-
tomizing the strings .xm1 file. In this way, the application apk can remain intact.
Value resource files are organized by the various types of data they contain. A
collection of text strings is stored as strings .xm1, while color definitions can be
stored in colors .xm1.
tis used to manage value re
15‘The Anatomy of an Android Project
1.8.2 Java Source Code and Activity Class Files
The Java source code of an application is placed in the java directory of the project
structure. A main file, often named MainAct ivity or sometimes MyActivity, is
a Java file that is auto-generated when the project is first built. It may have a different
name, depending on the Android Studio version you are using. This Java file repre-
sents an application activity and is important because it controls the behavior of the
application when it is first launched. An Android activity corresponds with a single,
focused activity that the user can perform, Applications are made up of one or more
Activities. For example, consider a banking application that requires the user to log
into the account securely before it is possible to access the account information. The
login sercen would be represented by one activity, while the account overview would
be represented by a separate activity.
Each Activity is represented by a visual interface to the user, called a layout, along
with source code, such as MainActivity. java, that drives it
Activities are essentially defined using two types of files:
+ Tava class determines the behavior of the activity.
+ Layout det
ines the visual layout of the activity.
When an application is designed with multiple activities, one activity must be
designated as the main activity when the application is launched for the first time. By
default, this activity is the one first created and named when the application project is
first set up.
1.5.3 Drawable Resources
The drawable folder is located in the res directory, which contains the application
resources. Drawable resources are image files, such as application icons, buttons, and
background textures. Mobile applications typically require many visual elements,
which are often managed as drawable resources, For example, in a chess game appli
cation, the chess pieces are drawable image files imported into the application project.
‘The most common drawable resource used in an application is a PNG file. Android
recommends the use of graphics that are not interlaced and are stored with a 24-bit
depth. Images and icons do not need to be restricted to. web-safe colors.
Android runs on a variety of devices, ranging from low-density small screens t0
high-density large screens. A density-independent pixel (dp) is a virtual pixel unit that
is equivalent to one physical pixel on a 160-dpi (dots per inch) screen. This is the base-
line density assumed by the system for a medium-density screen. The conversion of dp
units to screen pixels (px) is:
px = dp X (
-android .com/apk/rea/androia"
sapplication
android :allowBackup="true"
cone"@drawable/ic_
abel="@string/app_)
android:thene="@style/AppThene" >
android
android
patring/app_nane" >
category
android :nanes"android. intent category. LAUNCHER™ />
Part 4: Adding and Editing Application Resources
Before we can build a user interface and code the application, we need to add the
required resources to the project structure, The resources for a basic application will
typically consist of text values, graphic files, data values, and color definitions. AILBuilding Basic Applications in Android Studio
resources should be identified during the conceptual design phase of the application,
such as the one we will use from Figure 1-6.
This Hello Goodbye application will require three types of resources as follows:
Drawables: Three graphic fi
String valu
es will be added to the project structure to en-
hance the application visually.
hello” and
Text strings will be used to store the exclamation
‘goodbye”) and the text that appears on the button.
Color values: A color definition that will be used to color the “Hello” and.
Step 1:
Step 2:
Step 3:
Step 4:
Step 5:
Stop 6:
‘Goodbye” text generated and displayed by the application.
Assemble the drawable resour
es 10 be used in the application
Before constructing the application project, make sure that you have all neces-
sary external application elements, For this tutorial, there will be three image
files used in the application: a background image, a button image, and a small
‘graphic for decoration, These elements, shown in Figure 1-21, can be found in
the textbook resources. All image file names must contain only lowercase letters.
Within the drawable folder for Tutorial 1, you will find three folders hold-
ing the background .png, greetimage .png and exclamat ion-
btn .png image files. The png files located in these folders have been
‘customized for the screen pixel density specified in the directory’s name. In
production value applications, it is important to provide images for the
‘erent screen pixel densities in your projects.
xxhdpi —extra-extra-high-density screens (approximately 320 dpi)
xhdpi _extra-high-density screens (approximately 240 dpi)
Providing different images will reduce artifacts from images being scaled
up and down. All of the images in your project will be installed with your
app, and the operating system will choose the best one for that specific
device.
Drag the xxhdpi version of greet image .png to the drawable folder in
the project structure, as shown in
igure 1-22.
If the file cannot be dragged, perform a copy/paste
Select the xxhdpi destination directory, as shown in Figure 1-23.
‘Choose the name of the file, as shown in Figure 1-24.
Verify greetimage .png appears in the drawable folder, a8 shown in
Figure 1-25.
Add the xhdpi version of greet image .png to the drawable folder. Use
the same method from Step 4.
29