Android Programming The Big Nerd Ranch Guide

Android%20Programming%20The%20Big%20Nerd%20Ranch%20Guide%20Third%20Edition

Android-Programming-The-Big-Nerd-Ranch-Guide

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 720

DownloadAndroid Programming The Big Nerd Ranch Guide
Open PDF In BrowserView PDF
Android Programming: The Big Nerd Ranch Guide
by Bill Phillips, Chris Stewart and Kristin Marsicano
Copyright © 2017 Big Nerd Ranch, LLC.
All rights reserved. Printed in the United States of America. This publication is protected by copyright, and
permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system,
or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For
information regarding permissions, contact
Big Nerd Ranch, LLC.
200 Arizona Ave NE
Atlanta, GA 30307
(770) 817-6373
http://www.bignerdranch.com/
book-comments@bignerdranch.com
The 10-gallon hat with propeller logo is a trademark of Big Nerd Ranch, Inc.
Exclusive worldwide distribution of the English edition of this book by
Pearson Technology Group
800 East 96th Street
Indianapolis, IN 46240 USA
http://www.informit.com
The authors and publisher have taken care in writing and printing this book but make no expressed or implied
warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental
or consequential damages in connection with or arising out of the use of the information or programs contained
herein.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the
designations have been printed with initial capital letters or in all capitals.
ISBN-10 0134706099
ISBN-13 978-0134706092
Third edition, first printing, February 2017
Release D.3.1.1

Dedication
To the record player on my desk. Thanks for keeping me company
through all this. I promise I’ll get you a new needle soon.
— B.P.

To my dad, David, for teaching me the value of hard work. To my mom,
Lisa, for pushing me to always do the right thing.
— C.S.

To my dad, Dave Vadas, for inspiring and encouraging me to pursue a
career in computing. And to my mom, Joan Vadas, for cheering me on
through all the ups and downs (and for reminding me that watching an
episode of The Golden Girls always makes things better).
— K.M.

iii

Acknowledgments
With this being our third edition, we find ourselves used to saying this. It always needs to be said,
though: Books are not created by authors alone. They are shepherded into existence by a community
of collaborators, risk-takers, and other supporters, without whom the burden of comprehending and
writing all this material would be crippling.
• Brian Hardy, who, along with Bill, had the gusto to bring the very first edition of this book into
the world. From nothing, Brian and Bill made something great.
• Our co-instructors and members of our Android development team: Andrew Lunsford, Bolot
Kerimbaev, Brian Gardner, David Greenhalgh, Josh Skeen, Matt Compton, Paul Turner, and
Rashad Cureton. (Soon, Rashad. Soon.) They taught everything in this book before it was
polished enough to be presentable and gave us many invaluable suggestions and corrections. Most
people live their entire lives without ever working with such a talented and entertaining crew.
They make work at Big Nerd Ranch an everyday joy.
• Special thanks to Andrew, who went through the entire book and updated all the Android Studio
screenshots. We appreciate his thoroughness, attention to detail, and acerbic wit.
• Zack Simon, our fantastically talented and soft-spoken Big Nerd Ranch designer. Unbeknownst
to us, Zack went behind our backs and updated the nifty cheat sheet you can find attached to this
book. If you enjoy that sheet, you should find Zack and tell him so yourself. But we will also
thank Zack right here: Thanks, Zack!
• Kar Loong Wong, for his work redesigning the crime list screen. The more help we get from Kar,
the better the apps in this book look. Thanks, Kar.
• Mark Dalrymple, who reviewed our constraint layout coverage for accuracy and wonderfulness. If
you happen to run into Mark, ask him to review your constraint layout coverage. He is so good at
doing that! But if you have none, ask him to make balloon animals for you instead.
• Thanks to Aaron Hillegass. As a practical matter, it is not possible to do this work without Big
Nerd Ranch, the company Aaron founded. Thank you.
• Our editor, Elizabeth Holaday. The famous beat author William S. Burroughs sometimes wrote by
cutting up his work into little pieces, throwing them in the air, and publishing the rearrangement.
Without a strong editor like Liz, our confusion and simpleminded excitement may have caused
us to resort to such techniques. We are thankful that she was there to impose focus, precision, and
clarity on our drafts.
• Ellie Volckhausen, who designed our cover.
• Anna Bentley, our copyeditor, and Simone Payment, our proofreader. Thank you both for sanding
away the remaining rough edges of this book.
• Chris Loper at IntelligentEnglish.com, who designed and produced the print and ebook versions
of the book. His DocBook toolchain made life much easier, too.
v

Acknowledgments
Finally, thanks to our students. There is a feedback loop between us and our students: We teach them
out of these materials, and they respond to it. Without that loop, this book could never have existed, nor
could it be maintained. If Big Nerd Ranch books are special (and we hope they are), it is that feedback
loop that makes them so. Thank you.

vi

Table of Contents
Learning Android ........................................................................................................... xix
Prerequisites .......................................................................................................... xix
What’s New in the Third Edition? ............................................................................. xix
How to Use This Book ............................................................................................. xx
How This Book Is Organized .................................................................................... xx
Challenges ..................................................................................................... xxi
Are you more curious? .................................................................................... xxi
Code Style ............................................................................................................. xxi
Typographical Conventions ...................................................................................... xxii
Android Versions ................................................................................................... xxii
The Necessary Tools ..................................................................................................... xxiii
Downloading and Installing Android Studio .............................................................. xxiii
Downloading Earlier SDK Versions ......................................................................... xxiii
A Hardware Device ............................................................................................... xxiv
1. Your First Android Application ........................................................................................ 1
App Basics ............................................................................................................... 2
Creating an Android Project ........................................................................................ 3
Navigating in Android Studio ...................................................................................... 8
Laying Out the UI ..................................................................................................... 9
The view hierarchy .......................................................................................... 13
Widget attributes ............................................................................................. 14
Creating string resources ................................................................................... 15
Previewing the layout ....................................................................................... 16
From Layout XML to View Objects ........................................................................... 17
Resources and resource IDs ............................................................................... 18
Wiring Up Widgets .................................................................................................. 21
Getting references to widgets ............................................................................. 22
Setting listeners ............................................................................................... 23
Making Toasts ......................................................................................................... 25
Using code completion ..................................................................................... 26
Running on the Emulator .......................................................................................... 27
For the More Curious: Android Build Process .............................................................. 30
Android build tools .......................................................................................... 31
Challenges .............................................................................................................. 32
Challenge: Customizing the Toast ............................................................................... 32
2. Android and Model-View-Controller ............................................................................... 33
Creating a New Class ............................................................................................... 34
Generating getters and setters ............................................................................ 35
Model-View-Controller and Android ........................................................................... 37
Benefits of MVC ............................................................................................. 38
Updating the View Layer .......................................................................................... 39
Updating the Controller Layer ................................................................................... 41
Running on a Device ............................................................................................... 46
Connecting your device .................................................................................... 46
Configuring your device for development ............................................................ 46

vii

Android Programming

3.

4.

5.

6.

Adding an Icon ....................................................................................................... 48
Adding resources to a project ............................................................................ 49
Referencing resources in XML .......................................................................... 51
Challenge: Add a Listener to the TextView .................................................................. 52
Challenge: Add a Previous Button .............................................................................. 52
Challenge: From Button to ImageButton ...................................................................... 53
The Activity Lifecycle .................................................................................................. 55
Logging the Activity Lifecycle .................................................................................. 57
Making log messages ....................................................................................... 57
Using Logcat .................................................................................................. 59
Exploring the activity lifecycle by example .......................................................... 60
Rotation and the Activity Lifecycle ............................................................................ 63
Device configurations and alternative resources ..................................................... 63
Saving Data Across Rotation ..................................................................................... 68
Overriding onSaveInstanceState(Bundle) .............................................................. 69
The Activity Lifecycle, Revisited ............................................................................... 70
For the More Curious: Current State of Activity Cleanup ................................................ 72
For the More Curious: Log Levels and Methods ........................................................... 73
Challenge: Preventing Repeat Answers ........................................................................ 74
Challenge: Graded Quiz ............................................................................................ 74
Debugging Android Apps .............................................................................................. 75
Exceptions and Stack Traces ..................................................................................... 76
Diagnosing misbehaviors .................................................................................. 78
Logging stack traces ........................................................................................ 78
Setting breakpoints .......................................................................................... 80
Using exception breakpoints .............................................................................. 83
Android-Specific Debugging ...................................................................................... 85
Using Android Lint .......................................................................................... 85
Issues with the R class ..................................................................................... 87
Challenge: Exploring the Layout Inspector ................................................................... 88
Challenge: Exploring Allocation Tracking .................................................................... 89
Your Second Activity ................................................................................................... 91
Setting Up a Second Activity .................................................................................... 93
Creating a new activity ..................................................................................... 93
A new activity subclass .................................................................................... 96
Declaring activities in the manifest ..................................................................... 97
Adding a cheat button to QuizActivity ................................................................ 98
Starting an Activity .................................................................................................. 99
Communicating with intents ............................................................................ 100
Passing Data Between Activities ............................................................................... 101
Using intent extras ......................................................................................... 102
Getting a result back from a child activity .......................................................... 105
How Android Sees Your Activities ............................................................................ 109
Challenge: Closing Loopholes for Cheaters ................................................................ 112
Android SDK Versions and Compatibility ....................................................................... 113
Android SDK Versions ........................................................................................... 113
Compatibility and Android Programming ................................................................... 114
A sane minimum ........................................................................................... 114

viii

Android Programming
Minimum SDK version ...................................................................................
Target SDK version ........................................................................................
Compile SDK version .....................................................................................
Adding code from later APIs safely ..................................................................
Using the Android Developer Documentation .............................................................
Challenge: Reporting the Build Version .....................................................................
Challenge: Limited Cheats .......................................................................................
7. UI Fragments and the Fragment Manager .......................................................................
The Need for UI Flexibility .....................................................................................
Introducing Fragments ............................................................................................
Starting CriminalIntent ............................................................................................
Creating a new project ....................................................................................
Two types of fragments ...................................................................................
Adding dependencies in Android Studio ............................................................
Creating the Crime class .................................................................................
Hosting a UI Fragment ...........................................................................................
The fragment lifecycle ....................................................................................
Two approaches to hosting ..............................................................................
Defining a container view ...............................................................................
Creating a UI Fragment ..........................................................................................
Defining CrimeFragment’s layout .....................................................................
Creating the CrimeFragment class .....................................................................
Adding a UI Fragment to the FragmentManager ..........................................................
Fragment transactions .....................................................................................
The FragmentManager and the fragment lifecycle ................................................
Application Architecture with Fragments ...................................................................
The reason all our activities will use fragments ...................................................
For the More Curious: Fragments and the Support Library ............................................
For the More Curious: Why Support Fragments Are Superior ........................................
8. Displaying Lists with RecyclerView ..............................................................................
Updating CriminalIntent’s Model Layer .....................................................................
Singletons and centralized data storage ..............................................................
An Abstract Activity for Hosting a Fragment ..............................................................
A generic fragment-hosting layout ....................................................................
An abstract Activity class ................................................................................
RecyclerView, Adapter, and ViewHolder ....................................................................
ViewHolders and Adapters ..............................................................................
Using a RecyclerView ....................................................................................
A view to display ..........................................................................................
Implementing a ViewHolder and an Adapter .......................................................
Binding List Items .................................................................................................
Responding to Presses ............................................................................................
For the More Curious: ListView and GridView ...........................................................
For the More Curious: Singletons .............................................................................
Challenge: RecyclerView ViewTypes .........................................................................
9. Creating User Interfaces with Layouts and Widgets ..........................................................
Using the Graphical Layout Tool ..............................................................................
Introducing ConstraintLayout ...................................................................................

117
117
117
118
120
122
122
123
124
125
126
129
130
131
134
136
136
137
137
139
139
142
148
149
152
153
154
155
156
157
159
159
161
161
162
167
168
171
173
173
176
178
179
179
180
181
182
183
ix

Android Programming

10.

11.

12.

13.

x

Using ConstraintLayout ..................................................................................
The graphical editor .......................................................................................
Making room ................................................................................................
Adding widgets .............................................................................................
ConstraintLayout’s inner workings ....................................................................
Editing properties ...........................................................................................
Making list items dynamic ..............................................................................
More on Layout Attributes ......................................................................................
Screen pixel densities and dp and sp .................................................................
Margins vs padding ........................................................................................
Styles, themes, and theme attributes ..................................................................
Android’s design guidelines .............................................................................
The Graphical Layout Tools and You ........................................................................
Challenge: Formatting the Date ................................................................................
Using Fragment Arguments ........................................................................................
Starting an Activity from a Fragment ........................................................................
Putting an extra .............................................................................................
Retrieving an extra .........................................................................................
Updating CrimeFragment’s view with Crime data ................................................
The downside to direct retrieval ........................................................................
Fragment Arguments ..............................................................................................
Attaching arguments to a fragment ....................................................................
Retrieving arguments ......................................................................................
Reloading the List ..................................................................................................
Getting Results with Fragments ................................................................................
For the More Curious: Why Use Fragment Arguments? ................................................
Challenge: Efficient RecyclerView Reloading .............................................................
Challenge: Improving CrimeLab Performance .............................................................
Using ViewPager ......................................................................................................
Creating CrimePagerActivity ....................................................................................
ViewPager and PagerAdapter ...........................................................................
Integrating CrimePagerActivity .........................................................................
FragmentStatePagerAdapter vs FragmentPagerAdapter .................................................
For the More Curious: How ViewPager Really Works ..................................................
For the More Curious: Laying Out Views in Code .......................................................
Challenge: Restoring CrimeFragment’s Margins ..........................................................
Challenge: Adding First and Last Buttons ..................................................................
Dialogs ...................................................................................................................
Creating a DialogFragment ......................................................................................
Showing a DialogFragment ..............................................................................
Setting a dialog’s contents ...............................................................................
Passing Data Between Two Fragments .......................................................................
Passing data to DatePickerFragment ..................................................................
Returning data to CrimeFragment .....................................................................
Challenge: More Dialogs .........................................................................................
Challenge: A Responsive DialogFragment ..................................................................
The Toolbar .............................................................................................................
AppCompat ...........................................................................................................

184
186
188
190
194
195
199
200
200
202
203
204
204
204
205
205
207
207
208
209
210
210
211
212
215
216
216
216
217
219
219
221
223
224
225
226
226
227
228
231
232
235
236
238
245
245
247
248

Android Programming
Using the AppCompat library ..........................................................................
Menus ..................................................................................................................
Defining a menu in XML ................................................................................
Creating the menu ..........................................................................................
Responding to menu selections .........................................................................
Enabling Hierarchical Navigation .............................................................................
How hierarchical navigation works ...................................................................
An Alternative Action Item .....................................................................................
Toggling the action item title ...........................................................................
“Just one more thing...” ...................................................................................
For the More Curious: Action Bar vs Toolbar .............................................................
Challenge: Deleting Crimes .....................................................................................
Challenge: Plural String Resources ...........................................................................
Challenge: An Empty View for the RecyclerView ........................................................
14. SQLite Databases .....................................................................................................
Defining a Schema .................................................................................................
Building Your Initial Database .................................................................................
Exploring files using Android Device Monitor ....................................................
Debugging database issues ..............................................................................
Gutting CrimeLab ..................................................................................................
Writing to the Database ..........................................................................................
Using ContentValues ......................................................................................
Inserting and updating rows .............................................................................
Reading from the Database ......................................................................................
Using a CursorWrapper ..................................................................................
Converting to model objects ............................................................................
For the More Curious: More Databases .....................................................................
For the More Curious: The Application Context ..........................................................
Challenge: Deleting Crimes .....................................................................................
15. Implicit Intents .........................................................................................................
Adding Buttons .....................................................................................................
Adding a Suspect to the Model Layer .......................................................................
Using a Format String ............................................................................................
Using Implicit Intents .............................................................................................
Parts of an implicit intent ................................................................................
Sending a crime report ....................................................................................
Asking Android for a contact ...........................................................................
Checking for responding activities ....................................................................
Challenge: ShareCompat .........................................................................................
Challenge: Another Implicit Intent ............................................................................
16. Taking Pictures with Intents .......................................................................................
A Place for Your Photo ...........................................................................................
File Storage ..........................................................................................................
Using FileProvider .........................................................................................
Designating a picture location ..........................................................................
Using a Camera Intent ............................................................................................
Firing the intent .............................................................................................
Scaling and Displaying Bitmaps ...............................................................................

248
250
250
256
259
260
261
262
263
265
267
267
268
268
269
270
271
274
276
277
278
278
279
281
282
284
287
288
288
289
290
291
293
294
295
296
299
302
304
304
305
305
308
309
310
311
311
313
xi

Android Programming

17.

18.

19.

20.

xii

Declaring Features ................................................................................................. 316
Challenge: Detail Display ........................................................................................ 316
Challenge: Efficient Thumbnail Load ........................................................................ 316
Two-Pane Master-Detail Interfaces ............................................................................... 317
Adding Layout Flexibility ....................................................................................... 319
Modifying SingleFragmentActivity ................................................................... 320
Creating a layout with two fragment containers ................................................... 321
Using an alias resource ................................................................................... 323
Creating tablet alternatives ............................................................................... 324
Activity: Fragment Boss .......................................................................................... 325
Fragment callback interfaces ............................................................................ 326
For the More Curious: More on Determining Device Size ............................................. 335
Challenge: Adding Swipe to Dismiss ........................................................................ 335
Localization ............................................................................................................. 337
Localizing Resources .............................................................................................. 338
Default resources ........................................................................................... 341
Checking string coverage using Translations Editor .............................................. 344
Targeting a region .......................................................................................... 345
Configuration Qualifiers .......................................................................................... 348
Prioritizing alternative resources ....................................................................... 349
Multiple qualifiers .......................................................................................... 351
Finding the best-matching resources .................................................................. 352
Testing Alternative Resources .................................................................................. 353
Challenge: Localizing Dates .................................................................................... 354
Accessibility ............................................................................................................ 355
TalkBack .............................................................................................................. 355
Explore by Touch .......................................................................................... 359
Linear navigation by swiping ........................................................................... 359
Making Non-Text Elements Readable by TalkBack ...................................................... 362
Adding content descriptions ............................................................................. 362
Making a widget focusable .............................................................................. 364
Creating a Comparable Experience ........................................................................... 365
Using labels to provide context ........................................................................ 367
For the More Curious: Using Accessibility Scanner ..................................................... 370
Challenge: Improving the List .................................................................................. 373
Challenge: Providing Enough Context for Data Entry ................................................... 373
Challenge: Announcing Events ................................................................................. 373
Data Binding and MVVM .......................................................................................... 375
Different Architectures: Why Bother? ........................................................................ 376
Creating BeatBox ................................................................................................... 376
Simple data binding ....................................................................................... 378
Importing Assets .................................................................................................... 382
Getting At Assets ................................................................................................... 384
Wiring Up Assets for Use ....................................................................................... 386
Binding to Data ..................................................................................................... 389
Creating a ViewModel .................................................................................... 391
Binding to a ViewModel ................................................................................. 392
Observable data ............................................................................................. 394

Android Programming

21.

22.

23.

24.

Accessing Assets ................................................................................................... 396
For the More Curious: More About Data Binding ........................................................ 396
Lambda expressions ....................................................................................... 397
More syntactic sugar ...................................................................................... 397
BindingAdapters ............................................................................................ 397
For the More Curious: Why Assets, Not Resources ...................................................... 398
For the More Curious: Non-Assets? .......................................................................... 398
Unit Testing and Audio Playback ................................................................................ 399
Creating a SoundPool ............................................................................................. 399
Loading Sounds ..................................................................................................... 400
Playing Sounds ...................................................................................................... 402
Test Dependencies .................................................................................................. 402
Creating a Test Class .............................................................................................. 403
Setting Up Your Test .............................................................................................. 405
Using mocked dependencies ............................................................................ 405
Writing Tests ......................................................................................................... 407
Testing object interactions ............................................................................... 407
Data Binding Callbacks .......................................................................................... 411
Unloading Sounds .................................................................................................. 412
Rotation and Object Continuity ................................................................................ 413
Retaining a fragment ...................................................................................... 414
Rotation and retained fragments ....................................................................... 414
For the More Curious: Whether to Retain .................................................................. 416
For the More Curious: Espresso and Integration Testing ................................................ 417
For the More Curious: Mocks and Testing .................................................................. 418
Challenge: Playback Speed Control ........................................................................... 419
Styles and Themes .................................................................................................... 421
Color Resources .................................................................................................... 422
Styles ................................................................................................................... 422
Style inheritance ............................................................................................ 424
Themes ................................................................................................................ 425
Modifying the theme ...................................................................................... 426
Adding Theme Colors ............................................................................................ 428
Overriding Theme Attributes .................................................................................... 429
Theme spelunking .......................................................................................... 429
Modifying Button Attributes .................................................................................... 433
For the More Curious: More on Style Inheritance ........................................................ 435
For the More Curious: Accessing Theme Attributes ..................................................... 436
XML Drawables ....................................................................................................... 437
Making Uniform Buttons ........................................................................................ 438
Shape Drawables ................................................................................................... 439
State List Drawables ............................................................................................... 441
Layer List Drawables ............................................................................................. 443
For the More Curious: Why Bother with XML Drawables? ........................................... 444
For the More Curious: Mipmap Images ..................................................................... 445
For the More Curious: 9-Patch Images ...................................................................... 446
Challenge: Button Themes ....................................................................................... 452
More About Intents and Tasks .................................................................................... 453
xiii

Android Programming

25.

26.

27.

28.
xiv

Setting Up NerdLauncher ........................................................................................ 454
Resolving an Implicit Intent ..................................................................................... 456
Creating Explicit Intents at Runtime .......................................................................... 460
Tasks and the Back Stack ........................................................................................ 462
Switching between tasks ................................................................................. 462
Starting a new task ......................................................................................... 464
Using NerdLauncher as a Home Screen ..................................................................... 466
Challenge: Icons .................................................................................................... 468
For the More Curious: Processes vs Tasks .................................................................. 468
For the More Curious: Concurrent Documents ............................................................ 471
HTTP and Background Tasks ..................................................................................... 473
Creating PhotoGallery ............................................................................................ 475
Networking Basics ................................................................................................. 477
Asking permission to network .......................................................................... 479
Using AsyncTask to Run on a Background Thread ...................................................... 479
You and Your Main Thread ..................................................................................... 481
Beyond the main thread .................................................................................. 482
Fetching JSON from Flickr ..................................................................................... 483
Parsing JSON text .......................................................................................... 487
From AsyncTask Back to the Main Thread ................................................................. 491
Cleaning Up AsyncTasks ........................................................................................ 495
For the More Curious: More on AsyncTask ................................................................ 496
For the More Curious: Alternatives to AsyncTask ........................................................ 497
Challenge: Gson .................................................................................................... 498
Challenge: Paging .................................................................................................. 498
Challenge: Dynamically Adjusting the Number of Columns .......................................... 498
Loopers, Handlers, and HandlerThread ......................................................................... 499
Preparing RecyclerView to Display Images ................................................................ 499
Downloading Lots of Small Things ........................................................................... 502
Communicating with the Main Thread ....................................................................... 502
Assembling a Background Thread ............................................................................ 504
Messages and Message Handlers .............................................................................. 506
Message anatomy ........................................................................................... 506
Handler anatomy ............................................................................................ 507
Using handlers .............................................................................................. 508
Passing handlers ............................................................................................ 512
For the More Curious: AsyncTasks vs Threads ............................................................ 518
For the More Curious: Solving the Image Downloading Problem .................................... 518
For the More Curious: StrictMode ............................................................................ 519
Challenge: Preloading and Caching ........................................................................... 520
Search .................................................................................................................... 521
Searching Flickr .................................................................................................... 521
Using SearchView .................................................................................................. 526
Responding to SearchView user interactions ....................................................... 530
Simple Persistence with Shared Preferences ................................................................ 532
Polishing Your App ................................................................................................ 536
Challenge: Polishing Your App Some More ................................................................ 536
Background Services ................................................................................................. 537

Android Programming
Creating an IntentService ........................................................................................ 537
What Services Are For ........................................................................................... 540
Safe background networking ............................................................................ 540
Looking for New Results ........................................................................................ 542
Delayed Execution with AlarmManager ..................................................................... 544
Being a good citizen: using alarms the right way ................................................. 545
PendingIntent ................................................................................................ 547
Managing alarms with PendingIntent ................................................................. 547
Controlling Your Alarm .......................................................................................... 548
Notifications .......................................................................................................... 551
Challenge: Notifications on Android Wear .................................................................. 553
For the More Curious: Service Details ....................................................................... 553
What a service does (and does not do) ............................................................... 553
A service’s lifecycle ....................................................................................... 554
Non-sticky services ........................................................................................ 554
Sticky services ............................................................................................... 554
Bound services .............................................................................................. 555
For the More Curious: JobScheduler and JobServices ................................................... 556
JobScheduler and the future of background work ................................................. 559
Challenge: Using JobService on Lollipop ................................................................... 559
For the More Curious: Sync Adapters ....................................................................... 559
29. Broadcast Intents ...................................................................................................... 561
Regular Intents vs Broadcast Intents .......................................................................... 561
Receiving a System Broadcast: Waking Up on Boot ..................................................... 562
Creating and registering a standalone receiver ..................................................... 562
Using receivers .............................................................................................. 565
Filtering Foreground Notifications ............................................................................ 567
Sending broadcast intents ................................................................................ 567
Creating and registering a dynamic receiver ........................................................ 568
Limiting broadcasts to your app using private permissions ..................................... 570
Passing and receiving data with ordered broadcasts .............................................. 572
Receivers and Long-Running Tasks ........................................................................... 577
For the More Curious: Local Events .......................................................................... 578
Using EventBus ............................................................................................. 578
Using RxJava ................................................................................................ 579
For the More Curious: Detecting the Visibility of Your Fragment .................................... 580
30. Browsing the Web and WebView ................................................................................. 581
One Last Bit of Flickr Data ..................................................................................... 582
The Easy Way: Implicit Intents ................................................................................ 585
The Harder Way: WebView ..................................................................................... 586
Using WebChromeClient to spruce things up ...................................................... 590
Proper Rotation with WebView ................................................................................ 593
Dangers of handling configuration changes ......................................................... 593
For the More Curious: Injecting JavaScript Objects ...................................................... 594
For the More Curious: WebView Updates .................................................................. 595
Challenge: Using the Back Button for Browser History ................................................ 595
Challenge: Supporting Non-HTTP Links .................................................................... 596
31. Custom Views and Touch Events ................................................................................. 597
xv

Android Programming

32.

33.

34.

35.

xvi

Setting Up the DragAndDraw Project ........................................................................
Creating a Custom View .........................................................................................
Creating BoxDrawingView ..............................................................................
Handling Touch Events ...........................................................................................
Tracking across motion events ..........................................................................
Rendering Inside onDraw(Canvas) ............................................................................
Challenge: Saving State ..........................................................................................
Challenge: Rotating Boxes ......................................................................................
Property Animation ...................................................................................................
Building the Scene .................................................................................................
Simple Property Animation .....................................................................................
View transformation properties .........................................................................
Using different interpolators ............................................................................
Color evaluation ............................................................................................
Playing Animators Together .....................................................................................
For the More Curious: Other Animation APIs .............................................................
Legacy animation tools ...................................................................................
Transitions ....................................................................................................
Challenges ............................................................................................................
Locations and Play Services .......................................................................................
Locations and Libraries ...........................................................................................
Google Play Services ......................................................................................
Creating Locatr ......................................................................................................
Play Services and Location Testing on Emulators ........................................................
Mock location data .........................................................................................
Building Out Locatr ...............................................................................................
Setting Up Google Play Services ..............................................................................
Location permissions ......................................................................................
Using Google Play Services .....................................................................................
Flickr Geosearch ....................................................................................................
Getting a Location Fix ............................................................................................
Asking for Permission at Runtime ............................................................................
Checking for permissions ................................................................................
Find and Display an Image ......................................................................................
Challenge: Permissions Rationale .............................................................................
Challenge: Progress ................................................................................................
Maps ......................................................................................................................
Importing Play Services Maps ..................................................................................
Mapping on Android ..............................................................................................
Getting a Maps API Key .........................................................................................
Setting Up Your Map .............................................................................................
Getting More Location Data ....................................................................................
Working with Your Map .........................................................................................
Drawing on the map .......................................................................................
For the More Curious: Teams and API Keys ...............................................................
Material Design ........................................................................................................
Material Surfaces ...................................................................................................
Elevation and Z values ....................................................................................

598
600
600
602
604
606
608
608
609
609
612
614
616
616
618
620
620
620
620
621
622
622
623
623
624
627
629
630
631
633
634
637
638
644
646
646
647
647
647
648
650
652
654
657
659
661
662
664

Android Programming
State list animators .........................................................................................
Animation Tools ....................................................................................................
Circular reveal ...............................................................................................
Shared element transitions ...............................................................................
View Components ..................................................................................................
Cards ...........................................................................................................
Floating action buttons ....................................................................................
Snackbars .....................................................................................................
More on Material Design ........................................................................................
36. Afterword ................................................................................................................
The Final Challenge ...............................................................................................
Shameless Plugs ....................................................................................................
Thank You ............................................................................................................
Index ...........................................................................................................................

665
667
667
669
673
673
675
676
677
679
679
679
680
681

xvii

Learning Android
As a beginning Android programmer, you face a steep learning curve. Learning Android is like moving
to a foreign city. Even if you speak the language, it will not feel like home at first. Everyone around
you seems to understand things that you are missing. Things you already knew turn out to be dead
wrong in this new context.
Android has a culture. That culture speaks Java, but knowing Java is not enough. Getting your head
around Android requires learning many new ideas and techniques. It helps to have a guide through
unfamiliar territory.
That’s where we come in. At Big Nerd Ranch, we believe that to be an Android programmer, you
must:
• write Android applications
• understand what you are writing
This guide will help you do both. We have trained thousands of professional Android programmers
using it. We lead you through writing several Android applications, introducing concepts and
techniques as needed. When there are rough spots, or when some things are tricky or obscure, you will
face them head on, and we will do our best to explain why things are the way they are.
This approach allows you to put what you have learned into practice in a working app right away rather
than learning a lot of theory and then having to figure out how to apply it all later. You will come away
with the experience and understanding you need to get going as an Android developer.

Prerequisites
To use this book, you need to be familiar with Java, including classes and objects, interfaces, listeners,
packages, inner classes, anonymous inner classes, and generic classes.
If these concepts do not ring a bell, you will be in the weeds by page 2. Start instead with an
introductory Java book and return to this book afterward. There are many excellent introductory books
available, so you can choose one based on your programming experience and learning style.
If you are comfortable with object-oriented programming concepts, but your Java is a little rusty, you
will probably be OK. We will provide some brief reminders about Java specifics (like interfaces and
anonymous inner classes). Keep a Java reference handy in case you need more support as you go
through the book.

What’s New in the Third Edition?
This third edition adds coverage of a couple of new tools: constraint layout (plus its associated editor)
and data binding. New chapters have also been added on unit testing, accessibility, the MVVM
architectural style, and localization. Toward the end of the book, we have added material on the new
runtime permissions system. Finally, many new challenges and For the More Curious sections have
been added and many others have been revised throughout the book.
xix

Learning Android

How to Use This Book
This book is not a reference book. Its goal is to get you over the initial hump to where you can get
the most out of the reference and recipe books available. It is based on our five-day class at Big Nerd
Ranch. As such, it is meant to be worked through from the beginning. Chapters build on each other,
and skipping around is unproductive.
In our classes, students work through these materials, but they also benefit from the right environment
– a dedicated classroom, good food and comfortable board, a group of motivated peers, and an
instructor to answer questions.
As a reader, you want your environment to be similar. That means getting a good night’s rest and
finding a quiet place to work. These things can help, too:
• Start a reading group with your friends or coworkers.
• Arrange to have blocks of focused time to work on chapters.
• Participate in the forum for this book at forums.bignerdranch.com.
• Find someone who knows Android to help you out.

How This Book Is Organized
As you work through this book, you will write eight Android apps. A couple are very simple and take
only a chapter to create. Others are more complex. The longest app spans 13 chapters. All are designed
to teach you important concepts and techniques and give you direct experience using them.
GeoQuiz

In your first app, you will explore the fundamentals of Android projects,
activities, layouts, and explicit intents.

CriminalIntent

The largest app in the book, CriminalIntent lets you keep a record of your
colleagues’ lapses around the office. You will learn to use fragments, masterdetail interfaces, list-backed interfaces, menus, the camera, implicit intents,
and more.

BeatBox

Intimidate your foes with this app while you learn more about fragments,
media playback, MVVM architecture, data binding, testing, themes, and
drawables.

NerdLauncher

Building this custom launcher will give you insight into the intent system and
tasks.

PhotoGallery

A Flickr client that downloads and displays photos from Flickr’s public
feed, this app will take you through services, multithreading, accessing web
services, and more.

xx

Challenges
DragAndDraw

In this simple drawing app, you will learn about handling touch events and
creating custom views.

Sunset

In this toy app, you will create a beautiful representation of a sunset over open
water while learning about animations.

Locatr

This app lets you query Flickr for pictures around your current location and
display them on a map. In it, you will learn how to use location services and
maps.

Challenges
Most chapters have a section at the end with exercises for you to work through. This is your
opportunity to use what you have learned, explore the documentation, and do some problem solving on
your own.
We strongly recommend that you do the challenges. Going off the beaten path and finding your way
will solidify your learning and give you confidence with your own projects.
If you get lost, you can always visit forums.bignerdranch.com for some assistance.

Are you more curious?
There are also sections at the ends of chapters labeled “For the More Curious.” These sections offer
deeper explanations or additional information about topics presented in the chapter. The information in
these sections is not absolutely essential, but we hope you will find it interesting and useful.

Code Style
There are two areas where our choices differ from what you might see elsewhere in the Android
community:
We use anonymous inner classes for listeners.
This is mostly a matter of opinion. We find it makes for cleaner code in the applications in this
book because it puts the listener’s method implementations right where you want to see them. In
high-performance contexts or large applications, anonymous inner classes may cause problems,
but for most circumstances they work fine.
After we introduce fragments in Chapter 7, we use them for all user interfaces.
Fragments are not an absolutely necessary tool, but we find that, when used correctly, they are a
valuable tool in any Android developer’s toolkit. Once you get comfortable with fragments, they
are not that difficult to work with. Fragments have clear advantages over activities that make
them worth the effort, including flexibility in building and presenting your user interfaces.

xxi

Learning Android

Typographical Conventions
All code and XML listings are in a fixed-width font. Code or XML that you need to type in is always
bold. Code or XML that should be deleted is struck through. For example, in the following method
implementation, you are deleting the call to makeText(…) and adding the call to checkAnswer(true).
@Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this, R.string.incorrect_toast,
Toast.LENGTH_SHORT).show();
checkAnswer(true);
}

Android Versions
This book teaches Android development for all widely used versions of Android. As of this writing,
that is Android 4.4 (KitKat) - Android 7.1 (Nougat). While there is a small amount of market-share on
older versions of Android, we find that for most developers the amount of effort required to support
those versions is not worth the reward. For more info on the support of versions of Android earlier
than 4.4, see earlier editions of this book. The second edition targeted Android 4.1 and up, and the first
edition targeted Android 2.3 and up.
As Android releases new versions, the techniques you learn in this book will continue to work thanks
to Android’s backward compatibility support (see Chapter 6 for details). We will keep track of changes
at forums.bignerdranch.com and offer notes on using this book with the latest version.

xxii

The Necessary Tools
To get started with this book, you will need Android Studio. Android Studio is an integrated
development environment used for Android development that is based off of the popular IntelliJ IDEA.
An install of Android Studio includes:
Android SDK
the latest version of the Android SDK
Android SDK tools and platform tools
tools for debugging and testing your apps
A system image for the Android emulator
lets you create and test your apps on different virtual devices
As of this writing, Android Studio is under active development and is frequently updated. Be aware
that you may find differences between your version of Android Studio and what you see in this book.
Visit forums.bignerdranch.com for help with these differences.

Downloading and Installing Android Studio
Android Studio is available from Android’s developer site at developer.android.com/sdk/.
If you do not already have it installed, you will need to install the Java Development Kit (JDK 8),
which you can download from www.oracle.com.
If you are still having problems, return to developer.android.com/sdk/ for more information.

Downloading Earlier SDK Versions
Android Studio provides the SDK and the emulator system image from the latest platform. However,
you may want to test your apps on earlier versions of Android.
You can get components for each platform using the Android SDK Manager. In Android Studio, select
Tools → Android → SDK Manager. (You will only see the Tools menu if you have a project open. If
you have not created a project yet, you can instead access the SDK Manager from the Android Setup
Wizard screen. Under the Quick Start section, select Configure → SDK Manager.)

xxiii

The Necessary Tools
The SDK Manager is shown in Figure 1.

Figure 1 Android SDK Manager

Select and install each version of Android that you want to test with. Note that downloading these
components may take a while.
The Android SDK Manager is also how to get Android’s latest releases, like a new platform or an
update of the tools.

A Hardware Device
The emulator is useful for testing apps. However, it is no substitute for an actual Android device when
measuring performance. If you have a hardware device, we recommend using that device at times
when working through this book.

xxiv

1

Your First Android Application
This first chapter is full of new concepts and moving parts required to build an Android application. It
is OK if you do not understand everything by the end of this chapter. You will be revisiting these ideas
in greater detail as you proceed through the book.
The application you are going to create is called GeoQuiz. GeoQuiz tests the user’s knowledge of
geography. The user presses TRUE or FALSE to answer the question on screen, and GeoQuiz provides
instant feedback.
Figure 1.1 shows the result of a user pressing the TRUE button.

Figure 1.1 Do you come from a land down under?

1

Chapter 1 Your First Android Application

App Basics
Your GeoQuiz application will consist of an activity and a layout:
• An activity is an instance of Activity, a class in the Android SDK. An activity is responsible for
managing user interaction with a screen of information.
You write subclasses of Activity to implement the functionality that your app requires. A simple
application may need only one subclass; a complex application can have many.
GeoQuiz is a simple app, so it will have a single Activity subclass named QuizActivity.
will manage the user interface, or UI, shown in Figure 1.1.

QuizActivity

• A layout defines a set of UI objects and their positions on the screen. A layout is made up of
definitions written in XML. Each definition is used to create an object that appears on screen, like
a button or some text.
GeoQuiz will include a layout file named activity_quiz.xml. The XML in this file will define
the UI shown in Figure 1.1.
The relationship between QuizActivity and activity_quiz.xml is diagrammed in Figure 1.2.

Figure 1.2 QuizActivity manages what activity_quiz.xml defines

With those ideas in mind, let’s build an app.

2

Creating an Android Project

Creating an Android Project
The first step is to create an Android project. An Android project contains the files that make up an
application. To create a new project, first open Android Studio.
If this is your first time running Android Studio, you will see the Welcome dialog, as in Figure 1.3.

Figure 1.3 Welcome to Android Studio

From the dialog, choose Start a new Android Studio project. If you do not see the dialog, you may have
created projects before. In this case, choose File → New → New Project....

3

Chapter 1 Your First Android Application
You should see the New Project wizard (Figure 1.4). In the first screen of the wizard, enter GeoQuiz
as the application name. For the company domain, enter android.bignerdranch.com. As you do this,
you will see the generated package name change to com.bignerdranch.android.geoquiz. For the
project location, you can use any location on your filesystem that you want.

Figure 1.4 Creating a new application

Notice that the package name uses a “reverse DNS” convention: The domain name of your
organization is reversed and suffixed with further identifiers. This convention keeps package names
unique and distinguishes applications from each other on a device and on Google Play.

4

Creating an Android Project
Click Next. The next screen allows you to specify details about which devices you want to support.
GeoQuiz will only support phones, so just check Phone and Tablet. Select a minimum SDK version
of API 19: Android 4.4 (KitKat) (Figure 1.5). You will learn about the different versions of Android in
Chapter 6.

Figure 1.5 Specifying device support

5

Chapter 1 Your First Android Application
Click Next.
In the next screen, you are prompted to choose a template for the first screen of GeoQuiz (Figure 1.6).
You want the most basic template available. Choose Empty Activity and click Next.
(Android Studio updates regularly, so your wizard may look slightly different from what we are
showing you. This is usually not a problem; the choices should be similar. If your wizard looks very
different, then the tools have changed more drastically. Do not panic. Head to this book’s forum at
forums.bignerdranch.com and we will help you navigate the latest version.)

Figure 1.6 Choosing a type of activity

6

Creating an Android Project
In the final dialog of this wizard, name the activity subclass QuizActivity (Figure 1.7). Notice the
Activity suffix on the class name. This is not required, but it is an excellent convention to follow.

Figure 1.7 Configuring the new activity

Leave Generate Layout File checked. The layout name will automatically update to activity_quiz
to reflect the activity’s new name. The layout name reverses the order of the activity name, is all
lowercase, and has underscores between words. This naming style is recommended for layouts as well
as other resources that you will learn about later.
If your version of Android Studio has other options on this screen, leave them as is. Click Finish.
Android Studio will create and open your new project.

7

Chapter 1 Your First Android Application

Navigating in Android Studio
Android Studio opens your project in a window, as shown in Figure 1.8.
The different panes of the project window are called tool windows.
The lefthand view is the project tool window. From here, you can view and manage the files associated
with your project.
The main view is the editor. To get you started, Android Studio has opened QuizActivity.java in the
editor.

Figure 1.8 A fresh project window

You can toggle the visibility of the various tool windows by clicking on their names in the strips of tool
buttons on the left, right, and bottom of the screen. There are keyboard shortcuts for many of these as
well. If you do not see the tool button strips, click the gray square button in the lower-left corner of the
main window or choose View → Tool Buttons.

8

Laying Out the UI

Laying Out the UI
Open app/res/layout/activity_quiz.xml. If you see a graphical preview of the file, select the Text
tab at the bottom to see the backing XML.
Currently, activity_quiz.xml defines the default activity layout. The defaults change frequently, but
the XML will look something like Listing 1.1.

Listing 1.1 Default activity layout (activity_quiz.xml)




The default activity layout defines two widgets: a RelativeLayout and a TextView.
Widgets are the building blocks you use to compose a UI. A widget can show text or graphics, interact
with the user, or arrange other widgets on the screen. Buttons, text input controls, and checkboxes are
all types of widgets.
The Android SDK includes many widgets that you can configure to get the appearance and behavior
you want. Every widget is an instance of the View class or one of its subclasses (such as TextView or
Button).

9

Chapter 1 Your First Android Application
Figure 1.9 shows how the RelativeLayout and TextView defined in Listing 1.1 would appear on
screen.

Figure 1.9 Default widgets as seen on screen

But these are not the widgets you are looking for. The interface for QuizActivity requires five
widgets:
• a vertical LinearLayout
• a TextView
• a horizontal LinearLayout
• two Buttons

10

Laying Out the UI
Figure 1.10 shows how these widgets compose QuizActivity’s interface.

Figure 1.10 Planned widgets as seen on screen

Now you need to define these widgets in activity_quiz.xml.
In the project tool window, find the app/res/layout directory, reveal its contents, and open
activity_quiz.xml. Make the changes shown in Listing 1.2. The XML that you need to delete is
struck through, and the XML that you need to add is in bold font. This is the pattern we will use
throughout this book.

11

Chapter 1 Your First Android Application
Do not worry about understanding what you are typing; you will learn how it works next. However, do
be careful. Layout XML is not validated, and typos will cause problems sooner or later.
You will see errors on the three lines that start with android:text. Ignore these errors for now; you
will fix them soon.

Listing 1.2 Defining widgets in XML (activity_quiz.xml)