The Busy Coder's Guide To Android Development Version 8.9 Mark L. Murphy 2017
User Manual:
Open the PDF directly: View PDF
.
Page Count: 4495
| Download | |
| Open PDF In Browser | View PDF |
The Busy Coder's Guide to Android Development
by Mark L. Murphy
The Busy Coder's Guide to Android Development
by Mark L. Murphy
Copyright © 2008-2017 CommonsWare, LLC. All Rights Reserved.
Printed in the United States of America.
Printing History:
December 2017:
Version 8.9
ISBN: 978-0-9816780-0-9
The CommonsWare name and logo, “Busy Coder's Guide”, and related trade dress are trademarks of CommonsWare,
LLC.
All other trademarks referenced in this book are trademarks of their respective firms.
The publisher and author(s) assume no responsibility for errors or omissions or for damages resulting from the use of the
information contained herein.
Table of Contents
Headings formatted in bold-italic have changed since the last version.
• Preface
◦ Welcome to the Book! ...................................................................... xliii
◦ The Book’s Structure ........................................................................ xliii
◦ The Trails ................................................................................ xliv
◦ About the Updates ................................................................................. l
◦ What’s New in Version 8.9? ......................................................... l
◦ Warescription ........................................................................................ l
◦ About the APK Edition ......................................................................... li
◦ Book Bug Bounty ................................................................................. lii
◦ Source Code and Its License .............................................................. liii
◦ Creative Commons and the Four-to-Free (42F) Guarantee ...... liv
◦ Acknowledgments ............................................................................... liv
• Key Android Concepts
◦ Android Applications ............................................................................ 1
◦ Android Devices .......................................................................... 6
◦ Don’t Be Scared .................................................................................... 10
• Choosing Your Development Toolchain
◦ Android Studio ..................................................................................... 11
◦ Eclipse .................................................................................................... 11
◦ IntelliJ IDEA ............................................................................... 12
◦ Command-Line Builds via Gradle ...................................................... 12
◦ Yet Other Alternatives ......................................................................... 12
◦ IDEs… And This Book ........................................................................... 13
◦ What We Are Not Covering ................................................................. 13
• Tutorial #1 - Installing the Tools
◦ But First, Some Notes About Android’s Emulator ............................. 15
◦ Step #1: Checking Your Hardware ...................................................... 16
◦ Step #2: Setting Up Java and 32-Bit Linux Support ............................ 17
◦ Step #3: Install Android Studio .................................................. 17
◦ Step #4: Install the SDKs and Add-Ons ............................................. 19
◦ In Our Next Episode… ......................................................................... 27
• Android and Projects
◦ Projects and Android Studio ............................................................... 29
◦ Starter Project Generators ................................................................... 35
• Tutorial #2 - Creating a Stub Project
i
•
•
•
•
•
◦ About Our Tutorial Project ................................................................. 37
◦ About the Rest of the Tutorials ........................................................... 38
◦ About Our Tools .................................................................................. 38
◦ Step #1: Importing the Project ............................................................ 38
◦ Step #2: Get Ready for the x86 Emulator ........................................... 42
◦ Step #3: Set Up the AVD ...................................................................... 43
◦ Step #4: Set Up the Device .................................................................. 50
◦ Step #5: Running the Project .............................................................. 55
◦ In Our Next Episode… ......................................................................... 56
Getting Around Android Studio
◦ Navigating The Project Explorer ......................................................... 57
◦ Running Projects ................................................................................ 60
◦ Viewing Output ................................................................................... 61
◦ Accessing Android Tools ..................................................................... 62
◦ Android Studio and Release Channels .............................................. 64
◦ Visit the Trails! ..................................................................................... 65
Contents of Android Projects
◦ What You Get, In General ................................................................... 67
◦ More About the Directory Structure .................................................. 70
◦ What You Get Out Of It ...................................................................... 72
Introducing Gradle and the Manifest
◦ Gradle: The Big Questions .................................................................. 73
◦ Obtaining Gradle ................................................................................. 75
◦ Versions of Gradle and the Android Gradle Plugin .................. 77
◦ Gradle Environment Variables ............................................................ 78
◦ Examining the Gradle Files ...................................................... 78
◦ Introducing the Manifest .................................................................... 81
◦ Things In Common Between the Manifest and Gradle .................... 82
◦ Other Gradle Items of Note ............................................................... 84
◦ Where’s the GUI? ................................................................................. 85
◦ The Rest of the Manifest ..................................................................... 85
◦ Learning More About Gradle ............................................................. 88
◦ Visit the Trails! .................................................................................... 88
Tutorial #3 - Manifest Changes
◦ Some Notes About Relative Paths ..................................................... 89
◦ Step #1: Supporting Screens ............................................................... 89
◦ Step #2: Blocking Backups ................................................................. 90
◦ Step #3: Ignoring Lint ......................................................................... 90
◦ In Our Next Episode… ......................................................................... 92
Some Words About Resources
◦ String Theory ....................................................................................... 93
ii
◦ Got the Picture? .................................................................................. 99
◦ Dimensions ........................................................................................ 103
◦ The Resource That Shall Not Be Named… Yet ................................. 105
• Icons
•
•
•
•
•
•
◦ App Icons… And Everything Else .............................................. 107
◦ Creating an App Icon with the Asset Studio ........................... 108
◦ Creating Other Icons with the Asset Studio ..................................... 113
Tutorial #4 - Adjusting Our Resources
◦ Step #1: Changing the Name .............................................................. 115
◦ Step #2: Changing the Icon ................................................................ 116
◦ Step #3: Running the Result .............................................................. 120
◦ In Our Next Episode… ........................................................................ 121
The Theory of Widgets
◦ What Are Widgets? ............................................................................ 123
◦ Size, Margins, and Padding ................................................................ 125
◦ What Are Containers? ........................................................................ 125
◦ The Absolute Positioning Anti-Pattern ............................................ 126
◦ The Theme of This Section: Themes ................................................. 127
The Android User Interface
◦ The Activity ......................................................................................... 131
◦ Dissecting the Activity ....................................................................... 132
◦ Using XML-Based Layouts ....................................................... 133
Basic Widgets
◦ Common Concepts ................................................................... 137
◦ Introducing the Graphical Layout Editor ........................................ 140
◦ And Now, Some Notes About the Book’s Sample Projects ....... 149
◦ Assigning Labels ................................................................................ 150
◦ A Commanding Button ...................................................................... 155
◦ Fleeting Images .................................................................................. 158
◦ Fields of Green. Or Other Colors. ............................................ 164
◦ More Common Concepts ......................................................... 167
◦ Visit the Trails! ................................................................................... 170
Debugging Your App
◦ Get Thee To a Stack Trace .................................................................. 172
◦ The Case of the Confounding Class Cast .......................................... 173
◦ Point Break .......................................................................................... 174
The Classic Container Classes
◦ Introducing the Sampler App ............................................................ 175
◦ RTL and Your Layouts ....................................................................... 176
◦ LinearLayout and the Box Model ............................................ 177
◦ All Things Are Relative ............................................................ 201
iii
•
•
•
•
•
•
◦ Tabula Rasa ......................................................................................... 212
◦ Hey, What About ConstraintLayout? ............................................... 218
◦ Turning Back to RTL .......................................................................... 219
Other Common Widgets and Containers
◦ Just a Box to Check .................................................................. 221
◦ Don’t Like Checkboxes? How About Toggles or Switches? ............ 224
◦ Turn the Radio Up ............................................................................. 228
◦ Scrollwork ............................................................................................ 231
◦ Making Progress with ProgressBars ....................................... 234
◦ Framing the Scene ............................................................................. 235
◦ Visit the Trails! ................................................................................... 236
Tutorial #5 - Creating a Layout
◦ Step #1: Creating a New Layout Resource ........................................ 237
◦ Step #2: Defining the UI .................................................................... 238
◦ In Our Next Episode… ....................................................................... 243
GUI Building, Continued
◦ Making Your Selection ...................................................................... 245
◦ Including Includes .................................................................. 246
◦ Preview of Coming Attractions ......................................................... 248
AdapterViews and Adapters
◦ Adapting to the Circumstances ........................................................ 249
◦ Lists of Naughty and Nice ........................................................ 251
◦ Clicks versus Selections ........................................................... 253
◦ Spin Control ............................................................................. 257
◦ Grid Your Lions (Or Something Like That…) .......................... 260
◦ Fields: Now With 35% Less Typing! ......................................... 264
◦ Customizing the Adapter ................................................................. 268
◦ Visit the Trails! ................................................................................... 277
The WebView Widget
◦ Role of WebView ............................................................................... 279
◦ Daddy, Where Do WebViews Come From? .................................... 280
◦ Adding the Widget ........................................................................... 280
◦ Loading Content Via a URL ..................................................... 281
◦ Links and Redirects ........................................................................... 283
◦ Supporting JavaScript ........................................................................ 283
◦ Alternatives for Loading Content ..................................................... 284
◦ Listening for Events ........................................................................... 285
◦ Addressing the Link/Redirect Behavior ................................. 288
◦ Visit the Trails! .................................................................................. 290
Defining and Using Styles
◦ Styles: DIY DRY .................................................................................. 291
iv
•
•
•
•
•
◦ Elements of Style ............................................................................... 293
◦ Themes: Would a Style By Any Other Name… ............................... 296
◦ What Happens If You Have No Theme ............................................ 297
◦ Android Studio’s Theme Editor ........................................................ 297
Dependencies
◦ What’s a Dependency? ...................................................................... 303
◦ Dependency Scopes ........................................................................... 304
◦ Depending on a Local JAR ................................................................ 305
◦ What’s an Artifact? ............................................................................ 306
◦ Artifacts and Repositories ................................................................. 306
◦ Major Library Families from Google ................................................ 306
◦ Requesting Dependencies ...................................................... 307
◦ The Android Support Library .................................................. 310
Tutorial #6 - Adding a Library
◦ Step #1: Getting Rid of Existing Cruft ................................................ 315
◦ Step #2: Requesting New Dependencies .......................................... 316
◦ In Our Next Episode… ....................................................................... 318
Introducing ConstraintLayout
◦ Why Another Container? ......................................................... 319
◦ Comparing with the Classics ............................................................. 321
◦ Getting ConstraintLayout .................................................................. 321
◦ Using Widgets and Containers from Libraries ................................ 323
◦ Using a ConstraintLayout ................................................................. 323
◦ Converting Existing Layouts ............................................................. 339
◦ Visit the Trails! ................................................................................... 341
The Action Bar
◦ Bar Hopping ............................................................................. 343
◦ Yet Another History Lesson .............................................................. 349
◦ Your Action Bar Options ................................................................... 350
◦ Setting the Target .............................................................................. 352
◦ Defining the Resource ....................................................................... 353
◦ Applying the Resource ...................................................................... 356
◦ Responding to Events ........................................................................ 356
◦ The Rest of the Sample Activity ....................................................... 357
◦ MENU Key, We Hardly Knew Ye ...................................................... 363
◦ Action Bars, Live in Living Color! ........................................... 364
◦ Visit the Trails! ................................................................................... 374
Vector Drawables
◦ Getting the Artwork .......................................................................... 375
◦ VectorDrawableCompat .................................................................... 380
◦ Other VectorDrawable Backports ..................................................... 388
v
• Tutorial #7 - Setting Up the Action Bar
◦ Step #1: Adding Some Icons .............................................................. 389
◦ Step #2: Defining Some Options ...................................................... 391
◦ Step #3: Loading and Responding to Our Options ......................... 394
◦ Step #4: Supporting Older Devices .................................................. 395
◦ Step #5: Trying It Out ........................................................................ 396
◦ In Our Next Episode… ....................................................................... 398
• Android’s Process Model
◦ When Processes Are Created ............................................................ 399
◦ BACK, HOME, and Your Process ..................................................... 400
◦ Termination ........................................................................................ 401
◦ Foreground Means “I Love You” ....................................................... 402
◦ You and Your Heap ............................................................................ 402
• Activities and Their Lifecycles
◦ Creating Your Second (and Third and…) Activity .......................... 404
◦ Warning! Contains Explicit Intents! ................................................ 408
◦ Using Implicit Intents ............................................................ 410
◦ Extra! Extra! ........................................................................................ 416
◦ Pondering Parcelable ......................................................................... 417
◦ Asynchronicity and Results .............................................................. 419
◦ Schroedinger’s Activity ...................................................................... 419
◦ Life, Death, and Your Activity ................................................ 420
◦ When Activities Die .......................................................................... 422
◦ Walking Through the Lifecycle ........................................................ 423
◦ Recycling Activities ........................................................................... 426
◦ Application: Transcending the Activity ........................................... 427
◦ The Case of the Invisible Activity ..................................................... 428
• Tutorial #8 - Setting Up An Activity
◦ Step #1: Creating the Stub Activity Class and Manifest Entry ........ 431
◦ Step #2: Launching Our Activity ...................................................... 433
◦ In Our Next Episode… ....................................................................... 434
• The Tactics of Fragments
◦ The Six Questions .............................................................................. 435
◦ Where You Get Your Fragments From ............................................. 438
◦ Your First Fragment ........................................................................... 438
◦ The Fragment Lifecycle Methods ..................................................... 442
◦ Your First Dynamic Fragment ........................................................... 443
◦ Fragments and the Action Bar ......................................................... 446
◦ Fragments Within Fragments: Just Say “Maybe” ............................ 448
◦ Fragments and Multiple Activities .................................................. 448
• Tutorial #9 - Starting Our Fragments
vi
•
•
•
•
•
•
◦ Step #1: Create a SimpleContentFragment ...................................... 451
◦ Step #2: Examining SimpleContentFragment ................................. 453
◦ In Our Next Episode… ....................................................................... 454
Swiping with ViewPager
◦ Pieces of a Pager ................................................................................. 455
◦ Paging Fragments .............................................................................. 456
◦ Paging Other Stuff ............................................................................. 461
◦ Indicators ........................................................................................... 462
◦ Revisiting the Containers Sampler ................................................... 465
Tutorial #10 - Rigging Up a ViewPager
◦ Step #1: Add a ViewPager to the Layout ........................................... 473
◦ Step #2: Creating a ContentsAdapter ............................................... 474
◦ Step #3: Setting Up the ViewPager ................................................... 475
◦ In Our Next Episode… ....................................................................... 478
Resource Sets and Configurations
◦ What’s a Configuration? And How Do They Change? .................... 479
◦ Configurations and Resource Sets ................................................... 480
◦ Screen Size and Orientation ............................................................. 481
◦ Coping with Complexity .................................................................. 484
◦ Choosing The Right Resource ........................................................... 485
◦ API-Versioned Resources ................................................................. 489
◦ Default Change Behavior .................................................................. 491
◦ State Saving Scenarios ....................................................................... 493
◦ Your Options for Configuration Changes ....................................... 494
◦ Blocking Rotations ............................................................................ 508
◦ And Now, a Word From the Android Project View ........................ 509
◦ Configuration Challenges .................................................................. 510
Material Design Basics
◦ Your App, in Technicolor! .................................................................. 515
Dealing with Threads
◦ The Main Application Thread ........................................................... 521
◦ Getting to the Background ................................................................ 523
◦ Asyncing Feeling ................................................................................ 523
◦ Alternatives to AsyncTask ................................................................. 532
◦ And Now, The Caveats ....................................................................... 534
◦ Event Buses ........................................................................................ 535
◦ Visit the Trails! ................................................................................... 543
Requesting Permissions
◦ Frequently-Asked Questions About Permissions ........................... 546
◦ Characteristics of Permissions ........................................................... 551
◦ New Permissions in Old Applications .............................................. 554
vii
•
•
•
•
◦ Android 6.0+ Runtime Permission System ...................................... 555
◦ A Simple Runtime Permission Abstraction ..................................... 567
Assets, Files, and Data Parsing
◦ Packaging Files with Your App .......................................................... 571
◦ Files and Android .............................................................................. 573
◦ Working with Internal Storage ......................................................... 574
◦ Working with External Storage ......................................................... 583
◦ Removable Storage ........................................................................... 590
◦ Multiple User Accounts ..................................................................... 591
◦ Linux Filesystems: You Sync, You Win ............................................. 591
◦ StrictMode: Avoiding Janky Code ..................................................... 593
◦ Files, and Your Development Machine ............................................ 595
◦ XML Parsing Options ........................................................................ 603
◦ JSON Parsing Options ...................................................................... 604
◦ Using Files with Implicit Intents ..................................................... 604
◦ Visit the Trails! ................................................................................... 605
Tutorial #11 - Adding Simple Content
◦ Step #1: Adding Some Content ........................................................ 607
◦ Step #2: Using SimpleContentFragment ......................................... 608
◦ Step #3: Launching Our Activities, For Real This Time ................. 609
◦ Step #4: Getting a Bit More Material ................................................ 610
◦ Step #5: Seeing the Results ............................................................... 612
◦ In Our Next Episode… ....................................................................... 614
Tutorial #12 - Displaying the Book
◦ Step #1: Adding a Book ...................................................................... 615
◦ Step #2: Creating a ModelFragment ................................................. 616
◦ Step #3: Defining Our Model ............................................................ 617
◦ Step #4: Examining Our Model ........................................................ 619
◦ Step #5: Defining Our Event ............................................................. 619
◦ Step #6: Loading Our Model ............................................................ 620
◦ Step #7: Registering for Events ......................................................... 623
◦ Step #8: Adapting the Content ......................................................... 624
◦ Step #9: Showing the Content When Loaded ................................. 625
◦ Step #10: Attaching our ModelFragment ......................................... 626
◦ Step #11: Showing the Content After a Configuration Change ....... 627
◦ Step #12: Setting Up StrictMode ....................................................... 628
◦ In Our Next Episode… ....................................................................... 629
Using Preferences
◦ Getting What You Want .................................................................... 631
◦ Stating Your Preference ..................................................................... 632
◦ Collecting Preferences with PreferenceFragment ........................... 633
viii
•
•
•
•
◦ Android Studio’s Preferences Editor ............................................... 640
◦ Types of Preferences .......................................................................... 641
Tutorial #13 - Using Some Preferences
◦ Step #1: Defining the Preference XML Files ..................................... 647
◦ Step #2: Creating Our Preference Activity ....................................... 651
◦ Step #3: Adding To Our Action Bar .................................................. 652
◦ Step #4: Launching the Preference Activity .................................... 652
◦ Step #5: Loading the Preferences ..................................................... 655
◦ Step #6: Saving the Last-Read Position ........................................... 659
◦ Step #7: Restoring the Last-Read Position ...................................... 660
◦ Step #8: Keeping the Screen On ....................................................... 661
◦ In Our Next Episode… ....................................................................... 663
SQLite Databases
◦ Introducing SQLite ........................................................................... 665
◦ Thinking About Schemas ................................................................. 666
◦ Start with a Helper ........................................................................... 666
◦ Getting Data Out ............................................................................... 671
◦ The Rest of the CRUD ....................................................................... 678
◦ Hey, What About Hibernate? .......................................................... 684
◦ But, What About Room? .................................................................. 684
◦ Visit the Trails! .................................................................................. 684
Tutorial #14 - Saving Notes
◦ Step #1: Adding a DatabaseHelper .................................................. 687
◦ Step #2: Examining DatabaseHelper ............................................... 688
◦ Step #3: Creating a NoteFragment .................................................. 689
◦ Step #4: Examining NoteFragment ................................................. 690
◦ Step #5: Creating the NoteActivity .................................................. 690
◦ Step #6: Examining NoteActivity ..................................................... 691
◦ Step #7: Add Notes to the Action Bar ............................................. 692
◦ Step #8: Defining a NoteLoadedEvent ............................................ 694
◦ Step #9: Loading a Note from the Database ................................... 695
◦ Step #10: Loading the Note Into the Fragment .............................. 696
◦ Step #11: Updating the Database ...................................................... 697
◦ Step #12: Saving the Note ................................................................. 698
◦ Step #13: Adding a Delete Action Bar Item ...................................... 700
◦ Step #14: Closing the NoteFragment When Deleted ....................... 703
◦ In Our Next Episode… ....................................................................... 708
Internet Access
◦ DIY HTTP .......................................................................................... 709
◦ What About HttpClient? ................................................................... 719
◦ HTTP via DownloadManager ........................................................... 722
ix
•
•
•
•
•
◦ Using Third-Party JARs ..................................................................... 722
◦ SSL ...................................................................................................... 723
◦ Using HTTP Client Libraries .................................................... 723
◦ Visit the Trails .................................................................................... 749
Intents, Intent Filters
◦ What’s Your Intent? ............................................................................ 751
◦ Stating Your Intent(ions) .................................................................. 753
◦ Responding to Implicit Intents ......................................................... 753
◦ Requesting Implicit Intents .............................................................. 756
◦ ShareActionProvider .............................................................. 760
◦ Practice Safe Content Resolution ..................................................... 763
Broadcasts and Broadcast Receivers
◦ The Stopped State .............................................................................. 767
◦ Example System Broadcasts ............................................................. 768
◦ The Order of Things .......................................................................... 777
◦ Keeping It Local ................................................................................. 778
◦ Visit the Trails! ................................................................................... 778
Tutorial #15 - Sharing Your Notes
◦ Step #1: Adding a ShareActionProvider ........................................... 779
◦ Step #2: Sharing the Note ................................................................. 780
◦ Step #3: Testing the Result ................................................................ 782
◦ In Our Next Episode… ....................................................................... 785
Services and the Command Pattern
◦ Why Services? .................................................................................... 787
◦ Setting Up a Service ........................................................................... 788
◦ Communicating To Services ............................................................ 790
◦ Scenario: The Music Player ............................................................... 792
◦ Communicating From Services ........................................................ 796
◦ Scenario: The Downloader ................................................................ 798
◦ Services and Configuration Changes ............................................... 804
Tutorial #16 - Updating the Book
◦ Step #1: Adding a Stub DownloadCheckService ............................. 807
◦ Step #2: Tying the Service Into the Action Bar ............................... 808
◦ Step #3: Defining Our Event ............................................................. 810
◦ Step #4: Defining Our JSON ............................................................. 810
◦ Step #5: Defining Our Retrofit Interface ........................................... 811
◦ Step #6: Retrieving Our JSON Via Retrofit ...................................... 812
◦ Step #7: Downloading the Update .................................................... 814
◦ Step #8: Unpacking the Update ........................................................ 815
◦ Step #9: Using the Update ................................................................ 819
◦ In Our Next Episode… ....................................................................... 824
x
• Large-Screen Strategies and Tactics
◦ Objective: Maximum Gain, Minimum Pain ..................................... 825
◦ The Fragment Strategy ...................................................................... 825
◦ Fragment Example: The List-and-Detail Pattern ............................ 834
◦ Other Master-Detail Strategies ........................................................ 848
◦ Showing More Pages .......................................................................... 861
◦ Fragment FAQs ................................................................................. 867
◦ Screen Size and Density Tactics ...................................................... 868
◦ Other Considerations ........................................................................ 871
• Tutorial #17 - Supporting Large Screens
◦ Step #1: Creating Our Layouts .......................................................... 875
◦ Step #2: Loading Our Sidebar Widgets ............................................ 879
◦ Step #3: Opening the Sidebar .......................................................... 880
◦ Step #4: Loading Content Into the Sidebar ..................................... 881
◦ Step #5: Removing Content From the Sidebar ............................... 884
• Backwards Compatibility Strategies and Tactics
◦ Think Forwards, Not Backwards ...................................................... 891
◦ Aim Where You Are Going ............................................................... 893
◦ A Target-Rich Environment .............................................................. 893
◦ Lint: It’s Not Just For Belly Buttons ................................................. 894
◦ A Little Help From Your Friends ..................................................... 895
◦ Avoid the New on the Old ............................................................... 895
◦ Testing ............................................................................................... 899
◦ Keeping Track of Changes ................................................................ 899
• System Services
◦ What is a System Service? ................................................................. 901
◦ What System Services Are There? ................................................... 902
• Google Play Services
◦ What Is Google Play Services? ......................................................... 905
◦ What Is In the Play Services SDK? .................................................. 906
◦ Adding Play Services to Your Project ............................................... 913
• Getting Help
◦ Questions. Sometimes, With Answers. ................................... 923
◦ Heading to the Source ....................................................................... 924
• Working with Library Modules
◦ Prerequisites ....................................................................................... 927
◦ Creating a Library Module ................................................................ 927
◦ Using a Library Module ..................................................................... 930
◦ Library Modules and the Manifest ................................................... 930
◦ Library Modules and Transitive Dependencies ....................... 931
◦ Limitations of Library Modules ........................................................ 932
xi
• Gradle and Tasks
◦ Key Build-Related Tasks .................................................................... 933
◦ Results ................................................................................................ 936
• Gradle Build Variants
◦ Prerequisites ....................................................................................... 937
◦ Objectives of the Project Structure .................................................. 937
◦ Terminology ....................................................................................... 938
◦ Configuring the Stock Build Types ................................................... 941
◦ Adding Build Types ........................................................................... 945
◦ Adding Product Flavors and Getting Build Variants ....................... 945
◦ Doing the Splits ................................................................................. 947
◦ Gradle and Android Studio ..................................................... 949
• Manifest Merger Rules
◦ Prerequisites ....................................................................................... 951
◦ Manifest Scenarios ............................................................................. 951
◦ Pieces of Manifest Generation .......................................................... 953
◦ Examining the Merger Results .......................................................... 955
◦ Viewing Merged Manifests in Android Studio ................................ 955
◦ Merging Elements and Attributes ................................................... 956
◦ Employing Placeholders ................................................................... 966
• Signing Your App
◦ Prerequisites ....................................................................................... 971
◦ Role of Code Signing ......................................................................... 971
◦ What Happens In Debug Mode ........................................................ 972
◦ Production Signing Keys ................................................................... 973
• Distribution
◦ Prerequisites ....................................................................................... 981
◦ Get Ready To Go To Market .............................................................. 981
• Writing a Gradle Plugin
◦ Prerequisites ...................................................................................... 987
◦ Customizing a Gradle Build ............................................................. 987
◦ Some Use Cases for a Custom Plugin .............................................. 988
◦ Writing a Plugin ............................................................................... 989
◦ Distributing the Plugin .................................................................... 996
◦ Using the Plugin ............................................................................... 998
◦ Creating a Real Plugin ..................................................................... 1002
• Code Generation
◦ Prerequisites ..................................................................................... 1007
◦ What Drives the Custom Code? ..................................................... 1007
◦ Java as Poetry ................................................................................... 1009
◦ Writing a Code Generation Plugin .................................................. 1010
xii
•
•
•
•
•
•
◦ Using the Generated Code ............................................................... 1021
Advanced Gradle for Android Tips
◦ Prerequisites ...................................................................................... 1023
◦ Gradle, DRY ....................................................................................... 1023
◦ Automating APK Version Information ........................................... 1026
◦ Adding to BuildConfig ..................................................................... 1028
Testing with JUnit4
◦ Prerequisites ...................................................................................... 1033
◦ Instrumentation Tests and Unit Tests ............................................. 1033
◦ Writing JUnit4 Test Cases ................................................................ 1035
◦ Configuring Gradle ........................................................................... 1041
◦ Running Your Instrumentation Tests ............................................. 1042
◦ Testing Android Library Projects .................................................... 1047
◦ Testing and Runtime Permissions .................................................. 1047
◦ The Android Test Orchestrator ............................................. 1048
Testing with Espresso
◦ Prerequisites ...................................................................................... 1053
◦ Adding a Shot of Espresso ............................................................... 1054
◦ Writing Tests in Espresso ................................................................ 1056
◦ The Espresso Test Recorder ............................................................ 1062
◦ Stronger Espresso ............................................................................ 1067
◦ Opting Out of Analytics ................................................................... 1081
◦ Waiting for the World to Change ................................................... 1082
Testing with UI Automator
◦ Prerequisites ..................................................................................... 1089
◦ What Is UI Automator? ................................................................... 1089
◦ Why Choose UI Automator Over Alternatives? ............................ 1090
◦ Gradle and Android Studio Settings .............................................. 1090
◦ Creating a Test Case ......................................................................... 1091
◦ Running Your Tests .......................................................................... 1099
◦ Finding Your Widgets ...................................................................... 1099
◦ Using the UI Automator Viewer ...................................................... 1100
Measuring Test Coverage
◦ Prerequisites ...................................................................................... 1103
◦ Who Tests the Testers? ..................................................................... 1103
◦ Some Types of Test Coverage ........................................................... 1104
◦ Coverage and Your Instrumentation Tests ...................................... 1106
Unit Testing
◦ Prerequisites ........................................................................................ 1111
◦ I Thought We Were Already Unit Testing? ...................................... 1112
◦ Scenario: Clean Architecture ............................................................ 1112
xiii
•
•
•
•
•
◦ Setting Up Unit Testing ..................................................................... 1113
◦ Writing POJO Unit Tests .................................................................. 1116
◦ Running Unit Tests ........................................................................... 1120
◦ Mocking Android .............................................................................. 1125
MonkeyRunner and the Test Monkey
◦ Prerequisites ...................................................................................... 1147
◦ MonkeyRunner ................................................................................. 1147
◦ Monkeying Around ........................................................................... 1149
Java 8 Lambda Expressions
◦ Prerequisites ...................................................................................... 1155
◦ The Basic Idea ................................................................................... 1156
◦ Using Lambda Expressions .............................................................. 1157
◦ Alternative: Method References ....................................................... 1161
Rx Basics
◦ Prerequisites ...................................................................................... 1163
◦ Life is But a Stream ........................................................................... 1163
◦ Action and Reaction ......................................................................... 1165
◦ A Rx For What Ails You .................................................................... 1166
◦ Rx and Lambdas ............................................................................... 1167
◦ A Simple Stream .................................................................... 1167
◦ Be Your Own Stream ........................................................................ 1169
◦ Removing the AsyncTask .................................................................. 1171
◦ Lambdas and Lifetimes .................................................................... 1177
◦ Streaming from a Resource .............................................................. 1178
◦ Error Handling .................................................................................. 1179
◦ Transmogrification ........................................................................... 1180
◦ Rx-Enabled Libraries ......................................................................... 1181
◦ Further Reading ................................................................................ 1183
◦ What About LiveData? ..................................................................... 1183
Notifications
◦ Prerequisites ...................................................................................... 1187
◦ What’s a Notification? ............................................................ 1187
◦ Notifications and Channels ................................................... 1190
◦ Showing a Simple Notification .............................................. 1190
◦ The Activity-Or-Notification Scenario ............................................ 1196
◦ Big (and Rich) Notifications ................................................... 1197
◦ Foreground Services .............................................................. 1204
◦ Disabled Notifications ........................................................... 1207
Advanced Notifications
◦ Prerequisites ....................................................................................... 1211
◦ Being a Good Citizen ......................................................................... 1211
xiv
◦ More About Channels ............................................................. 1212
◦ Wear? There! ..................................................................................... 1219
◦ Stacking Notifications ........................................................... 1224
◦ Avoiding Wear ........................................................................ 1230
◦ Other Wear-Specific Notification Options ............................. 1231
◦ Remote Input, On-Device ................................................................ 1245
◦ Notification Groups .......................................................................... 1250
◦ Lockscreen Notifications .................................................................. 1252
◦ Priority, Importance, and Heads-Up Notifications ............... 1261
◦ Full-Screen Notifications ....................................................... 1264
◦ Progress Notifications ..................................................................... 1266
◦ Custom Views ........................................................................ 1275
◦ Life After Delete ................................................................................ 1278
◦ The Mysterious Case of the Missing Number ........................ 1279
◦ Notifications and MessagingStyle ......................................... 1279
◦ Changes in API Level 23 .................................................................. 1284
◦ Sounds and Android 7.0 ................................................................... 1285
◦ Auto-Timeout ........................................................................ 1286
◦ Colorized Notifications ......................................................... 1287
• Multi-Window Support
◦ Prerequisites ...................................................................................... 1291
◦ A History of Windows ...................................................................... 1291
◦ What The User Sees ........................................................................ 1292
◦ What Your Code Sees ...................................................................... 1294
◦ Opting Out ....................................................................................... 1296
◦ Opting In .......................................................................................... 1296
◦ Configuring the Layout ................................................................... 1297
◦ Avoiding Stutter ............................................................................... 1299
◦ Managing the Background .............................................................. 1300
◦ How Low Can You Go? .................................................................... 1300
◦ Parallel Processing ............................................................................ 1301
◦ Split-Screen, HOME, and Your Activity .......................................... 1303
◦ Split-Screen and Orientations ........................................................ 1304
◦ Forcing Your App Into Multi-Window/Multi-Instance ................ 1304
◦ Supporting Legacy Proprietary Multi-Window .............................. 1312
◦ Freeform Multi-Window Mode ........................................................ 1315
◦ Picture-in-Picture .................................................................. 1322
◦ Multi-Display Support ........................................................... 1326
• Advanced ConstraintLayout
◦ Prerequisites ...................................................................................... 1335
◦ Disclosing Your Bias ......................................................................... 1335
xv
•
•
•
•
•
•
◦ Centering Yourself ............................................................................ 1341
◦ Keeping Things Proportional ........................................................... 1345
◦ Constraining the ConstraintLayout Size ........................................ 1346
◦ Chains, Without the Whips ............................................................. 1347
◦ What If We’re GONE? ....................................................................... 1351
GridLayout
◦ Prerequisites ...................................................................................... 1353
◦ Issues with the Classic Containers .................................................. 1353
◦ The New Contender: GridLayout .................................................... 1355
◦ GridLayout and the Android Support Package .............................. 1355
◦ Our Test App ..................................................................................... 1356
◦ Replacing the Classics ...................................................................... 1359
◦ Implicit Rows and Columns ............................................................. 1365
◦ Row and Column Spans .................................................................. 1366
Dialogs and DialogFragments
◦ Prerequisites ...................................................................................... 1373
◦ DatePickerDialog and TimePickerDialog ....................................... 1373
◦ AlertDialog ........................................................................................ 1379
◦ DialogFragments .............................................................................. 1380
◦ DialogFragment: The Other Flavor ................................................. 1385
◦ Dialogs: Modal, Not Blocking .......................................................... 1385
Advanced ListViews
◦ Prerequisites ...................................................................................... 1387
◦ Multiple Row Types, and Self Inflation ........................................... 1387
◦ Choice Modes and the Activated Style ........................................... 1394
◦ Custom Mutable Row Contents ............................................. 1395
◦ From Head To Toe ................................................................. 1400
◦ Enter RecyclerView .......................................................................... 1404
Action Modes
◦ Prerequisites ..................................................................................... 1406
◦ A Matter of Context ......................................................................... 1406
◦ Manual Action Modes ..................................................................... 1407
◦ Multiple-Choice-Modal Action Modes .................................... 1412
◦ Long-Click To Initiate an Action Mode .......................................... 1416
Other Advanced Action Bar Techniques
◦ Prerequisites ...................................................................................... 1423
◦ Action Layouts .................................................................................. 1423
◦ Action Views and Action Providers ................................................ 1424
◦ Searching with SearchView .............................................................. 1425
◦ Floating Action Bars ............................................................... 1431
Toolbar
xvi
•
•
•
•
◦ Prerequisites ...................................................................................... 1435
◦ Basic Toolbar Mechanics .................................................................. 1435
◦ Use Case #1: Split Action Bar ................................................. 1436
◦ Use Case #2: Contextual Actions .................................................... 1442
◦ Use Case #3: Replacement Action Bar ................................... 1452
AppCompat: The Official Action Bar Backport
◦ Prerequisites ...................................................................................... 1455
◦ Ummmm… Why? .............................................................................. 1455
◦ The Basics of Using AppCompat ............................................ 1458
◦ Other AppCompat Effects ...................................................... 1465
◦ Toolbar and AppCompat ......................................................... 1471
◦ To Material, or Not to Material ........................................................ 1475
The Android Design Support Library
◦ Prerequisites ..................................................................................... 1478
◦ GUIs and the Support Package ....................................................... 1478
◦ Adding the Library… and What Comes With It ............................ 1479
◦ Introducing CWAC-CrossPort ........................................................ 1479
◦ Snackbars: Sweeter than Toasts ...................................................... 1480
◦ Absolutely FABulous ....................................................................... 1488
◦ Material Tabs with TabLayout ........................................................ 1506
◦ Floating Labels ....................................................................... 1518
Implementing a Navigation Drawer
◦ Prerequisites ...................................................................................... 1529
◦ What is a Navigation Drawer? ......................................................... 1529
◦ A Simple Navigation Drawer ............................................................ 1531
◦ Alternative Row Layouts .................................................................. 1537
◦ Additional Considerations ............................................................... 1539
◦ What Should Not Be in the Drawer ............................................... 1548
◦ Independent Implementations ....................................................... 1549
RecyclerView
◦ Prerequisites ...................................................................................... 1552
◦ AdapterView and its Discontents .................................................... 1552
◦ Enter RecyclerView ........................................................................... 1552
◦ A Trivial List ............................................................................ 1553
◦ Divider Options ................................................................................ 1561
◦ Handling Click Events ..................................................................... 1569
◦ What About Cursors? ............................................................. 1576
◦ Grids ....................................................................................... 1583
◦ Varying the Items .............................................................................. 1587
◦ Mutable Row Contents ......................................................... 1600
◦ Changing the Contents ................................................................... 1628
xvii
•
•
•
•
•
◦ The Order of Things ........................................................................ 1634
◦ Other Bits of Goodness ................................................................... 1642
◦ Animating the Deltas Using DiffUtil .............................................. 1643
◦ The March of the Libraries .................................................... 1651
Advanced RecyclerView
◦ Prerequisites ..................................................................................... 1659
◦ RecyclerView as Pager ..................................................................... 1659
◦ Declaring a LayoutManager in the Layout .................................... 1682
◦ Transcript Mode ............................................................................... 1682
Advanced Uses of WebView
◦ Prerequisites ..................................................................................... 1687
◦ Friends with Benefits ....................................................................... 1687
◦ Navigating the Waters ...................................................................... 1702
◦ Settings, Preferences, and Options (Oh, My!) ................................ 1702
◦ Security and Your WebView ............................................................ 1703
◦ Android 8.0 WebView Changes .............................................. 1706
◦ Chrome Custom Tabs ............................................................. 1709
◦ Prerequisites ....................................................................................... 1711
◦ Keyboards, Hard and Soft ................................................................. 1711
◦ Tailored To Your Needs .................................................................... 1712
◦ Tell Android Where It Can Go ......................................................... 1717
◦ Fitting In ............................................................................................ 1719
◦ Jane, Stop This Crazy Thing! ............................................................ 1722
Fonts and Text
◦ Prerequisites ...................................................................................... 1723
◦ Love The One You’re With ............................................................... 1723
◦ Yeah, But Do We Really Have To Do This in Java? ......................... 1727
◦ Here a Glyph, There a Glyph ........................................................... 1728
◦ Auto-Sizing TextView ............................................................. 1729
◦ Justified Text .......................................................................... 1734
Rich Text
◦ Prerequisites ...................................................................................... 1735
◦ The Span Concept ............................................................................. 1735
◦ Loading Rich Text ............................................................................. 1737
◦ Editing Rich Text .............................................................................. 1740
◦ Saving Rich Text ................................................................................ 1745
◦ Manipulating Rich Text .................................................................... 1745
Animators
◦ Prerequisites ...................................................................................... 1747
◦ ViewPropertyAnimator .................................................................... 1747
◦ The Foundation: Value and Object Animators .............................. 1752
xviii
◦ Animating Custom Types ................................................................. 1755
◦ Hardware Acceleration ..................................................................... 1756
◦ The Three-Fragment Problem ......................................................... 1757
• Legacy Animations
◦ Prerequisites ..................................................................................... 1769
◦ It’s Not Just For Toons Anymore ..................................................... 1769
◦ A Quirky Translation ........................................................................ 1770
◦ Fading To Black. Or Some Other Color. .......................................... 1774
◦ When It’s All Said And Done .......................................................... 1776
◦ Loose Fill ........................................................................................... 1777
◦ Hit The Accelerator .......................................................................... 1778
◦ Animate. Set. Match. ........................................................................ 1778
◦ Active Animations ........................................................................... 1780
• Custom Drawables
◦ Prerequisites ...................................................................................... 1781
◦ Where Do These Things Go? ........................................................... 1782
◦ ColorDrawable .................................................................................. 1783
◦ AnimationDrawable ......................................................................... 1783
◦ StateListDrawable ............................................................................. 1787
◦ ColorStateList .................................................................................. 1788
◦ LayerDrawable ................................................................................. 1790
◦ TransitionDrawable .......................................................................... 1791
◦ LevelListDrawable ............................................................................ 1792
◦ ScaleDrawable and ClipDrawable ................................................... 1794
◦ InsetDrawable .................................................................................. 1803
◦ ShapeDrawable ................................................................................ 1804
◦ BitmapDrawable ............................................................................... 1815
◦ Composite Drawables ....................................................................... 1822
◦ A Stitch In Time Saves Nine ........................................................... 1826
• Mapping with Maps V2
◦ Prerequisites ...................................................................................... 1837
◦ A Brief History of Mapping on Android ........................................ 1838
◦ Where You Can Use Maps V2 .................................................. 1838
◦ Licensing Terms for Maps V2 .......................................................... 1839
◦ What You Need to Start ......................................................... 1839
◦ The Book Samples… And You! ................................................ 1842
◦ Setting Up a Basic Map .......................................................... 1842
◦ Playing with the Map ...................................................................... 1847
◦ Map Tiles .......................................................................................... 1850
◦ Placing Simple Markers ................................................................... 1850
◦ Seeing All the Markers .................................................................... 1854
xix
◦ Flattening and Rotating Markers .................................................... 1856
◦ Sprucing Up Your “Info Windows” ................................................. 1860
◦ Images and Your Info Window ....................................................... 1865
◦ Setting the Marker Icon .................................................................. 1872
◦ Responding to Taps .......................................................................... 1874
◦ Dragging Markers ............................................................................. 1875
◦ The “Final” Limitations ................................................................... 1878
◦ A Bit More About IPC ............................................................. 1881
◦ Finding the User ............................................................................... 1881
◦ Dealing with Runtime Permissions ................................................ 1886
◦ Drawing Lines and Areas ................................................................ 1889
◦ Gestures and Controls ..................................................................... 1892
◦ Tracking Camera Changes .............................................................. 1893
◦ Maps in Fragments and Pagers ....................................................... 1896
◦ Animating Marker Movement ........................................................ 1902
◦ Maps, of the Indoor Variety ............................................................ 1908
◦ Taking a Snapshot of a Map ............................................................ 1909
◦ MapFragment vs. MapView ............................................................. 1910
◦ About That AbstractMapActivity Class… ........................................ 1910
◦ Helper Libraries for Maps V2 ........................................................... 1914
◦ Problems with Maps V2 at Runtime ............................................... 1918
◦ Problems with Maps V2 Deployment ............................................. 1918
◦ What Non-Compliant Devices Show .............................................. 1918
◦ Mapping Alternatives ....................................................................... 1919
• Crafting Your Own Views
◦ Prerequisites ...................................................................................... 1921
◦ Pick Your Poison ............................................................................... 1921
◦ Colors, Mixed How You Like Them ........................................ 1922
◦ ReverseChronometer: Simply a Custom Subclass .......................... 1933
◦ AspectLockedFrameLayout: A Custom Container ........................ 1939
◦ Mirror and MirroringFrameLayout: Draw It Yourself ................... 1942
• Advanced Preferences
◦ Prerequisites ...................................................................................... 1955
◦ Introducing PreferenceActivity ....................................................... 1955
◦ Intents for Headers or Preferences ................................................. 1960
◦ Conditional Headers ........................................................................ 1961
◦ Dependent Preferences ................................................................... 1966
◦ Nested Screens ................................................................................. 1969
◦ Listening to Preference Changes .................................................... 1972
◦ Defaults, and Defaults ...................................................................... 1975
◦ Listening to Preference Value Changes .......................................... 1976
xx
•
•
•
•
•
•
◦ Dynamic ListPreference Contents .................................................. 1976
◦ Dealing with External Changes to Preferences ............................... 1981
◦ Preferences in Device Settings App ....................................... 1983
Custom Dialogs and Preferences
◦ Prerequisites ...................................................................................... 1991
◦ Your Dialog, Chocolate-Covered ..................................................... 1991
◦ Preferring Your Own Preferences, Preferably ................................ 1995
Progress Indicators
◦ Prerequisites ..................................................................................... 2003
◦ Progress Bars .................................................................................... 2003
◦ ProgressBar and Threads ................................................................ 2007
◦ Tailoring Progress Bars .................................................................... 2010
◦ Progress Dialogs .............................................................................. 2020
◦ Title Bar and Action Bar Progress Indicators ................................ 2022
◦ Direct Progress Indication .............................................................. 2024
More Fun with Pagers
◦ Prerequisites ..................................................................................... 2027
◦ Hosting ViewPager in a Fragment .................................................. 2027
◦ Pages and the Action Bar ................................................................ 2029
◦ ViewPagers and Scrollable Contents .............................................. 2032
◦ Columns for Large, Pages for Small ................................................ 2032
◦ Introducing ArrayPagerAdapter ..................................................... 2038
◦ Columns for Large Landscape, Pages for the Rest ........................ 2041
◦ Adding, Removing, and Moving Pages .......................................... 2046
◦ Inside ArrayPagerAdapter ............................................................... 2050
Focus Management and Accessibility
◦ Prerequisites ..................................................................................... 2065
◦ Prepping for Testing ....................................................................... 2066
◦ Controlling the Focus ..................................................................... 2066
◦ Accessibility and Focus ................................................................... 2076
◦ Accessibility Beyond Focus ............................................................. 2077
◦ Accessibility Beyond Impairment ................................................... 2087
Miscellaneous UI Tricks
◦ Prerequisites .................................................................................... 2089
◦ Full-Screen and Lights-Out Modes ............................................... 2089
◦ Offering a Delayed Timeout ........................................................... 2100
Event Bus Alternatives
◦ Prerequisites ...................................................................................... 2105
◦ A Brief Note About the Sample Apps .............................................. 2105
◦ Standard Intents as Event Bus ......................................................... 2105
◦ LocalBroadcastManager as Event Bus ............................................ 2106
xxi
•
•
•
•
◦ greenrobot’s EventBus 3.x ................................................................ 2117
◦ greenrobot’s EventBus 2.x ................................................................ 2123
◦ Hey, What About Otto? .................................................................. 2124
Tasks
◦ Prerequisites ...................................................................................... 2125
◦ First, Some Terminology .................................................................. 2125
◦ And Now, a Bit About Task Killers .................................................. 2131
◦ A Canary for the Task’s Coal Mine ......................................... 2138
◦ The Default User Experience ........................................................... 2141
◦ Explaining the Default Behavior ...................................................... 2145
◦ Basic Scenarios for Changing the Behavior ................................... 2148
◦ Dealing with the Persistent Tasks ................................................... 2163
◦ Documents As Tasks ....................................................................... 2165
◦ Other Task-Related Activity Properties ......................................... 2168
◦ Other Task-Related Activity Methods ............................................. 2177
The Assist API (“Now On Tap”)
◦ Prerequisites ..................................................................................... 2180
◦ What Data Gets Disclosed .............................................................. 2180
◦ Adding to the Data ........................................................................... 2182
◦ Removing from the Data .................................................................. 2185
◦ Blocking Assist as a User ................................................................. 2188
◦ Implementing Your Own Assistant ................................................. 2191
The Autofill API
◦ Prerequisites ..................................................................................... 2206
◦ The Pieces of the Puzzle .................................................................. 2206
◦ The User Experience ........................................................................ 2207
◦ What Data Gets Disclosed .............................................................. 2209
◦ Blocking Autofill as a User .............................................................. 2223
◦ Supporting Autofill with Standard Widgets .................................. 2225
◦ Supporting Autofill with Custom Widgets .................................... 2228
◦ Dealing with Dynamic Changes ..................................................... 2228
◦ Security Requirements of Autofill Services .................................... 2229
The Data Binding Framework
◦ Prerequisites ..................................................................................... 2235
◦ The What, Now? .............................................................................. 2236
◦ The Basic Steps ................................................................................ 2237
◦ The Extended Layout Resource ...................................................... 2243
◦ The Binding Expression Language ................................................. 2247
◦ Observables and Updating the Binding ......................................... 2250
◦ Two-Way Binding ............................................................................ 2263
◦ Other Features of Note .................................................................... 2266
xxii
• Drag and Drop
◦ Prerequisites ..................................................................................... 2295
◦ The Scope of Drag and Drop ........................................................... 2295
◦ The Pieces of Drag-and-Drop ......................................................... 2297
◦ Drag-and-Drop, within an Activity ................................................. 2301
◦ Drag-and-Drop, Between Apps .............................................. 2310
◦ Detecting Cross-App Drag Events .................................................. 2322
◦ Intra-App Cross-Window Drag-and-Drop ..................................... 2322
◦ Pondering Legacy Multi-Window .................................................. 2325
◦ Dragging and Dropping Simple Stuff ............................................. 2325
◦ Multi-Action Drag-and-Drop ......................................................... 2326
◦ Nested Drop Targets .............................................................. 2332
◦ Pondering Standards ........................................................................ 2341
◦ Pondering Accessibility .................................................................... 2341
• Keyboard and Mouse Input
◦ Prerequisites ..................................................................................... 2343
◦ Offering Keyboard Shortcuts ................................................ 2343
◦ Custom Copy-and-Paste .................................................................. 2353
◦ Physical Keyboards and Focusing ................................................... 2357
◦ Offering Mouse Context Menus ...................................................... 2361
◦ Offering Tooltips ................................................................... 2367
◦ Pointer Capture ..................................................................... 2375
• Viewing PDFs
◦ Prerequisites ..................................................................................... 2377
◦ The Criteria ...................................................................................... 2378
◦ The Classic Solution: ACTION_VIEW ........................................... 2380
◦ The Really Bad Idea: Google Docs .................................................. 2380
◦ The Built-In Option: PdfRenderer ................................................... 2381
◦ The Thunder Lizard Choice: PDF.js ............................................... 2390
◦ The Native Approach: Pdfium ........................................................ 2394
◦ What To Choose? ............................................................................. 2398
• Home Screen App Widgets
◦ Prerequisites ..................................................................................... 2401
◦ App Widgets and Security .............................................................. 2401
◦ The Big Picture for a Small App Widget ........................................ 2402
◦ Crafting App Widgets ...................................................................... 2403
◦ Another and Another ...................................................................... 2410
◦ App Widgets: Their Life and Times ................................................ 2411
◦ Controlling Your (App Widget’s) Destiny ....................................... 2411
◦ One Size May Not Fit All ................................................................. 2412
◦ Lockscreen Widgets ........................................................................ 2418
xxiii
•
•
•
•
•
•
•
◦ Preview Images ................................................................................ 2424
◦ Being a Good Host ........................................................................... 2426
Adapter-Based App Widgets
◦ Prerequisites ..................................................................................... 2427
◦ AdapterViews for App Widgets ...................................................... 2427
◦ Building Adapter-Based App Widgets ........................................... 2428
Content Provider Theory
◦ Prerequisites ..................................................................................... 2445
◦ Using a Content Provider ................................................................ 2445
◦ Building Content Providers ............................................................ 2453
◦ Issues with Content Providers ........................................................ 2461
Content Provider Implementation Patterns
◦ Prerequisites ..................................................................................... 2463
◦ The Single-Table Database-Backed Content Provider .................. 2463
◦ The Local-File Content Provider ............................................ 2471
◦ The Protected Provider .................................................................. 2480
◦ The Stream Provider ........................................................................ 2482
◦ FileProvider .......................................................................... 2486
◦ StreamProvider ................................................................................ 2491
The Loader Framework
◦ Prerequisites ...................................................................................... 2501
◦ Cursors: Issues with Management .................................................. 2502
◦ Introducing the Loader Framework ............................................... 2502
◦ Choosing an Implementation ......................................................... 2504
◦ Using CursorLoader ......................................................................... 2504
◦ What Else Is Missing? ..................................................................... 2507
◦ What Happens When…? ................................................................. 2507
◦ Writing a Custom Loader ................................................................ 2508
The ContactsContract and CallLog Providers
◦ Prerequisites ...................................................................................... 2517
◦ Introducing You to Your Contacts .................................................. 2518
◦ Pick a Peck of Pickled People ......................................................... 2519
◦ Spin Through Your Contacts ............................................................ 2521
◦ Makin’ Contacts ............................................................................... 2528
◦ Looking at the CallLog .................................................................... 2532
The CalendarContract Provider
◦ Prerequisites ..................................................................................... 2538
◦ You Can’t Be a Faker ........................................................................ 2538
◦ Do You Have Room on Your Calendar? ......................................... 2538
◦ Penciling In an Event ....................................................................... 2544
The MediaStore Provider
xxiv
•
•
•
•
◦ Prerequisites ..................................................................................... 2547
◦ What Is the MediaStore? ................................................................. 2548
◦ MediaStore and “Other” External Storage ..................................... 2549
◦ How Does My Content Get Indexed? ............................................. 2550
◦ How Do I Retrieve Video from the MediaStore? ........................... 2550
Consuming Documents
◦ Prerequisites ..................................................................................... 2559
◦ The Storage Access… What? ........................................................... 2559
◦ The Storage Access Framework Participants .................................. 2561
◦ Picking How to Pick (a Peck of Pickled Pepper Photos) ............... 2561
◦ Opening a Document ...................................................................... 2562
◦ Why We Want Things To Be Openable ......................................... 2566
◦ The Rest of the CRUD ..................................................................... 2567
◦ The DocumentFile Helper .............................................................. 2568
◦ CWAC-Document and DocumentFileCompat ....................... 2568
◦ Getting Durable Access ................................................................... 2569
◦ Another Durable Example: Diceware ............................................. 2579
◦ Extended Example: A Tiny Text Editor .......................................... 2593
◦ Document Trees ............................................................................... 2623
◦ Getting a Tree: Example .................................................................. 2625
◦ Scoped Directory Access Bug .......................................................... 2642
◦ Android 8.0 Changes .............................................................. 2643
Providing Documents
◦ Prerequisites ..................................................................................... 2645
◦ Have Your Content, and Provide it Too ......................................... 2645
◦ Key Provider Concepts .................................................................... 2647
◦ Pieces of a Provider ......................................................................... 2648
◦ Optional Provider Capabilities ....................................................... 2663
Encrypted Storage
◦ Prerequisites ..................................................................................... 2670
◦ Scenarios for Encryption ................................................................. 2670
◦ Obtaining SQLCipher ..................................................................... 2670
◦ Using SQLCipher ............................................................................. 2671
◦ SQLCipher Limitations ................................................................... 2672
◦ Passwords and Sessions ................................................................... 2673
◦ About Those Passphrases… ............................................................. 2674
◦ Encrypted Preferences ..................................................................... 2681
◦ IOCipher ........................................................................................... 2683
Packaging and Distributing Data
◦ Prerequisites ..................................................................................... 2685
◦ Packing a Database To Go ............................................................... 2685
xxv
• Advanced Database Techniques
◦ Prerequisites .................................................................................... 2689
◦ Full-Text Indexing .......................................................................... 2689
• Data Backup
◦ Prerequisites ..................................................................................... 2707
◦ First, Some Terminology ................................................................. 2708
◦ Differing Definitions of “Backup” ................................................... 2708
◦ Implementing IT-Style Backup ....................................................... 2710
◦ The Google Backup Bootstrap ........................................................ 2735
◦ Boosting Backup Security ............................................................... 2744
◦ Alternative Approaches ................................................................... 2745
• SSL
◦ Prerequisites ...................................................................................... 2751
◦ Basic SSL Operation ......................................................................... 2751
◦ Problems in Paradise ....................................................................... 2752
◦ Introducing Network Security Configuration ................................ 2755
◦ SSL Problems and Network Security Configuration ..................... 2758
◦ Other SSL Strengthening Techniques ............................................ 2768
◦ Advanced Uses of CWAC-NetSecurity ............................................ 2771
◦ NetCipher ......................................................................................... 2774
• NetCipher
◦ Prerequisites ..................................................................................... 2775
◦ Network Security’s Got Onions ...................................................... 2775
◦ The NetCipher HTTP Integration APIs .......................................... 2777
◦ The Rest of the Builder API ............................................................ 2784
• Embedding a Web Server
◦ Prerequisites ..................................................................................... 2797
◦ Why a Web Server? .......................................................................... 2797
◦ Introducing AsyncHttpServer ......................................................... 2799
◦ Embedding a Simple Server ............................................................ 2799
◦ Template-Driven Responses, with Handlebars ............................. 2816
◦ Supporting WebSockets ................................................................... 2821
◦ Securing the Web Server ................................................................. 2827
◦ Towards a Reusable Web Server Service ........................................ 2834
• Miscellaneous Network Topics
◦ Prerequisites ..................................................................................... 2845
◦ Downloading Files ........................................................................... 2845
◦ Data Saver ......................................................................................... 2859
• Audio Playback
◦ Prerequisites ..................................................................................... 2863
◦ Get Your Media On .......................................................................... 2863
xxvi
•
•
•
•
•
•
◦ MediaPlayer for Audio .......................................................... 2864
◦ Other Ways to Make Noise ............................................................ 2869
Audio Recording
◦ Prerequisites ..................................................................................... 2873
◦ Recording by Intent ......................................................................... 2873
◦ Recording to Files ............................................................................ 2876
◦ Recording to Streams ...................................................................... 2881
◦ Raw Audio Input ............................................................................. 2884
◦ Requesting the Microphone .......................................................... 2884
Video Playback
◦ Prerequisites ..................................................................................... 2885
◦ Moving Pictures ..................................................................... 2885
Using the Camera via 3rd-Party Apps
◦ Prerequisites ..................................................................................... 2891
◦ Being Specific About Features ........................................................ 2891
◦ Still Photos: Letting the Camera App Do It ................................... 2892
◦ Permissions and Third-Party Camera Apps .................................. 2899
◦ A Matter of Orientation ................................................................. 2900
◦ Scanning with ZXing ....................................................................... 2907
◦ Videos: Letting the Camera App Do It .......................................... 2908
◦ Using a Camera Library ......................................................... 2911
◦ Directly Working with the Camera ................................................ 2923
Working Directly with the Camera
◦ Prerequisites ..................................................................................... 2925
◦ Notes About the Code Snippets ..................................................... 2925
◦ A Tale of Two APIs ........................................................................... 2926
◦ Performing Basic Camera Operations ............................................ 2927
◦ Configuring the Still Camera .......................................................... 2950
◦ And Now, The Problems ................................................................. 2959
Media Routes
◦ Prerequisites ..................................................................................... 2965
◦ Terminology ..................................................................................... 2965
◦ A Tale of Two MediaRouters .......................................................... 2966
◦ Attaching to MediaRouter .............................................................. 2967
◦ User Route Selection with MediaRouteActionProvider ............... 2969
◦ Using Live Video Routes ................................................................ 2984
◦ Using Remote Playback Routes ..................................................... 2984
Supporting External Displays
◦ Prerequisites ..................................................................................... 3003
◦ A History of External Displays ........................................................ 3003
◦ What is a Presentation? .................................................................. 3004
xxvii
•
•
•
•
•
◦ Playing with External Displays ............................................ 3005
◦ Detecting Displays ............................................................................ 3011
◦ A Simple Presentation ...................................................................... 3012
◦ A Simpler Presentation ................................................................... 3018
◦ Presentations and Configuration Changes .................................... 3024
◦ Presentations as Fragments ............................................................ 3025
◦ Another Sample Project: Slides ...................................................... 3036
◦ Device Support for Presentation .................................................... 3044
◦ Presentations from a Service .......................................................... 3045
◦ Hey, What About Chromecast? ...................................................... 3048
Google Cast and Chromecast
◦ Prerequisites ...................................................................................... 3051
◦ Here a Cast, There a Cast ................................................................. 3051
◦ Common Chromecast Development Notes ................................... 3053
◦ Your API Choices ............................................................................. 3053
◦ Senders and Receivers ..................................................................... 3054
◦ Supported Media Types ................................................................... 3055
◦ Cast SDK Dependencies .................................................................. 3056
◦ Developing Google Cast Apps ........................................................ 3058
The “Ten-Foot UI”
◦ Prerequisites ..................................................................................... 3059
◦ What is the “Ten-Foot UI”? ............................................................ 3060
◦ Overscan .......................................................................................... 3060
◦ Navigation ........................................................................................ 3061
◦ Stylistic Considerations ................................................................... 3062
◦ The Leanback UI .............................................................................. 3064
◦ Testing Your Theories ...................................................................... 3079
Putting the TVs All Together: Decktastic
◦ Prerequisites ..................................................................................... 3082
◦ Introducing Decktastic .................................................................... 3082
◦ Implementing Decktastic ............................................................... 3086
Creating a MediaRouteProvider
◦ Prerequisites ...................................................................................... 3121
◦ Terminology ...................................................................................... 3121
◦ DIY Chromecast ................................................................................ 3122
◦ Creating the MediaRouteProvider ................................................... 3124
◦ Consuming the MediaRouteProvider .............................................. 3135
◦ Implementing This “For Realz” ....................................................... 3139
The Media Projection APIs
◦ Prerequisites ...................................................................................... 3141
◦ Requesting Screenshots ................................................................... 3141
xxviii
•
•
•
•
•
◦ Recording the Screen ........................................................................ 3156
◦ Yet Another Sample: andshooter ..................................................... 3176
Advanced Permissions
◦ Prerequisites ...................................................................................... 3183
◦ Securing Yourself .............................................................................. 3183
◦ Signature Permissions ..................................................................... 3186
◦ The Custom Permission Vulnerability ........................................... 3188
◦ Custom Dangerous Permissions, and Android 6.0 ....................... 3198
◦ Finding the Available Permissions ................................................. 3202
Restricted Profiles and UserManager
◦ Prerequisites ...................................................................................... 3215
◦ Android Tablets and Multiple User Accounts ................................ 3215
◦ Determining What the User Can Do .............................................. 3221
◦ Impacts of Device-Level Restrictions ............................................. 3224
◦ Enabling Custom Restrictions ........................................................ 3224
◦ Implicit Intents May Go “Boom” .................................................... 3235
Miscellaneous Security Techniques
◦ Prerequisites ..................................................................................... 3237
◦ Public Key Validation ...................................................................... 3237
◦ Choosing Your Signing Keysize ...................................................... 3249
◦ Avoiding Accidental APIs ................................................................ 3250
◦ Other Ways to Expose Data ............................................................ 3255
◦ Jacking Attacks ................................................................................ 3256
◦ Using FLAG_SECURE ...................................................................... 3264
AlarmManager and the Scheduled Service Pattern
◦ Scenarios .......................................................................................... 3267
◦ Options ............................................................................................. 3268
◦ A Simple Example ............................................................................ 3270
◦ The Five set…() Varieties ................................................................. 3272
◦ The Four Types of Alarms ............................................................... 3274
◦ When to Schedule Alarms .............................................................. 3274
◦ Archetype: Scheduled Service Polling ............................................ 3276
◦ Staying Awake at Work ................................................................... 3280
◦ Warning: Not All Android Devices Play Nice ................................ 3285
◦ Debugging Alarms ........................................................................... 3285
◦ WakefulBroadcastReceiver .............................................................. 3288
◦ Android 6.0 and the War on Background Processing ................... 3292
◦ Android 7.0 and OnAlarmListener ................................................. 3292
PowerManager and WakeLocks
◦ Prerequisites ..................................................................................... 3295
◦ Keeping the Screen On, UI-Style .................................................... 3295
xxix
•
•
•
•
•
◦ The Role of the WakeLock .............................................................. 3296
◦ What WakefulIntentService Does .................................................. 3297
JobScheduler
◦ Prerequisites ..................................................................................... 3299
◦ The Limitations of AlarmManager ................................................. 3299
◦ Enter the JobScheduler ................................................................... 3300
◦ Employing JobScheduler ................................................................. 3300
◦ Pondering Backoff Criteria ............................................................... 3315
◦ Other JobScheduler Features ........................................................... 3316
◦ JobScheduler Period Limits .............................................................. 3317
◦ GcmNetworkManager ...................................................................... 3317
◦ Periodic Work, Across Device Versions ................................. 3318
◦ Android 6.0 and “the War on Background Processing” ................ 3322
◦ Scheduling Content Monitoring ............................................ 3337
Accessing Location-Based Services
◦ Prerequisites ...................................................................................... 3351
◦ Location Providers: They Know Where You’re Hiding ................. 3352
◦ Finding Yourself ............................................................................... 3352
◦ On the Move .................................................................................... 3354
◦ Getting Locations via PendingIntent ............................................. 3362
◦ Are We There Yet? Are We There Yet? Are We There Yet? ........... 3362
◦ Testing… Testing… ............................................................................ 3363
◦ Alternative Flavors of Updates ........................................................ 3364
◦ The Fused Option ............................................................................ 3365
◦ Locations and Features ................................................................... 3365
The Fused Location Provider
◦ Prerequisites ..................................................................................... 3367
◦ Why Use the Fused Location Provider? ......................................... 3367
◦ Why Not Use the Fused Location Provider? ................................. 3368
◦ Finding Our Location, Once ........................................................... 3368
◦ Requesting Location Updates ......................................................... 3373
◦ I Can Haz Location? ........................................................................ 3375
Working with the Clipboard
◦ Prerequisites ..................................................................................... 3385
◦ Working with the Clipboard ........................................................... 3385
◦ ClipData and Drag-and-Drop ......................................................... 3390
◦ Monitoring the Clipboard ................................................................ 3391
◦ The Android 4.3 Clipboard Bug ...................................................... 3392
Telephony
◦ Prerequisites ..................................................................................... 3395
◦ Report To The Manager ................................................................... 3396
xxx
•
•
•
•
•
◦ You Make the Call! ................................................................. 3396
◦ No, Really, You Make the Call! ........................................................ 3399
Working With SMS
◦ Prerequisites ..................................................................................... 3401
◦ Sending Out an SOS, Give or Take a Letter ................................... 3402
◦ Monitoring and Receiving SMS ...................................................... 3410
◦ The SMS Inbox ................................................................................. 3416
◦ Asking to Change the Default .......................................................... 3417
◦ SMS and the Emulator .................................................................... 3418
◦ SMS Tokens ............................................................................ 3419
NFC
◦ Prerequisites ..................................................................................... 3425
◦ What Is NFC? ................................................................................... 3425
◦ To NDEF, Or Not to NDEF .............................................................. 3427
◦ NDEF Modalities ............................................................................. 3427
◦ NDEF Structure and Android’s Translation ................................... 3428
◦ The Reality of NDEF ........................................................................ 3429
◦ Sources of Tags .................................................................................. 3431
◦ Writing to a Tag ................................................................................ 3431
◦ Responding to a Tag ........................................................................ 3440
◦ Expected Pattern: Bootstrap ........................................................... 3441
◦ Mobile Devices are Mobile .............................................................. 3442
◦ Enabled and Disabled ..................................................................... 3442
◦ Android Beam .................................................................................. 3442
◦ Beaming Files ................................................................................... 3450
◦ Another Sample: SecretAgentMan .................................................. 3451
◦ Additional Resources ....................................................................... 3461
Device Administration
◦ Prerequisites ..................................................................................... 3463
◦ Objectives and Scope ....................................................................... 3463
◦ Defining and Registering an Admin Component .......................... 3464
◦ Going Into Lockdown ...................................................................... 3470
◦ Passwords and Device Administration ........................................... 3477
◦ Getting Along with Others ............................................................. 3482
Basic Use of Sensors
◦ Prerequisites ..................................................................................... 3483
◦ The Sensor Abstraction Model ....................................................... 3483
◦ Considering Rates ............................................................................ 3484
◦ Reading Sensors ............................................................................... 3485
◦ Batching Sensor Readings ............................................................... 3496
Printing and Document Generation
xxxi
•
•
•
•
◦ Prerequisites ..................................................................................... 3498
◦ The Android Print System ............................................................... 3498
◦ About the Sample App .................................................................... 3499
◦ Printing a Bitmap ............................................................................ 3500
◦ Printing an HTML Document ........................................................ 3502
◦ Printing a PDF File .......................................................................... 3507
◦ Printing Using a Canvas ................................................................... 3515
◦ Print Jobs ........................................................................................... 3518
◦ Printing, Threads, and Services ....................................................... 3518
◦ Printing Prior to Android 4.4 ........................................................... 3521
◦ HTML Generation ............................................................................ 3521
◦ PDF Generation Options ................................................................. 3525
Basic Bluetooth RFCOMM
◦ Prerequisites .......................................................................... 3527
◦ A Quick Bit of Scope .............................................................. 3528
◦ About the Sample App ........................................................... 3528
◦ Bluetooth and Permissions ................................................... 3534
◦ The Rx for Your Bluetooth ..................................................... 3535
◦ I Can Haz Bluetooth? ............................................................. 3536
◦ I Feel a Bond Between Us ....................................................... 3539
◦ A Voyage of Discovery ............................................................ 3542
◦ Serving and Shouting ............................................................ 3545
◦ Reach Out and Touch Someone ............................................. 3551
◦ Ping and Pong ........................................................................ 3554
◦ Differences with Android Things ........................................... 3558
Dealing with Different Hardware
◦ Prerequisites ...................................................................................... 3561
◦ Filtering Out Devices ....................................................................... 3561
◦ Runtime Capability Detection ........................................................ 3564
◦ Dealing with Device Bugs ............................................................... 3565
Writing and Using Parcelables
◦ Prerequisites ..................................................................................... 3569
◦ The Role of Parcelable ..................................................................... 3569
◦ Writing a Parcelable ........................................................................ 3570
◦ The Limitations of Parcelable ......................................................... 3576
◦ Beware the PendingIntent .............................................................. 3580
Responding to URLs
◦ Prerequisites ..................................................................................... 3587
◦ Manifest Modifications ................................................................... 3587
◦ Creating a Custom URL ................................................................... 3589
◦ Reacting to the Link ........................................................................ 3590
xxxii
•
•
•
•
•
•
◦ App Links ......................................................................................... 3592
App Shortcuts
◦ Prerequisites ..................................................................................... 3603
◦ Enabling Deep Dives ....................................................................... 3604
◦ App Shortcuts, from the User’s POV .............................................. 3604
◦ Offering Manifest App Shortcuts .................................................. 3606
◦ Offering Dynamic App Shortcuts .................................................... 3612
◦ Privacy, Security, and App Shortcuts .............................................. 3624
Plugin Patterns
◦ Prerequisites ..................................................................................... 3625
◦ Definitions, Scenarios, and Scope .................................................. 3625
◦ The Keys to Any Plugin System ...................................................... 3626
◦ Case Study: DashClock .................................................................... 3634
◦ Other Plugin Examples .......................................................... 3637
PackageManager Tricks
◦ Prerequisites ..................................................................................... 3657
◦ Asking Around ................................................................................. 3657
◦ Preferred Activities .......................................................................... 3661
◦ Middle Management ....................................................................... 3667
Remote Services and the Binding Pattern
◦ Prerequisites ..................................................................................... 3671
◦ The Binding Pattern ........................................................................ 3672
◦ When IPC Attacks! .......................................................................... 3678
◦ Service From Afar ............................................................................ 3681
◦ Tightening Up the Security .................................................... 3687
◦ Servicing the Service ....................................................................... 3691
◦ Thinking About Security ................................................................ 3696
◦ The “Everlasting Service” Anti-Pattern ......................................... 3696
Advanced Manifest Tips
◦ Prerequisites .................................................................................... 3699
◦ Just Looking For Some Elbow Room ............................................. 3699
◦ Using an Alias .................................................................................. 3709
◦ Getting Meta (Data) ......................................................................... 3710
Miscellaneous Integration Tips
◦ Prerequisites ...................................................................................... 3715
◦ Direct Share ...................................................................................... 3715
◦ Take the Shortcut ............................................................................. 3724
◦ Homing Beacons for Intents ............................................................ 3731
◦ Integrating with Text Selection ............................................. 3731
◦ Quick Settings and TileService ....................................................... 3742
◦ Installing Packages ................................................................ 3751
xxxiii
•
•
•
•
•
•
•
◦ Deleting Packages ................................................................. 3754
◦ Detecting Changes in Packages ............................................ 3754
Replacing App Code Dynamically
◦ Prerequisites ..................................................................................... 3757
◦ Typical Objectives ............................................................................ 3758
◦ The Challenges ................................................................................. 3760
◦ The Scripting Solution .................................................................... 3762
◦ The Hybrid Solution ........................................................................ 3763
◦ The Patch Solution .......................................................................... 3764
◦ A DIY Solution ................................................................................. 3765
◦ Is Any Of This a Good Idea? ........................................................... 3788
Android Studio Editors and Dialogs
◦ Prerequisites ..................................................................................... 3789
◦ Project Structure .............................................................................. 3789
◦ Translations Editor ......................................................................... 3800
Advanced Emulator Capabilities
◦ Prerequisites ..................................................................................... 3807
◦ Other Notable Configuration Options ........................................... 3807
◦ The Emulator Sidebar ...................................................................... 3813
◦ Emulator Window Operations ....................................................... 3824
◦ Headless Operation ......................................................................... 3824
Lint and the Support Annotations
◦ Prerequisites ..................................................................................... 3827
◦ What It Is .......................................................................................... 3828
◦ When It Runs ................................................................................... 3828
◦ What to Fix ....................................................................................... 3829
◦ What to Configure ........................................................................... 3830
◦ Support Annotations ....................................................................... 3834
Inspecting Layouts
◦ Prerequisites ..................................................................................... 3847
◦ The Layout Inspector ...................................................................... 3847
◦ Hierarchy View ................................................................................ 3849
Screenshots and Screencasts
◦ Prerequisites ..................................................................................... 3855
◦ Collecting from Android Studio ..................................................... 3855
◦ Screencasts ....................................................................................... 3859
◦ Collecting from the Command Line .............................................. 3859
◦ Collecting from Another App ......................................................... 3861
◦ Tips and Tricks ................................................................................. 3862
ADB Tips and Tricks
◦ Prerequisites ..................................................................................... 3863
xxxiv
•
•
•
•
•
•
◦ This is the Droid That You Are Looking For .................................. 3863
◦ Installing and Uninstalling Apps .................................................... 3864
◦ Playing with Permissions ................................................................ 3864
◦ Starting and Stopping Components ............................................... 3865
◦ Killing Processes and Clearing Data .............................................. 3866
◦ Changing Display Metrics .............................................................. 3866
Stetho
◦ Wait, Wut? Chrome? ...................................................................... 3869
◦ Basic Stetho Integration ....................................................... 3869
◦ Connecting Chrome to Your App ................................................... 3876
◦ What You Get In Chrome Dev Tools .............................................. 3877
◦ Getting Help with Stetho ................................................................ 3885
Issues with Speed
◦ Prerequisites .................................................................................... 3889
◦ Getting Things Done ...................................................................... 3889
◦ Your UI Seems… Janky .................................................................... 3890
◦ Not Far Enough in the Background ............................................... 3890
◦ Playing with Speed .......................................................................... 3891
Finding CPU Bottlenecks
◦ Prerequisites ..................................................................................... 3893
◦ Android Studio’s Profiler ................................................................ 3894
◦ Method Tracing ............................................................................... 3896
◦ Other General CPU Measurement Techniques ............................. 3901
◦ UI “Jank” Measurement ................................................................... 3902
Focus On: NDK
◦ Prerequisites ..................................................................................... 3919
◦ The Role of the NDK ....................................................................... 3920
◦ Introducing CWAC-AndDown ....................................................... 3923
◦ Installing the NDK ........................................................................... 3923
◦ The Contents of an NDK Project .................................................... 3924
◦ Building Your Library ...................................................................... 3927
◦ libhoudini and the NDK .................................................................. 3933
Improving CPU Performance in Java
◦ Prerequisites ..................................................................................... 3935
◦ Reduce CPU Utilization .................................................................. 3935
◦ Reduce Time on the Main Application Thread ............................ 3940
◦ Improve Throughput and Responsiveness .................................... 3948
Finding and Eliminating Jank
◦ Prerequisites ...................................................................................... 3951
◦ The Case: ThreePaneDemoBC ......................................................... 3951
◦ Are We Janky? .................................................................................. 3952
xxxv
•
•
•
•
•
•
◦ Finding the Source of the Jank ....................................................... 3952
◦ Where Things Went Wrong ............................................................ 3963
◦ Removing the Jank ........................................................................... 3963
◦ Frame Metrics API .......................................................................... 3964
Issues with Bandwidth
◦ Prerequisites ..................................................................................... 3971
◦ You’re Using Too Much of the Slow Stuff ....................................... 3972
◦ You’re Using Too Much of the Expensive Stuff .............................. 3972
◦ You’re Using Too Much of Somebody Else’s Stuff .......................... 3973
◦ You’re Using Too Much… And There Is None ................................ 3974
Focus On: TrafficStats
◦ Prerequisites ..................................................................................... 3975
◦ TrafficStats Basics ............................................................................ 3975
◦ Example: TrafficMonitor ................................................................. 3977
◦ Other Ways to Employ TrafficStats ............................................... 3986
Measuring Bandwidth Consumption
◦ Prerequisites .................................................................................... 3989
◦ On-Device Measurement ............................................................... 3989
◦ Off-Device Measurement ................................................................ 3993
◦ Android Studio Profiler ................................................................... 3995
Being Smarter About Bandwidth
◦ Prerequisites ..................................................................................... 3997
◦ Bandwidth Savings .......................................................................... 3997
◦ Bandwidth Shaping ......................................................................... 4001
◦ Avoiding Metered Connections ..................................................... 4005
◦ Data Saver ........................................................................................ 4005
Issues with Application Heap
◦ Prerequisites .................................................................................... 4007
◦ You Are in a Heap of Trouble ......................................................... 4008
◦ Determining Your Heap Size At Runtime ..................................... 4009
◦ Fragments of Memory .................................................................... 4009
◦ Getting a Trim .................................................................................. 4010
◦ Warning: Contains Graphic Images ................................................ 4011
◦ Releasing SQLite Memory ............................................................... 4023
◦ Cheating ........................................................................................... 4023
◦ The 1MB IPC Transaction Limit ..................................................... 4024
Finding Memory Leaks
◦ Prerequisites ..................................................................................... 4027
◦ Android Studio Profiler .................................................................. 4028
◦ Getting Heap Dumps ....................................................................... 4031
◦ Analyzing Heap Dumps in Android Studio ................................... 4032
xxxvi
•
•
•
•
•
•
◦ Common Leak Scenarios ................................................................. 4038
◦ A Canary in a Leaky Coal Mine ...................................................... 4045
Issues with System RAM
◦ Prerequisites ..................................................................................... 4055
◦ Can’t We All Just Get Along? .......................................................... 4055
◦ Contributors to System RAM Consumption ................................. 4056
◦ Measuring System RAM Consumption: Tools ............................... 4057
◦ Measuring System RAM Consumption: Runtime ......................... 4073
◦ Learn To Let Go (Of Your Heap) .................................................... 4074
Issues with Battery Life
◦ Prerequisites ..................................................................................... 4077
◦ You’re Getting Blamed .................................................................... 4078
◦ Not All Batteries Are Created Equal .............................................. 4079
◦ Stretching Out the Last mWh ....................................................... 4079
Power Measurement Options
◦ Prerequisites ..................................................................................... 4081
◦ batterystats and the Battery Historian .......................................... 4082
◦ PowerTutor ....................................................................................... 4093
◦ Battery Screen in Settings Application ......................................... 4097
◦ BatteryInfo Dump ........................................................................... 4099
Sources of Power Drain
◦ Prerequisites ..................................................................................... 4103
◦ Screen ............................................................................................... 4104
◦ Disk I/O ............................................................................................ 4105
◦ WiFi and Mobile Data ..................................................................... 4106
◦ GPS ................................................................................................... 4109
◦ Camera .............................................................................................. 4110
◦ Additional Sources ............................................................................ 4110
Addressing Application Size Issues
◦ Prerequisites ...................................................................................... 4113
◦ The APK Analyzer ............................................................................. 4113
◦ Java Code, and the 64K Method Limit ............................................ 4116
◦ Native Code ....................................................................................... 4121
◦ Images ............................................................................................... 4122
◦ APK Expansion Files ........................................................................ 4124
Crash Reporting Using ACRA
◦ Prerequisites ...................................................................................... 4125
◦ What Happens When Things Go “Boom”? ..................................... 4125
◦ Introducing ACRA ........................................................................... 4126
◦ Where ACRA Reports Crashes ......................................................... 4127
◦ ACRA Integration Basics ................................................................. 4129
xxxvii
•
•
•
•
•
•
◦ What the User Sees ......................................................................... 4134
◦ What You See .................................................................................... 4141
◦ Customizing Where Reports Go ..................................................... 4148
◦ Adding Additional Data .................................................................. 4149
◦ Removing Data ................................................................................. 4152
◦ End-User Configuration ................................................................... 4153
◦ ACRA and Processes ......................................................................... 4153
JVM Scripting Languages
◦ Prerequisites ...................................................................................... 4155
◦ Languages on Languages ................................................................. 4155
◦ A Brief History of JVM Scripting .................................................... 4156
◦ Limitations ........................................................................................ 4157
◦ SL4A and JVM Languages ............................................................... 4158
◦ Embedding JVM Languages ............................................................ 4158
◦ Other JVM Scripting Languages ...................................................... 4172
In-App Diagnostics
◦ Prerequisites ...................................................................................... 4177
◦ The Diagnostic Activity ................................................................... 4178
◦ The Diagnostic Web App ................................................................ 4189
◦ The Diagnostic Overlay ................................................................... 4197
Anti-Patterns
◦ Prerequisites ...................................................................................... 4213
◦ Leak Threads… Or Things Attached to Threads ............................ 4213
◦ Use Large Heap Unnecessarily ......................................................... 4215
◦ Misuse the MENU Button ................................................................ 4217
◦ Interfere with Navigation ................................................................ 4218
◦ Use android:sharedUserId .............................................................. 4220
◦ Implement a “Quit” Button ............................................................. 4221
◦ Terminate Your Process ................................................................... 4223
◦ Try to Hide from the User ............................................................... 4224
◦ Use Multiple Processes .................................................................... 4225
◦ Hog System Resources ..................................................................... 4227
Widget Catalog: AdapterViewFlipper
◦ Key Usage Tips .................................................................................. 4231
◦ A Sample Usage ............................................................................... 4232
◦ Visual Representation ..................................................................... 4232
Widget Catalog: CalendarView
◦ Key Usage Tips ................................................................................. 4233
◦ A Sample Usage ............................................................................... 4234
◦ Visual Representation ..................................................................... 4235
Widget Catalog: DatePicker
xxxviii
•
•
•
•
•
•
•
•
◦ Key Usage Tips ................................................................................. 4239
◦ A Sample Usage .............................................................................. 4240
◦ Visual Representation ..................................................................... 4242
Widget Catalog: ExpandableListView
◦ Key Usage Tips ................................................................................. 4247
◦ A Sample Usage .............................................................................. 4248
◦ Visual Representation ..................................................................... 4254
Widget Catalog: SeekBar
◦ Key Usage Tips ................................................................................. 4257
◦ A Sample Usage ............................................................................... 4257
◦ Visual Representation .................................................................... 4260
Widget Catalog: SlidingDrawer
◦ Key Usage Tips ................................................................................. 4263
◦ A Sample Usage .............................................................................. 4264
◦ Visual Representation ..................................................................... 4265
Widget Catalog: StackView
◦ Key Usage Tips ................................................................................ 4269
◦ A Sample Usage ...................................................................... 4270
◦ Visual Representation ..................................................................... 4271
Widget Catalog: TabHost and TabWidget
◦ Deprecation Notes ........................................................................... 4273
◦ Key Usage Tips ................................................................................. 4273
◦ A Sample Usage ...................................................................... 4274
◦ Visual Representation ..................................................................... 4276
Widget Catalog: TimePicker
◦ Key Usage Tips ................................................................................. 4279
◦ A Sample Usage ............................................................................... 4279
◦ Visual Representation ..................................................................... 4281
Widget Catalog: ViewFlipper
◦ Key Usage Tips ................................................................................. 4285
◦ A Sample Usage ..................................................................... 4286
◦ Visual Representation ..................................................................... 4287
Device Catalog: Chrome and Chrome OS
◦ Prerequisites ..................................................................................... 4291
◦ How This Works .............................................................................. 4292
◦ Testing Your App on Chrome OS ................................................... 4293
◦ Be Prepared To Be Wiped Out ........................................................ 4303
◦ Enabling Your App for Chrome OS ................................................ 4304
◦ Your App on Chrome OS ................................................................. 4304
◦ Distribution Options ........................................................................ 4313
◦ Apps Sans Role .................................................................................. 4313
xxxix
•
•
•
•
•
•
◦ Getting Help ..................................................................................... 4314
Android Things Basics
◦ Prerequisites ...................................................................................... 4315
◦ Um, What’s a Thing? .............................................................. 4316
◦ Headless, But No Horseman .................................................. 4317
◦ Setting Up a Raspberry-Flavored Thing ................................ 4317
◦ An App For Your Thing ........................................................... 4328
◦ Control Interfaces .................................................................. 4332
◦ What’s Different? ................................................................... 4335
◦ Environment Details ............................................................. 4338
◦ Considerations ...................................................................... 4340
Device Catalog: BlackBerry
◦ I Thought BlackBerry Had Their Own OS? ................................... 4344
◦ What Else Is Different? ................................................................... 4344
◦ What Are We Making? .................................................................... 4347
◦ Getting Your Development Environment Established .................. 4347
◦ How Does Distribution Work? ....................................................... 4350
Device Catalog: Android TV
◦ Prerequisites ..................................................................................... 4353
◦ Hey, Wait a Minute… I Thought the Name Was “Google TV”? .... 4353
◦ Some Android TV Hardware .......................................................... 4354
◦ What Features and Configurations Does It Use? .......................... 4356
◦ What Is Really Different? ................................................................ 4357
◦ Getting Your Development Environment Established .................. 4359
◦ How Does Distribution Work? ....................................................... 4361
Device Catalog: Amazon Fire TV and Fire TV Stick
◦ Prerequisites ..................................................................................... 4365
◦ Introducing the Fire TV Devices .................................................... 4365
◦ What Features and Configurations Do They Use? ......................... 4371
◦ What Is Really Different? ................................................................ 4372
◦ Casting and Fire TV ......................................................................... 4373
◦ Getting Your Development Environment Established .................. 4374
◦ Working with the Remote and Controller ..................................... 4375
◦ How Does Distribution Work? ....................................................... 4377
◦ Getting Help ..................................................................................... 4377
Device Catalog: Samsung DeX
◦ DeX Screen Modes ........................................................................... 4381
◦ Other App Impacts .......................................................................... 4383
◦ For More Information ..................................................................... 4388
Appendix A: CWAC Libraries
◦ cwac-adapter .................................................................................... 4391
xl
◦ cwac-colormixer ............................................................................... 4391
◦ cwac-crossport ................................................................................. 4392
◦ cwac-document ............................................................................... 4392
◦ cwac-layouts ..................................................................................... 4392
◦ cwac-merge ...................................................................................... 4392
◦ cwac-netsecurity .............................................................................. 4393
◦ cwac-pager ....................................................................................... 4393
◦ cwac-presentation ........................................................................... 4393
◦ cwac-provider .................................................................................. 4393
◦ cwac-richedit ................................................................................... 4394
◦ cwac-sacklist .................................................................................... 4394
◦ cwac-saferoom ................................................................................. 4394
◦ cwac-security ................................................................................... 4394
◦ cwac-strictmodeex ........................................................................... 4394
◦ cwac-wakeful .................................................................................... 4395
• Appendix B: Android 8.0
◦ The War on Background Processing, Continued .......................... 4397
◦ JobScheduler Enhancements ................................................ 4406
◦ Auto-Fill ............................................................................................ 4411
◦ Notification Channels ........................................................... 4411
◦ Other Changes with Notifications ........................................ 4412
◦ Multi-Window Changes ......................................................... 4412
◦ WebView Changes .................................................................. 4412
◦ ContentProvider Changes ............................................................... 4413
◦ Storage Access Framework Changes ..................................... 4413
◦ Package Management ........................................................... 4413
◦ Fonts as Resources ........................................................................... 4413
◦ Other Major Changes in Android 8.0 .................................... 4414
◦ Other Minor Changes in Android 8.0 .................................... 4422
• Appendix C: Community Theater and the Appinars
◦ Viewing the Appinar Roster ............................................................ 4427
◦ Managing Appinars ......................................................................... 4430
◦ Viewing an Appinar ......................................................................... 4433
xli
Preface
Welcome to the Book!
Thanks!
Thanks for your interest in developing applications for Android! Android has grown
from nothing to arguably the world’s most popular smartphone OS in a few short
years. Whether you are developing applications for the public, for your business or
organization, or are just experimenting on your own, I think you will find Android to
be an exciting and challenging area for exploration.
And, most of all, thanks for your interest in this book! I sincerely hope you find it
useful and at least occasionally entertaining.
The Book’s Structure
As you may have noticed, this is a rather large book.
To make this vast quantity of material manageable, the chapters are divided into the
core chapters and a series of trails.
The core chapters represent many key concepts that Android developers need to
understand in order to build an app. While an occasional “nice to have” topic will
drift into the core — to help illustrate a point, for example — the core chapters
generally are fairly essential.
The core chapters are designed to be read in sequence and will interleave both
traditional technical book prose with tutorial chapters, to give you hands-on
experience with the concepts being discussed. Most of the tutorials can be skipped,
xliii
PREFACE
though the first two — covering setting up your SDK environment and creating a
project – everybody should read.
The bulk of the chapters are divided into trails, covering some particular general
topic, from data storage to advanced UI effects to performance measurement and
tuning. Each trail will have several chapters. However, those chapters, and the trails
themselves, are not necessarily designed to be read in any order. Each chapter in the
trails will point out prerequisite chapters or concepts that you will want to have
covered in advance. Hence, these chapters are mostly reference material, for when
you specifically want to learn something about a specific topic.
The core chapters will link to chapters in the trails, to show you where you can find
material related to the chapter you just read. So between the book’s table of
contents, this preface, the search tool in your digital book reader, and the crosschapter links, you should have plenty of ways of finding the material you want to
read.
You are welcome to read the entire book front-to-back if you wish. The trails will
appear after the core chapters. Those trails will be in a reasonably logical order,
though you may have to hop around a bit to cover all of the prerequisites.
The Trails
Here is a list of all of the trails and the chapters that pertain to those trails, in order
of appearance (except for those appearing in the list multiple times, where they span
major categories):
Code Organization and Gradle
•
•
•
•
•
•
•
Working with Library Projects
Gradle and Tasks
Gradle Build Variants
Manifest Merger Rules
Signing Your App
Distribution
Advanced Gradle for Android Tips
Testing
• Testing with JUnit4
xliv
PREFACE
•
•
•
•
•
Testing with Espresso
Testing with UIAutomator
Measuring Test Coverage
Unit Testing
MonkeyRunner and the Test Monkey
Rx
• Java 8 Lambda Expressions
• Rx Basics
Advanced UI
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Notifications
Advanced Notifications
Multi-Window Support
Advanced ConstraintLayout
GridLayout
Dialogs and DialogFragments
Advanced ListViews
Action Modes and Context Menus
Other Advanced Action Bar Techniques
Toolbar
AppCompat: The Official Action Bar Backport
RecyclerView
Implementing a Navigation Drawer
The Android Design Support Library
Advanced Uses of WebView
The Input Method Framework
Fonts
Rich Text
Animators
Legacy Animations
Custom Drawables
Mapping with Maps V2
Crafting Your Own Views
Advanced Preferences
Custom Dialogs and Preferences
Progress Indicators
More Fun with Pagers
xlv
PREFACE
•
•
•
•
•
•
•
•
•
•
Focus Management and Accessibility
Miscellaneous UI Tricks
Event Bus Alternatives
Tasks
The Assist API (“Now On Tap”)
The Auto-Fill API
Data Binding
Drag-and-Drop
Keyboard and Mouse Input
Viewing PDFs
Home Screen Effects
• Home Screen App Widgets
• Adapter-Based App Widgets
Data Storage and Retrieval
•
•
•
•
•
•
•
•
•
•
•
•
Content Provider Theory
Content Provider Implementation Patterns
The Loader Framework
The ContactsContract Provider
The CalendarContract Provider
The MediaStore Provider
Consuming Documents
Providing Documents
Encrypted Storage
Packaging and Distributing Data
Advanced Database Techniques
Data Backup
Advanced Network Topics
•
•
•
•
SSL
NetCipher
Embedding a Web Server
Miscellaneous Network Capabilities
xlvi
PREFACE
Media
•
•
•
•
•
•
•
•
•
•
•
•
•
Audio Playback
Audio Recording
Video Playback
Using the Camera via 3rd-Party Apps
Working Directly with the Camera
The MediaStore Provider
Media Routes
Supporting External Displays
Google Cast and ChromeCast
The “10 Foot UI”
Putting the TVs All Together: Decktastic
Creating a MediaRouteProvider
The Media Projection APIs
Security
•
•
•
•
•
•
SSL
NetCipher
Encrypted Storage
Advanced Permissions
Restricted Profiles and UserManager
Miscellaneous Security Techniques
Hardware and System Services
•
•
•
•
•
•
•
•
•
•
•
•
•
AlarmManager and the Scheduled Service Pattern
PowerManager and WakeLocks
JobScheduler
Accessing Location-Based Services
The Fused Location Provider
Working with the Clipboard
Telephony
Working With SMS
NFC
Device Administration
Basic Use of Sensors
Printing and Document Generation
Basic Bluetooth RFCOMM
xlvii
PREFACE
• Dealing with Different Hardware
Integration and Introspection
•
•
•
•
•
•
•
•
•
Writing and Using Parcelables
Responding to URLs
App Shortcuts
Plugin Patterns
PackageManager Tricks
Remote Services and the Binding Pattern
Advanced Manifest Tips
Miscellaneous Integration Tips
Replacing App Code Dynamically
Other Tools
•
•
•
•
•
•
•
•
•
Android Studio Dialogs and Editors
Advanced Emulator Capabilities
Lint and the Support Annotations
Inspecting Layouts
Screenshots and Screencasts
ADB Tips and Tricks
Stetho
Finding CPU Bottlenecks
Finding Memory Leaks
Tuning Android Applications
•
•
•
•
•
•
•
•
•
•
•
•
Issues with Speed
Finding CPU Bottlenecks
NDK
Improving CPU Performance in Java
Finding and Eliminating Jank
Issues with Bandwidth
Focus On: TrafficStats
Measuring Bandwidth Consumption
Being Smarter About Bandwidth
Issues with Application Heap
Finding Memory Leaks
Issues with System RAM
xlviii
PREFACE
•
•
•
•
Issues with Battery Life
Other Power Measurement Options
Sources of Power Drain
Addressing Application Size Issues
Miscellaneous Topics
•
•
•
•
Crash Reporting with ACRA
JVM Scripting Languages
In-App Diagnostics
Anti-Patterns
Widget Catalog
•
•
•
•
•
•
•
•
•
•
AdapterViewFlipper
CalendarView
DatePicker
ExpandableListView
SeekBar
SlidingDrawer
StackView
TabHost
TimePicker
ViewFlipper
Device Catalog
•
•
•
•
•
•
Chrome and Chrome OS
Android Things Basics
BlackBerry
Google TV
Amazon Fire TV
Samsung DeX
Appendices
• Appendix A: CWAC Libraries
• Appendix B: O Developer Preview
• Appendix C: Community Theater and the Appinars
xlix
PREFACE
About the Updates
This book is updated frequently, typically every 6-8 weeks.
Each release has notations to show what is new or changed compared with the
immediately preceding release:
• The Table of Contents shows sections with changes in bold-italic font
• Those sections have changebars on the right to denote specific paragraphs
that are new or modified
What’s New in Version 8.9?
For those of you who have read previous editions of this book, here are some of the
highlights of what is new in the prose in Version 8.9.
In this update, I:
• Added a new chapter on basic Bluetooth RFCOMM communications.
• Restored the chapter on Android Things (which had been pulled from
Version 8.8) and updated it to DP 6.1, including the use of the Android
Things Console.
• “Mainstreamed” about a third of the material from the Android 8.0
appendix into long-term homes in the other chapters. In particular, the
chapters on notifications wound up with a significant overhaul to
accommodate notification channels.
• Updated the MapsV2 samples to 11.6.2, including getting rid of the license
notification requirements.
• Added a section on the Android Test Orchestrator, which did not involve
timpani, much to my disappointment.
• Updated the chapter on working with the camera for the latest versions of
CameraKit-Android (now under new management!) and Fotoapparat.
• Fixed a variety of errata
• Bulk-replaced various onCreate() methods on activities, that formerly took
a Bundle parameter named icicle, to have the Bundle named state instead
Warescription
You (hopefully) are reading this digital book by means of a Warescription.
l
PREFACE
The Warescription entitles you, for the duration of your subscription, to digital
editions of this book and its updates, in PDF, EPUB, and Kindle (MOBI/KF8)
formats. You also have access to a version of the book as its own Android APK file,
complete with high-speed full-text searching. You also have access to other titles
that CommonsWare may publish during that subscription period.
Each subscriber gets personalized editions of all editions of each title. That way,
your books are never out of date for long, and you can take advantage of new
material as it is made available. For example, when new releases of the Android SDK
are made available, this book will be quickly updated to be accurate with changes in
the APIs.
However, you can only download the books while you have an active Warescription.
There is a grace period after your Warescription ends: you can still download the
book until the next book update comes out after your Warescription ends. After
that, you can no longer download the book. Hence, please download your
updates as they come out. You can find out when new releases of this book are
available via:
1. The CommonsWare Twitter feed
2. The CommonsBlog
3. The Warescription newsletter, which you can subscribe to off of your
Warescription page
4. Just check back on the Warescription site every month or two
Subscribers also have access to other benefits, including:
• “Office hours” — online chats to help you get answers to your Android
application development questions. You will find a calendar for these on
your Warescription page.
• A Stack Overflow “bump” service, to get additional attention for a question
that you have posted there that does not have an adequate answer.
• A discussion board for asking arbitrary questions about Android app
development
About the APK Edition
In addition to classic digital book formats (PDF, EPUB, MOBI/Kindle), this book is
available as an Android app, in the form of an APK file. This app has an integrated
li
PREFACE
digital book reader, showing you the same contents as you would find in the EPUB
version of the book. However, it has a few features that are unique.
First, it has a very fast full-text-search index built in. You can quickly search for
keywords, class names, and the like, with sub-second response time on most
Android hardware. You can even use boolean search clauses (e.g., search on
encryption OR decryption).
Second, it has Community Theater, where you can view appinars, or app-based
training modules. These are presentations, complete with slides, videos, screencasts,
source code, and more. Through Community Theater, you can view available
appinars, download those of interest, and watch them when you want.
The APK edition of the book reader works on Android 4.0.3 and higher, though the
Community Theater portion only works on Android 4.4 and higher.
Installation instructions for the APK edition can be found on the CommonsWare
Web site. Details about using Community Theater can be found in an appendix of
this book.
Book Bug Bounty
Find a problem in the book? Let CommonsWare know!
Be the first to report a unique concrete problem in the current digital edition, and
CommonsWare will extend your Warescription by six months as a bounty for
helping CommonsWare deliver a better product.
By “concrete” problem, we mean things like:
1. Typographical errors
2. Sample applications that do not work as advertised, in the environment
described in the book
3. Factual errors that cannot be open to interpretation
By “unique”, we mean ones not yet reported. Be sure to check the book’s errata page,
though, to see if your issue has already been reported. One coupon is given per
email containing valid bug reports.
We appreciate hearing about “softer” issues as well, such as:
lii
PREFACE
1. Places where you think we are in error, but where we feel our interpretation
is reasonable
2. Places where you think we could add sample applications, or expand upon
the existing material
3. Samples that do not work due to “shifting sands” of the underlying
environment (e.g., changed APIs with new releases of an SDK)
However, those “softer” issues do not qualify for the formal bounty program.
The Book Bug Bounty also extends to the appinars that you view in the Community
Theater portion of the APK edition of the book. Typos and similar concrete issues in
an appinar will qualify. Be sure to point out which appinar it is and what slide (or
code, screenshot, video, etc.) has the problem.
In addition, the Book Bug Bounty covers reproducible bugs in the APK itself. If you
are having problems using the APK, due to crashes or some other problem, be sure
to let us know, with sufficient steps to reproduce the problem (including
information about the device that you are using, such as the Android OS version).
Questions about the bug bounty, or problems you wish to report for bounty
consideration, should be sent to bounty@commonsware.com.
Source Code and Its License
The source code samples shown in this book are available for download from the
book’s GitHub repository. All of the Android projects are licensed under the Apache
2.0 License, in case you have the desire to reuse any of it.
If you wish to use the source code from the GitHub repository, please follow the
instructions on that repository’s home page for details of how to use the projects in
various development environments, notably Android Studio.
Copying source code directly from the book, in the PDF editions, works best with
Adobe Reader, though it may also work with other PDF viewers. Some PDF viewers,
for reasons that remain unclear, foul up copying the source code to the clipboard
when it is selected.
liii
PREFACE
Creative Commons and the Four-to-Free (42F)
Guarantee
Each CommonsWare book edition will be available for use under the Creative
Commons Attribution-Noncommercial-ShareAlike 3.0 license as of the fourth
anniversary of its publication date, or when 4,000 copies of the edition have been
sold, whichever comes first. That means that, once four years have elapsed (perhaps
sooner!), you can use this prose for non-commercial purposes. That is our Four-toFree Guarantee to our readers and the broader community. For the purposes of this
guarantee, new Warescriptions and renewals will be counted as sales of this edition,
starting from the time the edition is published.
This edition of this book will be available under the aforementioned Creative
Commons license on 1 December 2021. Of course, watch the CommonsWare Web
site, as this edition might be relicensed sooner based on sales.
For more details on the Creative Commons Attribution-Noncommercial-ShareAlike
3.0 license, visit the Creative Commons Web site
Note that future editions of this book will become free on later dates, each four years
from the publication of that edition or based on sales of that specific edition.
Releasing one edition under the Creative Commons license does not automatically
release all editions under that license.
Acknowledgments
I would like to thank the Android team, not only for putting out a good product, but
for invaluable assistance on the Android Google Groups and Stack Overflow.
I would also like to thank the thousands of readers of past editions of this book, for
their feedback, bug reports, and overall support.
Of course, thanks are also out to the overall Android ecosystem, particularly those
developers contributing their skills to publish libraries, write blog posts, answer
support questions, and otherwise contribute to the strength of Android.
Portions of this book are reproduced from work created and shared by the Android
Open Source Project and used according to terms described in the Creative
Commons 2.5 Attribution License.
liv
Core Chapters
Key Android Concepts
No doubt, you are in a hurry to get started with Android application development.
After all, you are reading this book, aimed at busy coders.
However, before we dive into getting tools set up and starting in on actual
programming, it is important that we “get on the same page” with respect to several
high-level Android concepts. This will simplify further discussions later in the book.
Android Applications
This book is focused on writing Android applications. An application is something
that a user might install from the Play Store or otherwise download to their device.
That application should have some user interface, and it might have other code
designed to work in the background (multi-tasking).
This book is not focused on modifications to the Android firmware, such as writing
device drivers. For that, you will need to seek other resources.
This book assumes that you have some hands-on experience with Android devices,
and therefore you are familiar with buttons like HOME and BACK, the built-in
Settings application, the concept of a home screen and launcher, and so forth. If you
have never used an Android device, you are strongly encouraged to get one (new or
used) and spend some time with it before starting in on learning Android
application development.
1
KEY ANDROID CONCEPTS
Programming Language
The vast majority of Android applications are written exclusively in Java. Hence, that
is what this book will spend most of its time on and will demonstrate with a
seemingly infinite number of examples.
However, there are other options:
• You can write parts of the app in C/C++, for performance gains, porting over
existing code bases, etc.
• You can write an entire app in C/C++, mostly for games using OpenGL for
3D animations
• You can write the guts of an app in HTML, CSS, and JavaScript, using tools
to package that material into an Android application that can be distributed
through the Play Store and similar venues
• And so on
Some of this will be covered later in the book, but the vast majority of this book is
focused on Java-based app development.
The author assumes that you know Java at this point. If you do not, you will need to
learn Java before you go much further. You do not need to know everything about
Java, as Java is vast. Rather, focus on:
•
•
•
•
•
•
•
•
•
•
•
•
Language fundamentals (flow control, etc.)
Classes and objects
Methods and data members
Public, private, and protected
Static and instance scope
Exceptions
Threads
Collections
Generics
File I/O
Reflection
Interfaces
The links are to Wikibooks material on those topics, though there are countless
other Java resources for you to consider.
2
KEY ANDROID CONCEPTS
Google also supports Kotlin as a programming language for Android apps. Kotlin
can be used as a replacement for Java. While Kotlin has plenty of benefits, it is also a
relatively new programming language. This book is focused on the Android SDK,
more so than on Java (or Kotlin), and so regardless of which of those two languages
you use, the material in this book will be relevant. This book’s examples are mostly
in Java, due to that being the dominant Android app development language today.
Components
When you first learned Java — whether that was yesterday or back when dinosaurs
roamed the Earth — you probably started off with something like this:
class SillyApp {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
In other words, the entry point into your application was a public static void
method named main() that took a String array of arguments. From there, you were
responsible for doing whatever was necessary.
However, there are other patterns used elsewhere in Java. For example, you do not
usually write a main() method when writing a Java servlet. Instead, you extend a
particular class supplied by a framework (e.g., HttpServlet) to create a component,
then write some metadata that enumerates your components and tell the framework
when and how to use them (e.g., WEB.XML).
Android apps are closer in spirit to the servlet approach. You will not write a
public static void main() method. Instead, you will create subclasses of some
Android-supplied base classes that define various application components. In
addition, you will create some metadata that tells Android about those subclasses.
There are four types of components, all of which will be covered extensively in this
book:
Activities
The building block of the user interface is the activity. You can think of an activity as
being the Android analogue for the window or dialog in a desktop application, or
the page in a classic Web app. It represents a chunk of your user interface and, in
3
KEY ANDROID CONCEPTS
some cases, a discrete entry point into your app (i.e., a way for other apps to link to
your app).
Normally, an activity will take up most of the screen, leaving space for some
“chrome” bits like the clock, signal strength indicators, and so forth.
However, bear in mind that on some devices, the user will be able to work with more
than one activity at a time, such as split-screen mode on a phone or tablet. So, while
it is easy to think of activities as being equivalent to the screen, just remember that
this is a simplification, and that reality is more complicated (as reality often is).
Services
Activities are short-lived and can be shut down at any time, such as when the user
presses the BACK button. Services, on the other hand, are designed to keep running,
if needed, independent of any activity, for a moderate period of time. You might use
a service for checking for updates to an RSS feed, or to play back music even if the
controlling activity is no longer operating. You will also use services for scheduled
tasks (akin to Linux or macOS “cron jobs”) and for exposing custom APIs to other
applications on the device, though the latter is a relatively advanced capability.
Content Providers
Content providers provide a level of abstraction for any data stored on the device
that is accessible by multiple applications. The Android development model
encourages you to make your own data available to other applications, as well as
your own — building a content provider lets you do that, while maintaining a degree
of control over how your data gets accessed.
So, for example, if you have a PDF file that you downloaded on behalf of the user,
and you want to allow the user to view that PDF file, you might create a content
provider to make that PDF file available to other apps. You can then start up an
activity that will be able to view that PDF, where Android and the user will
determine what PDF-viewing activity handles that request.
Broadcast Receivers
The system, or applications, will send out broadcasts from time to time, for
everything from the battery getting low, to when the screen turns off, to when
4
KEY ANDROID CONCEPTS
connectivity changes from WiFi to mobile data. A broadcast receiver can arrange to
listen for these broadcasts and respond accordingly.
Widgets, Containers, and Resources
Most of the focus on Android application development is on the UI layer and
activities. Most Android activities use what is known as “the widget framework” for
rendering their user interface, though you are welcome to use the 2D (Canvas) and
3D (OpenGL) APIs as well for more specialized GUIs.
In Android terms, a widget is the “micro” unit of user interface. Fields, buttons,
labels, lists, and so on are all widgets. Your activity’s UI, therefore, is made up of one
or more of these widgets. This is a common approach in most UI toolkits, and so
most likely you have already worked with buttons, labels, fields, and similar sorts of
widgets somewhere else previously.
If you have more than one widget — which is fairly typical — you will need to tell
Android how those widgets are organized on the screen. To do that, you will use
various container classes referred to as layout managers. These will let you put
things in rows, columns, or more complex arrangements as needed.
To describe how the containers and widgets are connected, you will typically create a
layout resource file. Resources in Android refer to things like images, strings, and
other material that your application uses but is not in the form of some
programming language source code. UI layouts are another type of resource. You will
create these layouts either using a structured tool, such as an IDE’s drag-and-drop
GUI builder, or by hand in XML form.
Sometimes, your UI will work across all sorts of devices: phones, tablets, televisions,
etc. Sometimes, your UI will need to be tailored for different environments. You will
be able to put resources into resource sets that indicate under what circumstances
those resources can be used (e.g., use these for normal-sized screens, but use those
for larger screens).
We will be examining all of these concepts, in much greater detail, as we get deeper
into the book.
5
KEY ANDROID CONCEPTS
Apps and Packages
Given a bucket of source code and a basket of resources, the Android build tools will
give you an application as a result. The application comes in the form of an APK file.
It is that APK file that you will upload to the Play Store or distribute by other means.
Each Android application has a package name, also referred to as an application ID.
A package name must fulfill three requirements:
1. It must be a valid Java package name, as some Java source code will be
generated by the Android build tools in this package
2. No two applications can exist on a device at the same time with the same
application ID
3. No two applications can be uploaded to the Play Store having the same
application ID
When you create your Android project — the repository of that source code and
those resources — you will declare what package name is to be used for your app.
Typically, you will pick a package name following the Java package name “reverse
domain name” convention (e.g., com.commonsware.android.foo). That way, the
domain name system ensures that your package name prefix (com.commonsware) is
unique, and it is up to you to ensure that the rest of the package name distinguishes
one of your apps from any other.
Android Devices
There are well in excess of one billion Android devices in use today, representing
thousands of different models from dozens of different manufacturers. Android
itself has evolved since Android 1.0 in 2008. Between different device types and
different Android versions, many a media pundit has lobbed the term
“fragmentation” at Android, suggesting that creating apps that run on all these
different environments is impossible.
In reality, it is not that bad. Some apps will have substantial trouble, but most apps
will work just fine if you follow the guidance presented in this book and in other
resources.
6
KEY ANDROID CONCEPTS
Types
Android devices come in all shapes, sizes, and colors. However, there are three
dominant “form factors”:
• the phone
• the tablet
• the notebook (mostly, these run Chrome OS, which has some support for
Android apps)
Beyond that, there are several less-common form factors
• the television (TV)
• the wearable (smart watches, etc.)
• the desktop (a device designed to be plugged into a monitor, keyboard, and
mouse)
You will often hear developers and pundits refer to these form factors, and this book
will do so from time to time as well. However, it is important that you understand
that Android has no built-in concept of a device being a “phone” or a “tablet” or a
“TV”. Rather, Android distinguishes devices based on capabilities and features. So,
you will not see an isPhone() method anywhere, though you can ask Android:
• what is the screen size?
• does the device have telephony capability?
• etc.
Similarly, as you build your applications, rather than thinking of those form factors,
focus on what capabilities and features you need. Not only will this help you line up
better with how Android wants you to build your apps, but it will make it easier for
you to adapt to other form factors that will come about such as:
• airplane seat-back entertainment centers
• in-car navigation and entertainment devices
• and so on
The Emulator
While there are ~2 billion Android devices representing ~10,000 device models,
probably you do not have one of each model. You may only have a single piece of
7
KEY ANDROID CONCEPTS
Android hardware. And if you do not even have that, you most certainly will want to
acquire one before trying to publish an Android app.
To help fill in the gaps between the devices you have and the devices that are
possible, the Android developer tools ship an emulator. The emulator behaves like a
piece of Android hardware, but it is a program you run on your development
machine. You can use this emulator to emulate many different devices, with
different screen sizes and Android OS versions, by creating one or more Android
virtual devices, or AVDs.
In an upcoming chapter, we will discuss how you install the Android developer tools
and how you will be able to create these AVDs and run the emulator.
OS Versions and API Levels
Android has come a long way since the early beta releases from late 2007. Each new
Android OS version adds more capabilities to the platform and more things that
developers can do to exploit those capabilities.
Moreover, the core Android development team tries very hard to ensure forwards
and backwards compatibility. An app you write today should work unchanged on
future versions of Android (forwards compatibility), albeit perhaps missing some
features or working in some sort of “compatibility mode”. And there are well-trod
paths for how to create apps that will work both on the latest and on previous
versions of Android (backwards compatibility).
To help us keep track of all the different OS versions that matter to us as developers,
Android has API levels. A new API level is defined when an Android version ships
that contains changes that affect developers. When you create an emulator AVD to
test your app, you will indicate what API level that emulator should emulate. When
you distribute your app, you will indicate the oldest API level your app supports, so
the app is not installed on older devices.
At the time of this writing, the API levels of significance to most Android developers
are:
•
•
•
•
•
API Level 19 (Android 4.4)
API Level 21 (Android 5.0)
API Level 22 (Android 5.1)
API Level 23 (Android 6.0)
API Level 24 (Android 7.0)
8
KEY ANDROID CONCEPTS
Here, “of significance” refers to API levels that have a reasonable number of Android
devices — 5% or more, as reported by the “Platform Versions” dashboard chart.
The latest version of Android is 8.1, API Level 27.
Note that API Level 20 was used for the version of Android 4.4 running on the firstgeneration Android Wear devices. Unless you are specifically developing apps for
Wear, you will not be worrying much about API Level 20.
Dalvik and ART
In terms of Android, Dalvik and ART are virtual machines (VM)s. Virtual machines
are used by many programming languages, such as Java, Perl, and Smalltalk. Dalvik
and ART are designed to work much like a Java VM, but optimized for embedded
Linux environments.
Primarily, the difference between the two is that ART is used on Android 5.0 and
higher, while Dalvik was used on older devices. In truth, the story is more
complicated than this, but this will do for now.
So, what really goes on when somebody writes an Android application is:
1. Developers write Java-syntax source code, leveraging class libraries published
by the Android project and third parties.
2. Developers compile the source code into Java VM bytecode, using the javac
compiler that comes with the Java SDK.
3. Developers translate the Java VM bytecode into Dalvik VM bytecode, which
is packaged with other files into a ZIP archive with the .apk extension (the
APK file).
4. An Android device or emulator runs the APK file, causing the bytecode to be
executed by an instance of a Dalvik or ART VM.
From your standpoint, most of this is hidden by the build tools. You pour Java source
code into the top, and the APK file comes out the bottom.
However, there will be places from time to time where the differences between the
Dalvik VM and the traditional Java VM will affect application developers, and this
book will point out some of them where relevant.
9
KEY ANDROID CONCEPTS
Processes and Threads
When your application runs, it will do so in its own process. This is not significantly
different than any other traditional operating system. Part of Dalvik’s magic is
making it possible for many processes to be running many Android applications at
one time without consuming ridiculous amounts of RAM.
Android will also set up a batch of threads for running your app. The thread that
your code will be executed upon, most of the time, is variously called the “main
application thread” or the “UI thread”. You do not have to set it up, but, as we will
see later in the book, you will need to pay attention to what you do and do not do on
that thread. You are welcome to fork your own threads to do work, and that is fairly
common, though in some places Android handles that for you behind the scenes.
Don’t Be Scared
Yes, this chapter threw a lot of terms at you. We will be going into greater detail on
all of them in this book. However, Android is like a jigsaw puzzle with lots of
interlocking pieces. To be able to describe one concept in detail, we will need to at
least reference some of the others. Hence, this chapter was meant to expose you to
terms, in hopes that they will sound vaguely familiar as we dive into the details.
10
Choosing Your Development
Toolchain
Before you go much further in your Android endeavors (or possibly endeavours,
depending upon your preferred spelling), you will need to determine what
toolchain you will use to build your Android applications.
Android Studio
The current Google-backed Android IDE is Android Studio. Based on IntelliJ IDEA,
Android Studio is the new foundation of Google’s efforts to give Android developers
top-notch development tools.
The next chapter contains a section with instructions on how to set up Android
Studio.
Note, though, that Android Studio requires a fairly powerful development machine
to work well: a fast CPU, lots of RAM (8GB or more), and an SSD are all strongly
recommended.
Eclipse
Eclipse is also a popular IDE, particularly for Java development. Eclipse was Google’s
original IDE for Android development, by means of the Android Developer Tools
(ADT) add-in, which gives the core of Eclipse awareness of Android. The ADT addin, in essence, takes regular Eclipse operations and extends them to work with
Android projects.
11
CHOOSING YOUR DEVELOPMENT TOOLCHAIN
Note, though, that Google has discontinued maintenance of ADT. The Eclipse
Foundation is setting up the “Andmore” project to try to continue work on allowing
Eclipse to build Android apps. This book does not cover the Andmore project at this
time, and developers are strongly encouraged to not use the ADT-enabled Eclipse
from Google.
IntelliJ IDEA
While Android Studio is based on IntelliJ IDEA, you can still use the original IntelliJ
IDEA for Android app development. A large subset of the Android Studio
capabilities are available in the Android plugin for IDEA. Plus, the commercial IDEA
Ultimate Edition will go beyond Android Studio in many areas outside of Android
development.
In particular, if you are looking for “the one true IDE” that you can use for Android
and non-Android projects, you should consider IntelliJ IDEA. Android Studio is
nice, but it is mostly for Android projects.
Command-Line Builds via Gradle
And, of course, you do not need to use an IDE at all. While this may sound
sacrilegious to some, IDEs are not the only way to build applications. Much of what
is accomplished via an IDE can be accomplished through command-line equivalents,
meaning a shell and an editor is all you truly need.
The recommended way to build Android apps outside of an IDE is by means of
Gradle. Google has published a Gradle plugin that teaches Gradle how to build
Android apps. Android Studio itself uses Gradle for its builds, so a single build
configuration (e.g., build.gradle files) can be used both from an IDE and from a
build automation tool like a continuous integration server.
An upcoming chapter gets into more about what Gradle (and the Android Gradle
Plugin) are all about.
Yet Other Alternatives
Other IDEs have their equivalents of the ADT, albeit with minimal assistance from
Google. For example, NetBeans has support via the NBAndroid add-on, and
reportedly this has advanced substantially in the past few years.
12
CHOOSING YOUR DEVELOPMENT TOOLCHAIN
You will also hear reference to using Apache Ant for doing command-line builds of
Android apps. This has been supplanted by the Android Gradle Plugin at this time,
and there is little support for Apache Ant anymore. Newcomers to Android are
encouraged to not invest time in new work with Apache Ant for Android
development projects.
IDEs… And This Book
You are encouraged to use Android Studio as you work through this book. You are
welcome to use another IDE if you wish. You are even welcome to skip the IDE
outright and just use an editor.
This book is focused primarily on demonstrating Android capabilities and the APIs
for exploiting those capabilities. Hence, the sample code will work with any IDE.
However, this book will cover some Android Studio-specific instructions, since that
is the predominant Android IDE in use today.
What We Are Not Covering
In the beginning (a.k.a., 2007), we were lucky to have any means of creating an
Android app.
Nowadays, there seems to be no end to the means by which we can create an
Android app.
There are a few of these “means”, though, that are specifically out of scope for this
book.
App Inventor
You may also have heard of a tool named App Inventor and wonder where it fits in
with all of this.
App Inventor was originally created by an education group within Google, as a
means of teaching students how to think about programming constructs (branches,
loops, etc.) and create interesting output (Android apps) without classic
programming in Java or other syntax-based languages. App Inventor is purely dragand-drop, both of widgets and application logic, the latter by means of “blocks” that
snap together to form logic chains.
13
CHOOSING YOUR DEVELOPMENT TOOLCHAIN
App Inventor was donated by Google to MIT, which has recently re-opened it to the
public.
However, App Inventor is a closed system — at the present time, it does not
somehow generate Java code that you can later augment. That limits you to whatever
App Inventor is natively capable of doing, which, while impressive in its own right,
offers a small portion of the total Android SDK capabilities.
App Generators
There are a seemingly infinite number of “app generators” available as online
services. These are designed mostly for creating apps for specific vertical markets,
such as apps for restaurants or apps for grocers. The resulting apps are mostly
“brochure-ware”, with few capabilities beyond a mobile Web site, yet still requiring
the user to find, download, and install the app. Few of these generators provide the
source code to the generated app, to allow the apps to be customized beyond what
the generator generates.
14
Tutorial #1 - Installing the Tools
Now, let us get you set up with the pieces and parts necessary to build an Android
app.
NOTE: The instructions presented here are accurate as of the time of this writing.
However, the tools change rapidly, and so these instructions may be out of date by
the time you read this. Please refer to the Android Developers Web site for current
instructions, using this as a base guideline of what to expect.
But First, Some Notes About Android’s Emulator
The Android tools include an emulator, a piece of software that pretends to be an
Android device. This is very useful for development — not only does it mean you
can get started on Android without a device, but the emulator can help test device
configurations that you do not own.
There are two types of emulator: x86 and ARM. These are the two major types of
CPUs used for Android devices. You really want to be able to use the x86 emulator,
as the ARM emulator is extremely slow.
However, to use the x86 emulator, your development machine must have things set
up properly first. Linux users need KVM, while Mac and Windows users need the
“Intel Hardware Accelerated Execution Manager” (a.k.a., HAXM).
Also, this only works for certain CPU architectures, ones that support virtualization
in hardware:
• Intel Virtualization Technology (VT, VT-x, vmx) extensions
• AMD Virtualization (AMD-V, SVM) extensions (Linux only)
15
TUTORIAL #1 - INSTALLING THE TOOLS
Those virtualization extensions must also be enabled in your device’s BIOS, and
other OS-specific modifications may be required.
Also, at least for newer API levels, your CPU must support SSSE3 extensions, though
the details of this requirement are not documented as of October 2017.
Part of the Android Studio installation process will try to set you up to be able to use
the x86 emulator. Make note of any messages that you see in the installation wizard
regarding “HAXM” (or, if you are running Linux, KVM), as those will be important
later.
Step #1: Checking Your Hardware
Compiling and building an Android application, on its own, can be a hardwareintensive process, particularly for larger projects. Beyond that, your IDE and the
Android emulator will stress your development machine further. Of the two, the
emulator poses the bigger problem.
The more RAM you have, the better. 8GB or higher is a very good idea if you intend
to use an IDE and the emulator together. If you can get an SSD for your data storage,
instead of a conventional hard drive, that too can dramatically improve the IDE
performance.
A faster CPU is also a good idea. The Android SDK emulator, as of 2016, supports
CPUs with multiple cores — previously, it only supported a single core. However,
other processes on your development machine will be competing with the emulator
for CPU time, and so the faster your CPU is, the better off you will be. Ideally, your
CPU has 2 to 4 cores, each 2.5GHz or faster at their base speed.
Beyond that, to use the x86 emulator — the emulator that runs well — you need a
CPU with certain features:
Development
OS
Windows
Mac
Linux
CPU Requirements
an Intel CPU with support for VT-x, EM64T, and “Execute Disable”
(XD)
any
an Intel CPU with support for VT-x, EM64T, and “Execute Disable”
(XD), or an AMD CPU with support for AMD-V
16
TUTORIAL #1 - INSTALLING THE TOOLS
If your CPU does not meet those requirements, you will want to have 1+ Android
devices available to you, so that you can test on hardware.
Also, if you are running Windows or Linux, you need to ensure that your computer’s
BIOS is set up to support Intel’s virtualization extensions. Unfortunately, many PC
manufacturers disable this by default. The details of how to get into your BIOS
settings will vary by PC, but usually it involves rebooting your computer and
pressing some function key on the initial boot screen. In the BIOS settings, you are
looking for references to “virtualization” or “VT-x”. Enable them if they are not
already enabled. macOS machines come with virtualization extensions pre-enabled.
Step #2: Setting Up Java and 32-Bit Linux Support
When you write Android applications, you typically write them in Java source code.
That Java source code is then turned into the stuff that Android actually runs
(Dalvik bytecode in an APK file).
Android Studio, starting with version 2.2, ships with its own private copy of
OpenJDK 8, and it will use that by default. You are welcome to install and use your
own JDK if you wish, though ideally it is for Java 8.
If your development OS is Linux, make sure that you can run 32-bit Linux binaries.
This may or may not already be enabled in your Linux distro. For example, on
Ubuntu 14.10, you may need to run the following to get the 32-bit binary support
installed that is needed by the Android build tools:
sudo apt-get install lib32z1 lib32ncurses5 lib32stdc++6
You may also need lib32bz2-1.0, depending on your version of Linux.
Step #3: Install Android Studio
As noted in the previous chapter, there are a few developer tools that you can choose
from.
This book’s tutorials focus on Android Studio. You are welcome to attempt to use
Eclipse, another IDE, or no IDE at all for building Android apps. However, you will
need to translate some of the tutorials’ IDE-specific instructions to be whatever is
needed for your development toolchain of choice.
17
TUTORIAL #1 - INSTALLING THE TOOLS
At the time of this writing, the current production version of Android Studio is 3.0.0,
and this book covers that version. If you are reading this in the future, you may be
on a newer version of Android Studio, and there may be some differences between
what you have and what is presented here.
You have two major download options. You can get the latest shipping version of
Android Studio from the Android Studio download page.
Figure 1: Android Studio Download Page
Or, you can download Android Studio 3.0.1 — the version used in this edition of
this book — directly, for:
• Windows
• macOS
• Linux
Windows users can download a self-installing EXE, which will add suitable launch
options for you to be able to start the IDE.
macOS users can download a DMG disk image and install it akin to other macOS
software, dragging the Android Studio icon into the Applications folder.
Linux users (and power Windows users) can download a ZIP file, then unZIP it to
some likely spot on your hard drive. Android Studio can then be run from the
studio batch file or shell script from your Android Studio installation’s bin/
directory.
18
TUTORIAL #1 - INSTALLING THE TOOLS
Step #4: Install the SDKs and Add-Ons
Next, we need to review what pieces of the Android SDK we have already and
perhaps install some new items. To do that, you need to access the SDK Manager.
When you first run Android Studio, you may be asked if you want to import settings
from some other prior installation of Android Studio:
Figure 2: Android Studio First-Run Settings Migration Dialog
For most users, particularly those using Android Studio for the first time, the “I do
not have…” option is the correct choice to make.
Then, after a short splash screen and a potentially long “Finding Available SDK
Components” progress dialog, you will be taken to the Android Studio Setup
Wizard:
19
TUTORIAL #1 - INSTALLING THE TOOLS
Figure 3: Android Studio Setup Wizard, First Page
Just click “Next” to advance to the second page of the wizard:
20
TUTORIAL #1 - INSTALLING THE TOOLS
Figure 4: Android Studio Setup Wizard, Second Page
Here, you have a choice between “Standard” and “Custom” setup modes. Most likely,
right now, the “Standard” route will be fine for your environment.
If you go the “Standard” route and click “Next”, you should be taken to a wizard page
where you can choose your UI theme:
21
TUTORIAL #1 - INSTALLING THE TOOLS
Figure 5: Android Studio Setup Wizard, UI Theme Page
Choose whichever you like, then click Next, to go to a wizard page to verify what will
be downloaded and installed:
22
TUTORIAL #1 - INSTALLING THE TOOLS
Figure 6: Android Studio Setup Wizard, Verify Settings Page
Clicking Next may take you to a wizard page explaining some information about the
Android emulator:
23
TUTORIAL #1 - INSTALLING THE TOOLS
Figure 7: Android Studio Setup Wizard, Emulator Info Page
What is explained on this page may not make much sense to you. That is perfectly
normal, and we will get into what this page is trying to say later in the book. Just
click “Finish” to begin the setup process. This will include downloading a copy of the
Android SDK and installing it into a directory adjacent to where Android Studio
itself is installed.
When that is done, after clicking “Finish”, Android Studio will busily start
downloading stuff to your development machine. If you are running Linux, and your
installation crashes with an “Unable to run mksdcard SDK tool” error, go back to
Step #2 and set up 32-bit support on your Linux environment.
Clicking “Finish” will then take you to the Android Studio Welcome dialog:
24
TUTORIAL #1 - INSTALLING THE TOOLS
Figure 8: Android Studio Welcome Dialog
Then, in the welcome dialog, click Configure, to bring up a configuration drop-down
list:
Figure 9: Android Studio Welcome Dialog, Configure Drop-Down List
There, tap on SDK Manager to bring up the SDK Manager.
25
TUTORIAL #1 - INSTALLING THE TOOLS
Using SDK Manager and Updating Your Environment
You should now have the SDK Manager open, as part of the overall default settings
for Android Studio:
Figure 10: Android SDK Manager, “SDK Platforms” Tab
The “SDK Platforms” tab lists the versions of Android that you can compile against.
The latest version of Android (or possibly a preview edition) is usually installed
when you set up Android Studio initially. However, for the tutorials, please also
check “Android 7.1 (Nougat)” in the list if it is not already checked, and then click
the “Apply” button to download and install those versions. You may need to accept a
license confirmation dialog as part of this process — review the license, and if you
accept it, click Next to begin the download:
26
TUTORIAL #1 - INSTALLING THE TOOLS
Figure 11: Android SDK Manager, License Confirmation Dialog
When that has completed, you can click “Finish” to close up the download dialog,
and then you will be returned to the SDK Manager. Then, you can close up the SDK
Manager by clicking the OK button.
In Our Next Episode…
… we will create an Android project that will serve as the basis for all our future
tutorials, plus set up our emulator and device.
27
Android and Projects
When you work on creating an app for Android, you will do so by working in a
“project”. The project is a directory containing your source code and other files, like
images and UI definitions. Your IDE or other build tools will take what is in your
project and generate an Android app (APK) as output.
The details of how you get started with a project vary based upon what IDE you are
using, so this chapter goes through the various possibilities.
Projects and Android Studio
With Android Studio, to work on a project, you can either create a new project from
scratch, you can copy an existing Android Studio project to a new one, or you can
import an existing Android project into Android Studio. The following sections will
review the steps needed for each of these.
Creating a New Project
You can create a project from one of two places:
• If you are at the initial dialog that you first encountered when you opened
Android Studio, choose the “Start a new Android Studio project…” menu
item
• If you are inside the Android Studio IDE itself, choose File > New > New
Project… from the main menu
This brings up the new-project wizard:
29
ANDROID AND PROJECTS
Figure 12: Android Studio Create-Project Wizard, First Page
The first page of the wizard is where you can specify:
• The application name, which is the initial name of your project as seen by
the user, in places like your home screen launcher icon and the list of
installed applications.
• The package name, which refers to a Java package name (e.g.,
com.commonsware.empublite). This package name will be used for
generating some Java source code, and it also is used as a unique identifier of
this package, as was mentioned earlier in this book.
• The directory where you want the project files to go
• Whether you know right now if you will be using C++ or not, as part of the
Android Native Development Kit (NDK)
• Whether you know right now if you will be using Kotlin or not
Nothing that you choose here is permanent; you can revise everything later on if
needed. The most painful to change is the package name, so ideally you choose a
good value up front.
By default, the package name will be made up of two pieces:
30
ANDROID AND PROJECTS
1. The domain name that you specify in the “Company Domain” field
2. The application name, converted into all lowercase with no spaces or other
punctuation
If this is not what you want, click the “Edit” button on the far right side of the
proposed package name, which will now allow you to edit the package name
directly:
Figure 13: Android Studio Create-Project Wizard, First Page, with Editable Package
Name
Clicking “Next” will advance you to a wizard page where you indicate what sort of
project you are creating, in terms of intended device type (phones/tablets, TVs, etc.)
and minimum required SDK level:
31
ANDROID AND PROJECTS
Figure 14: Android Studio Create-Project Wizard, Second Page
The “Minimum SDK” refers to how far back in Android’s version history you are
willing to support. The lower the value you specify here, the more Android devices
can run your app, but the more work you will have to do to test whether your app
really does support those devices.
Developers just starting out on Android should only check “Phone and Tablet” as
the device type, leaving the other checkboxes unchecked. The default “Minimum
SDK” value also usually is a good choice, and it can be changed readily in your
project, as we will see later in the book.
Clicking “Next” advances you to the third page of the wizard, where you can choose
if Android Studio should create an initial activity for you, and if so, based on what
template:
32
ANDROID AND PROJECTS
Figure 15: Android Studio Create-Project Wizard, Third Page
None of these templates are especially good, as they add a lot of example material
that you will wind up replacing. “Empty Activity” is the best of the available options
for first-time Android developers, simply because it adds the least amount of this
“cruft”.
If you choose any option other than “Add No Activity”, clicking “Next” will advance
you to a page in the wizard where you can provide additional details about the
activity to be created:
33
ANDROID AND PROJECTS
Figure 16: Android Studio Create-Project Wizard, Fourth Page
What options appear here will vary based upon the template you chose in the
previous page. Common options include “Activity Name” (the name of the Java class
for your activity) and “Layout Name” (the base name of an XML file that will contain
a UI definition of your activity).
The “Backwards Compatibility (AppCompat)” checkbox indicates if you want to use
a library known as AppCompat. We will discuss using libraries later in the book, as
well as what this “AppCompat” is. Unless you know for certain that you want to use
AppCompat — and few of this book’s example apps do — uncheck this checkbox.
Clicking “Finish” will generate your project files.
Copying a Project
Android Studio projects are simply directories of files, with no special metadata held
elsewhere. Hence, to copy a project, just copy its directory.
Importing a Project
You can import a project from one of two places:
34
ANDROID AND PROJECTS
• If you are at the initial dialog that you first encountered when you opened
Android Studio, choose the “Import Project…” menu item
• If you are inside the Android Studio IDE itself, choose File > New… > Import
Project… from the main menu
Then, choose the directory containing the project to be imported.
What happens now depends upon the nature of the project. If the project was
already set up for use with Android Studio, or at least with the Android Gradle
Plugin, the Android Studio-specific files will be created (or updated) in the project
directory.
However, if the project was not set up for Android Studio (or at least for the Android
Gradle Plugin), but does have Eclipse project files (or at least a project.properties
file), you will be led through an Eclipse import wizard. This will be fairly uncommon
nowadays.
Starter Project Generators
In addition to creating projects through an IDE’s new-project wizard, there are
various Web sites that offer online project generators:
• Android Bootstrap
• Android Kickstartr
On those sites, you provide basic configuration data, such as your application’s
package name, and they generate a complete starter project for you. These projects
tend to be significantly more advanced than what you get from the IDE wizards. On
the plus side, you get a more elaborate “scaffold” on which you can “hang” your own
business logic. However, understanding what those generators create and how to
change the generated code requires a fair bit of Android development experience.
35
Tutorial #2 - Creating a Stub Project
Creating an Android application first involves creating an Android “project”. As with
many other development environments, the project is where your source code and
other assets (e.g., icons) reside. And, the project contains the instructions for your
tools for how to convert that source code and other assets into an Android APK file
for use with an emulator or device, where the APK is Android’s executable file
format.
Hence, in this tutorial, we kick off development of a sample Android application, to
give you the opportunity to put some of what you are learning in this book in
practice.
About Our Tutorial Project
The application we will be building in these tutorials is called EmPubLite. EmPubLite
will be a digital book reader, allowing users to read a digital book like the one that
you are reading right now.
EmPubLite
will be a partial implementation of the EmPub reader used for the APK
version of this book. EmPub itself is a fairly extensive application, so EmPubLite will
have only a subset of its features.
The “Em” of EmPub and EmPubLite stands for “embedded”. These readers are not
designed to read an arbitrary EPUB or MOBI formatted book that you might
download from somewhere. Rather, the contents of the book (largely an unpacked
EPUB file) will be “baked into” the reader APK itself, so by distributing the APK, you
are distributing the book.
37
TUTORIAL #2 - CREATING A STUB PROJECT
About the Rest of the Tutorials
Of course, you may have little interest in writing a digital book reader app.
The tutorials presented in this book are certainly optional. There is no expectation
that you have to write any code in order to get value from the book. These tutorials
are here simply as a way to help those of you who “learn by doing” have an
opportunity to do just that.
Hence, there are any number of ways that you can use these tutorials:
• You can ignore them entirely. That is not the best answer, but you are
welcome to do it.
• You can read the tutorials but not actually do any of the work. This is the
best low-effort answer, as it is likely that you will learn things from the
tutorials that you might have missed by simply reading the non-tutorial
chapters.
• You can follow along the steps and actually build the EmPubLite app.
• You can download the answers from the book’s GitHub repository. There,
you will find one directory per tutorial, showing the results of having done
the steps in that tutorial. For example, you will find a T2-Project/ directory
containing a copy of the EmPubLite sample app after having completed the
steps found in this tutorial. You can import these projects into your IDE,
examine what they contain, cross-reference them back to the tutorials
themselves, and run them.
Any of these are valid options — you will need to choose for yourself what you wish
to do.
About Our Tools
The instructions in the remaining tutorials should be accurate for Android Studio
3.0.x. The instructions may work for other versions of this IDE, but there may also
be some differences.
Step #1: Importing the Project
We need to create the Android project for EmPubLite.
38
TUTORIAL #2 - CREATING A STUB PROJECT
Normally, you would use the new-project wizard to create a new project. However,
the problem with the new-project wizard is that Google keeps changing what the
new-project wizard generates. In most situations, that is not a huge problem.
However, it becomes a problem for tutorials like this one, as if Google changes what
is in the new project, the tutorial’s instructions become out of date.
So, instead, we will import an existing project, so we can start from a stable base.
Visit the releases page of this book’s GitHub repository. Then, scroll down to this
book’s version and download the EmPubLite-Starter.zip file for it. UnZIP that
project to some place on your development machine. It will unZIP into an
EmPubLite/ directory.
Then, import the project. From the Android Studio welcome dialog, that is handled
by the “Import project (Eclipse ADT, Gradle, etc.)” option. From an existing open
Android Studio IDE window, you would use File > New > Import Project… from the
main menu.
Importing a project brings up a typical directory-picker dialog. Pick the EmPubLite/
directory and click OK to begin the import process. This may take a while,
depending on the speed of your development machine. A “Tip of the Day” dialog
may appear, which you can dismiss.
At this point, you should have an empty Android Studio IDE window, probably with
an error message:
39
TUTORIAL #2 - CREATING A STUB PROJECT
Figure 17: Android Studio, As Initially Launched, Showing Error
In the “Messages Gradle Sync” tool pane, towards the bottom of the screen, you may
have a “Failed to find Build Tools revision 25.0.3”. Each Android project states what
version of the development tools it uses, and this one uses a version slightly older
than the current. In that tool pane, the “Install Build Tools 25.0.3 and sync project”
message is a hyperlink — click that to download the missing bits. This is a common
pattern with these error messages, where the message will contain a link to try to fix
the problem.
Next, after several moments, you will get a pop-up dialog like this one:
Figure 18: Android Studio, Update Recommendation Dialog
40
TUTORIAL #2 - CREATING A STUB PROJECT
The trigger for this dialog is similar to the trigger for the preceding error message:
the project that you imported is looking to use some older tools than what is the
latest-and-greatest. For projects that you create yourself from scratch, you will not
get this message, as the new-project wizard always uses the latest tools… even if that
is not always the best idea. For projects like this one, that you import from
elsewhere, this dialog is common. For the purposes of these tutorials, click the
“Don’t remind me again for this project” button. For other projects that you import,
you could opt to click the “Update” button, which will adjust the project to use the
newer tools, though this may cause compatibility problems that you would have to
debug.
The “Project” tool — docked by default on the left side, towards the top — brings up
a way for you to view what is in the project. Android Studio has several ways of
viewing the contents of Android projects. The default one, that you are presented
with when creating or importing the project, is known as the “Android view”:
Figure 19: Android Studio “Android View”
While you are welcome to navigate your project using it, the tutorial chapters in this
book, where they have screenshots of Android Studio, will show the project view:
41
TUTORIAL #2 - CREATING A STUB PROJECT
Figure 20: Android Studio “Project View”
To switch to this view — and therefore match what the tutorials will show you —
click the “Android” entry above the tree, to display a drop-down of different views.
Choose “Project”, and that will switch you to the project view used by these tutorials.
Step #2: Get Ready for the x86 Emulator
Your first decision to make is whether or not you want to bother setting up an
emulator image right now. If you have an Android device, you may prefer to start
testing your app on it, and come back to set up the emulator at a later point. In that
case, skip to Step #4.
Otherwise, here is what you may need to do, based on the operating system on your
development machine.
Windows
If your CPU met the requirements, and you successfully enabled the right things in
your system’s BIOS, the Android Studio installation should have installed HAXM,
and you should be ready to go.
If, on the other hand, you got some error messages in the installation wizard
regarding HAXM, you would need to address those first.
42
TUTORIAL #2 - CREATING A STUB PROJECT
Mac
The wizards of Cupertino set up their Mac hardware to be able to run the Android
x86 emulator, which is awfully nice of them, considering that Android competes
with iOS. The Android Studio installation wizard should have installed HAXM
successfully, and you should be able to continue with the next step of the tutorial.
Linux
The Android x86 emulator on Linux does not use HAXM. Instead, it uses KVM, a
common Linux virtualization engine.
If, during the Android Studio installation process, the wizard showed you a page
that said that you needed to configure KVM, you will need to do just that before you
can set up and use the x86 emulator. The details of how to set up KVM will vary by
Linux distro (e.g., Ubuntu).
Step #3: Set Up the AVD
The Android emulator can emulate one or several Android devices. Each
configuration you want is stored in an “Android virtual device”, or AVD. The AVD
Manager is where you create these AVDs.
Note that Android Studio now has its own implementation of the AVD Manager that
is separate from the one Android developers have traditionally used. You may see
screenshots of the older AVD Manager in blog posts, Stack Overflow answers, and
the like. The AVD Manager still fills the same role, but it has a different look and
feel.
To open the AVD Manager in Android Studio, choose Tools > Android > AVD
Manager from the main menu.
You should be taken to “welcome”-type screen:
43
TUTORIAL #2 - CREATING A STUB PROJECT
Figure 21: Android Studio AVD Manager, Welcome Screen
Click the “Create Virtual Device” button, which brings up a “Virtual Device
Configuration” wizard:
44
TUTORIAL #2 - CREATING A STUB PROJECT
Figure 22: Android Studio Virtual Device Configuration Wizard, First Page
The first page of the wizard allows you to choose a device profile to use as a starting
point for your AVD. The “New Hardware Profile” button allows you to define new
profiles, if there is no existing profile that meets your needs.
Since emulator speeds are tied somewhat to the resolution of their (virtual) screens,
you generally aim for a device profile that is on the low end but is not completely
ridiculous. For example, an 800x480 or 1280x768 phone would be considered by
many people to be fairly low-resolution. However, there are plenty of devices out
there at that resolution (or lower), and it makes for a reasonable starting emulator.
If you want to create a new device profile based on an existing one — to change a
few parameters but otherwise use what the original profile had – click the “Clone
Device” button once you have selected your starter profile.
However, in general, at the outset, using an existing profile is perfectly fine. The
Galaxy Nexus or Nexus 4 images are likely choices to start with.
Clicking “Next” allows you to choose an emulator image to use:
45
TUTORIAL #2 - CREATING A STUB PROJECT
Figure 23: Android Studio Virtual Device Configuration Wizard, Second Page
The emulator images are spread across three tabs:
• “Recommended”
• “x86 Images”
• “Other Images”
For the purposes of the tutorials, you do not need an emulator image with the
“Google APIs” — those are for emulators that have Google Play Services in them and
related apps like Google Maps. However, in terms of API level, you can choose
anything from API Level 15 (Android 4.0.3) on up. You should have one or more
suitable images already set up for you, courtesy of having installed Android Studio.
If you click on the x86 Images tab, you should see some images with a “Download”
link, and others without it:
46
TUTORIAL #2 - CREATING A STUB PROJECT
Figure 24: Android Studio Virtual Device Configuration Wizard, x86 Images
The emulator images with “Download” next to them will trigger a one-time
download of the files necessary to create AVDs for that particular API level and CPU
architecture combination, after another license dialog and progress dialog:
47
TUTORIAL #2 - CREATING A STUB PROJECT
Figure 25: Android Studio Component Installer Dialog, Downloading API 23 ARM
Image
Once you have identified the image(s) that you want — and have downloaded any
that you did not already have — click on one of them in the wizard:
48
TUTORIAL #2 - CREATING A STUB PROJECT
Figure 26: Android Studio Virtual Device Configuration Wizard, After Choosing
Image
Clicking “Next” allows you to finalize the configuration of your AVD:
49
TUTORIAL #2 - CREATING A STUB PROJECT
Figure 27: Android Studio Virtual Device Configuration Wizard, Third Page
A default name for the AVD is suggested, though you are welcome to replace this
with your own value.
Change the AVD name, if necessary, to something valid: only letters, numbers,
spaces, and select punctuation (e.g., ., _, -, (, )) are supported.
The rest of the default values should be fine for now.
Clicking “Finish” will return you to the main AVD Manager, showing your new AVD.
You can then close the AVD Manager window.
Step #4: Set Up the Device
You do not need an Android device to get started in Android application
development. Having one is a good idea before you try to ship an application (e.g.,
upload it to the Play Store). And, perhaps you already have a device – maybe that is
what is spurring your interest in developing for Android.
50
TUTORIAL #2 - CREATING A STUB PROJECT
If you do not have an Android device that you wish to set up for development, skip
this step.
The first step to make your device ready for use with development is to go into the
Settings application on the device. What happens now depends a bit on your
Android version:
• On Android 1.x/2.x, go into Applications, then into Development
• On Android 3.0 through 4.1, go into “Developer options” from the main
Settings screen
• On Android 4.2 and higher, go into About, tap on the build number seven
times, then press BACK, and go into “Developer options” (which was
formerly hidden)
Figure 28: Developer Options, in Settings App
You may need to slide a switch in the upper-right corner of the screen to the “ON”
position to modify the values on this screen.
Generally, you will want to scroll down and enable USB debugging, so you can use
your device with the Android build tools:
51
TUTORIAL #2 - CREATING A STUB PROJECT
Figure 29: Debugging Options, in Settings App
You can leave the other settings alone for now if you wish, though you may find the
“Stay awake” option to be handy, as it saves you from having to unlock your phone
all of the time while it is plugged into USB.
Note that on Android 4.2.2 and higher devices, before you can actually use the
setting you just toggled, you will be prompted to allow USB debugging with your
specific development machine via a dialog box:
52
TUTORIAL #2 - CREATING A STUB PROJECT
Figure 30: Allow USB Debugging Dialog
This occurs when you plug in the device via the USB cable and have the driver
appropriately set up. That process varies by the operating system of your
development machine, as is covered in the following sections.
Windows
When you first plug in your Android device, Windows will attempt to find a driver
for it. It is possible that, by virtue of other software you have installed, that the
driver is ready for use. If it finds a driver, you are probably ready to go.
If the driver is not found, here are some options for getting one.
Windows Update
Some versions of Windows (e.g., Vista) will prompt you to search Windows Update
for drivers. This is certainly worth a shot, though not every device will have supplied
its driver to Microsoft.
Standard Android Driver
In your Android SDK installation, if you chose to install the “Google USB Driver”
package from the SDK Manager, you will find an extras/google/usb_driver/
53
TUTORIAL #2 - CREATING A STUB PROJECT
directory, containing a generic Windows driver for Android devices. You can try
pointing the driver wizard at this directory to see if it thinks this driver is suitable
for your device. This will often work for Nexus devices.
Manufacturer-Supplied Driver
If you still do not have a driver, the OEM USB Drivers in the developer
documentation may help you find one for download from your device manufacturer.
Note that you may need the model number for your device, instead of the model
name used for marketing purposes (e.g., GT-P3113 instead of “Samsung Galaxy Tab 2
7.0”).
macOS and Linux
Odds are decent that simply plugging in your device will “just work”. You can see if
Android recognizes your device via running adb devices in a shell (e.g., macOS
Terminal), where adb is in your platform-tools/ directory of your SDK. If you get
output similar to the following, the build tools detected your device:
List of devices attached
HT9CPP809576 device
If you are running Ubuntu (or perhaps other Linux variants), and this command did
not work, you may need to add some udev rules. For example, here is a
51-android.rules file that will handle the devices from a handful of manufacturers:
SUBSYSTEM=="usb", SYSFS{idVendor}=="0bb4", MODE="0666"
SUBSYSTEM=="usb", SYSFS{idVendor}=="22b8", MODE="0666"
SUBSYSTEM=="usb", SYSFS{idVendor}=="18d1", MODE="0666"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="18d1", ATTRS{idProduct}=="0c01", MODE="0666",
OWNER="[me]"
SUBSYSTEM=="usb", SYSFS{idVendor}=="19d2", SYSFS{idProduct}=="1354", MODE="0666"
SUBSYSTEM=="usb", SYSFS{idVendor}=="04e8", SYSFS{idProduct}=="681c", MODE="0666"
Drop that in your /etc/udev/rules.d directory on Ubuntu, then either reboot the
computer or otherwise reload the udev rules (e.g., sudo service udev reload).
Then, unplug and re-plug in the device and see if it is detected.
54
TUTORIAL #2 - CREATING A STUB PROJECT
Step #5: Running the Project
Now, we can confirm that our project is set up properly by running it on a device or
emulator.
To do that in Android Studio, just press the Run toolbar button (usually depicted as
a green rightward-pointing triangle).
You will then be presented with a dialog indicating where you want the app to run:
on some existing device or emulator, or on some newly-launched emulator:
Figure 31: Android Studio Device Chooser Dialog
If you do not have an emulator running, choose one from the list, then click OK.
Android Studio will launch your emulator for you.
And, whether you start a new emulator instance or reuse an existing one, your app
should appear on it:
55
TUTORIAL #2 - CREATING A STUB PROJECT
Figure 32: Android 7.0 Emulator with EmPubLite
Note that you may have to unlock your device or emulator to actually see the app
running. It will not unlock automatically for you, except the very first time that you
run the emulator.
In Our Next Episode…
… we will modify the AndroidManifest.xml file of our tutorial project.
56
Getting Around Android Studio
This chapter will serve as a quick tour of the Android Studio IDE, to help you get
settled in. Other Android-specific capabilities of Android Studio will be explored in
the chapters that follow.
Navigating The Project Explorer
After the main editing area — where you will modify your Java source code, your
resources, and so forth — the piece of Android Studio you will spend the most time
with is the project explorer, usually available on the left side of the IDE window:
Figure 33: Android Studio Project Explorer, Showing Android Project View
This explorer pane has two main “project views” that an Android developer will use:
the Android project view and the classic project view.
57
GETTING AROUND ANDROID STUDIO
Android Project View
By default, when you create or import a project, you will wind up in the Android
project view.
In theory, the Android project view is designed to simplify working with Android
project files. In practice, it may do so, but only for some advanced developers. On
the whole, it makes the IDE significantly more complicated for newcomers to
Android, as it is rather difficult to see where things are and what relates to what.
We will return to the Android project view a bit later in the book and explain its
benefits relative to resources and Gradle’s source sets.
However, for most of the book — most importantly, for the tutorials – we will use
the classic project view.
Classic Project View
To switch to the classic project view, click the pair of arrowheads to the right of the
“Project Files” tab just above the tree in the explorer, and choose Project:
Figure 34: Android Studio Project Explorer, Showing Project View Drop-Down
On some machines, in some cases, the pair of arrowheads is instead a single dropdown arrowhead next to the currently-chosen view (e.g., Android).
Switching to the project view will change the contents of the tree to show you all of
the files, in their associated directories:
58
GETTING AROUND ANDROID STUDIO
Figure 35: Android Studio Project Explorer, Showing Classic Project View
This project view is much like its equivalent in other IDEs, allowing you to find all of
the pieces of your Android project. We will be exploring what those pieces are, and
how their files are organized in our projects, in the next chapter.
Context Menus in the Explorer
Right-clicking over a directory or file in the explorer will give you a context menu
with a variety of options. Some of these will be typical of any sort of file manager,
such as “cut”, “copy”, and/or “paste” options. Some of these will be organized
according to how Android Studio manages application development, such as the
“Refactor” sub-menu, where you can rename or move files around. Yet others will be
specific to Android Studio, such as the ability to invoke wizards to create certain
types of Android components or other Java classes.
Opening Files from the Explorer
Double-clicking on a file usually opens that file in a tab that allows you to edit that
file, using some sort of editor.
59
GETTING AROUND ANDROID STUDIO
Some file types, like images, can be opened but not edited, as Android Studio does
not have editors for all file types.
Running Projects
Of course, as you change your app, you will want to try it out and see if it works,
whether on a device or an emulator.
The Basics
As noted in Tutorial #2, to run your project, just press the Run toolbar button:
Figure 36: Android Studio Run Controls, Showing Green Arrow to Run the App
You will then be presented with a dialog indicating where you want the app to run:
Figure 37: Android Studio Device Chooser Dialog
The “Connected Devices” category lists any devices or running emulators that the
build tools can find. Some may be disabled due to compatibility issues, such as
having an emulator for an old version of Android where your app requires a newer
version of Android.
The “Available Emulators” category lists all AVDs that you have defined in the AVD
Manager that are not already running. Again, you may find that some are disabled
for compatibility reasons.
60
GETTING AROUND ANDROID STUDIO
The “Create New Emulator” button brings up the wizard to create a new AVD, just
like the one you can launch from the AVD Manager.
“Instant Run”
Next to the green “run” arrow button in the toolbar is a lightning bolt button.
Sometimes, this will be grayed out and unusable. Other times, it will appear in
yellow:
Figure 38: Android Studio Run Controls, With Instant Run Enabled
This button performs what is called “Instant Run”. Instead of building your app and
pushing the app to the device or emulator, Instant Run attempts to patch your
existing app based on whatever changes you made to the project since you last ran
it.
On the plus side, Instant Run is very fast. However, the patched app is not exactly
the same as would be your app built from scratch. Feel free to use this for smaller
changes if you wish.
Viewing Output
Beyond your app itself, Android Studio will generate other sorts of diagnostic
output, in the form of “console”-style transcripts of things that have occurred. The
two of these that probably will matter most for you are the Gradle console and
Logcat.
Gradle Console
By default, docked in the lower-right corner of your Android Studio window is a
“Gradle Console” item. Tapping on that will open up a pane showing the output of
attempts to build your application:
61
GETTING AROUND ANDROID STUDIO
Figure 39: Android Studio Gradle Console
This may automatically appear from time to time, if specific build problems are
detected, and you can always go examine it whenever you need.
Click on the “Gradle Console” item again to collapse the view and get it out of your
way.
Logcat
Messages that appear at runtime — including the all-important Java stack traces
triggered by bugs in your code — are visible in Logcat. The Logcat tool docked
towards the lower-left corner of your Android Studio window will display Logcat
when tapped:
Figure 40: Android Studio Logcat Tool
Logcat is explained in greater detail a bit later in this book.
Accessing Android Tools
Not everything related to Android is directly part of Android Studio itself. In some
cases, tools need to be shared between users of Android Studio, users of Eclipse, and
62
GETTING AROUND ANDROID STUDIO
users of “none of the above”. In some cases, while the long term direction may be to
incorporate the tools’ functionality directly into Android Studio, that work simply
has not been completed to date.
Here are some noteworthy Android-related tools that you can access via the Tools >
Android main menu option.
SDK and AVD Managers
As we saw in Tutorial #1, the SDK Manager is Android’s tool for downloading pieces
of the Android SDK, including:
•
•
•
•
•
“SDK Platform” editions, allowing us to compile against a particular API level
ARM and (sometimes) x86 emulator images
Documentation
Updates to the core build tools
Etc.
You can launch the SDK Manager via Tools > Android > SDK Manager from the
Android Studio main menu, or by clicking on the “droid in a box” toolbar button:
Figure 41: Android Studio SDK Manager Toolbar Icon
The AVD Manager is the tool for creating emulators that emulate certain Android
environments, based upon API level, screen size, and other characteristics.
You can launch the AVD Manager via Tools > Android > AVD Manager from the
Android Studio main menu, or by clicking the “droid and a screen” toolbar button:
63
GETTING AROUND ANDROID STUDIO
Figure 42: Android Studio AVD Manager Toolbar Icon
Android Studio and Release Channels
When you install Android Studio for the first time, your installation will be set up to
get updates on the “stable” release channel. Here, a “release channel” is a specific set
of possible upgrades. The “stable” release channel means that you are getting full
production-ready updates. Android Studio will check for updates when launched,
and you can manually check for updates via the main menu (e.g., Help > Check for
Update… on Windows and Linux).
If an update is available, you will be presented with a dialog box showing you details
of the update:
Figure 43: Android Studio Update Dialog
Choosing “Release Notes” will bring up a Web page with release notes for the new
release. Clicking “Update and Restart” does pretty much what the button name
suggests: it downloads the update and restarts the IDE, applying the update along
the way.
64
GETTING AROUND ANDROID STUDIO
Clicking the “Updates” hyperlink in the dialog brings up yet another dialog, allowing
you to choose which release channel you want to subscribe to:
Figure 44: Android Studio Update Release Channel Dialog
You have four channels to choose from:
•
•
•
•
Stable, which is appropriate for most developers
Beta, which will get updates that are slightly ahead of stable
Dev, which is even more ahead than is the beta channel
Canary, which is updated very early (and the name, suggestive of a “canary in
a coal mine”, indicates that you are here to help debug the IDE)
Visit the Trails!
Android Studio’s Project Structure dialog and Translations Editor are covered later in
this book.
65
Contents of Android Projects
The Android build system is organized around a specific directory tree structure for
your Android project, much like any other Java project. The specifics, though, are
fairly unique to Android — the Android build tools do a few extra things to prepare
the actual application that will run on the device or emulator.
Here is a quick primer on the project structure, to help you make sense of it all,
particularly for the sample code referenced in this book.
What You Get, In General
The details of exactly what files are in your project depend on a variety of things:
• What IDE and version the project was used to create the project
• What project template was used to create the project
• What other changes have been made to the project after it was created
However, usually, there are many elements in common.
The Modules
A default Android Studio project will have an app/ directory off of the project root
directory (i.e., the directory in which you told Android Studio to create the project).
That app/ directory represents what Android Studio refers to as a module. Most
projects just have this one app/ module, though you can have more than one
module if needed.
67
CONTENTS OF ANDROID PROJECTS
The Source Sets
Inside of app/ you will find a src/main/ directory. This represents the main source
set, and it contains all of the “source” that your project is contributing to build the
application. Here, “source” means more than just programming language source
code (e.g., Java). It also includes other types of files, such as resources and the
manifest, that contribute to the app.
The Manifest
Inside of app/src/main/, you will find a file named AndroidManifest.xml.
AndroidManifest.xml is an XML file describing the application being built and what
components — activities, services, etc. — are being supplied by that application. You
can think of it as being the “table of contents” of what your application is about,
much as a book has a “table of contents” listing the various parts, chapters, and
appendices that appear in the book.
We will examine the manifest a bit more closely starting in the next chapter.
The Java
When you created the project, if you had Android Studio create an activity for you,
you supplied the class name of the “main” activity for the application (e.g.,
MainActivity). That will be combined with the package name that you provided for
the project to determine the fully-qualified class name for this activity (e.g.,
com.commonsware.android.MainActivity).
You will find that your project’s Java source tree already has the package’s directory
tree in place, plus a class representing your requested activity (e.g., com/
commonsware/android/MainActivity.java). This will be inside the main source set,
so the full path from the project root would be something like app/src/main/java/
com/commonsware/android/MainActivity.java.
You are welcome to modify this file and add Java classes as needed to implement
your application, and we will demonstrate that countless times as we progress
through this book.
Elsewhere — in directories that you normally do not work with — the Android build
tools will also be code-generating some source code for you each time you build
your app. One of the code-generated Java classes (R.java) will be important for
68
CONTENTS OF ANDROID PROJECTS
controlling our user interfaces from our own Java code, and we will see many
references to this R class as we start building applications in earnest.
The Resources
You will also find that your project has a res/ directory tree inside of the main
source set. This holds “resources” — static files that are packaged along with your
application, either in their original form or, occasionally, in a preprocessed form.
Some of the subdirectories you will find or create under res/ include:
1. res/drawable/ and res/mipmap-*/ (for a few values of *) for images (PNG,
JPEG, etc.)
2. res/layout/ for XML-based UI layout specifications
3. res/menu/ for XML-based menu specifications
4. res/raw/ for general-purpose files (e.g., an audio clip, a CSV file of account
information)
5. res/values/ for strings, dimensions, and the like
6. res/xml/ for other general-purpose XML files you wish to ship
Some of the directory names may have suffixes, like res/mipmap-hdpi/. This
indicates that the directory of resources should only be used in certain
circumstances — in this case, the mipmap resources are designed for devices with
high-density screens.
We will cover all of these, and more, later in this book.
The Build Instructions
The IDE needs to know how to take all of this stuff and come up with an Android
APK file. Some of this is already “known” to the IDE based upon how the IDE was
written. But some details are things that you may need to configure from time to
time, and so those details are stored in files that you will edit, by one means or
another, from your IDE.
In Android Studio, most of this knowledge is kept in files named build.gradle.
These are for a build engine known as Gradle, that Android Studio uses to build
APKs and other Android outputs.
69
CONTENTS OF ANDROID PROJECTS
More About the Directory Structure
All of those items are stored in a particular directory structure in an Android Studio
project… at least by default. Android Studio and Gradle are powerful and can be
configured to handle other structures, though most projects stick with the standard
setup.
The Root Directory
In the root directory of your project, the most important item is the app/ directory
representing your application module. We will look at that more in the next section.
Beyond the app/ directory, the other noteworthy files in the root of your project
include:
• build.gradle, which is part of the build instructions for your project, as is
described above
• Various other Gradle-related files (settings.gradle, gradle.properties,
gradlew, gradlew.bat, and so forth)
• local.properties, which indicates where your Android SDK tools reside
• An .iml file, where Android Studio holds some additional metadata about
your project
• A .gitignore file, representing standard rules for what should and should
not go into version control, particularly with respect to the Git version
control system
Eventually, you will have:
• A build/ directory, containing the compiled output of your app, plus various
reports and other files related to the build process and app testing
• A .gradle/ directory, containing Gradle executable code
• An .idea/ directory — this, along with the .iml file, represents data needed
by IntelliJ IDEA, on which Android Studio is based
The App Directory
The app/ directory, and its contents, are where you will spend most of your time as a
developer. Only infrequently do you need to manipulate the files in the project root.
70
CONTENTS OF ANDROID PROJECTS
The most important thing in the app/ directory is the src/ directory, which is the
root of your project’s source sets. We will explore those more in the next section.
Beyond the src/ directory, there are a few other items of note in app/:
• A build/ directory, which will hold the outputs of building your app,
including your APK file
• A build.gradle file, where most of your project-specific Gradle
configuration will go, to teach Android Studio how to build your app
• An app.iml file, containing more Android Studio metadata
• Another .gitignore file, for overrides to the Git version control rules from
the .gitignore file in the project root
• proguard-rules.pro, which are rules for a tool called ProGuard, which helps
reduce the size of your app
The Source Sets
Source sets are where the “source” of your project is organized. As noted earlier,
“source” not only refers to programming language source code (e.g., Java), but other
types of inputs to the build, such as your resources.
The source set that you will spend most of your time in is main/. You may also have
stub source sets named androidTest and test, for use in testing your app, as will be
covered later in the book.
Inside of a source set, common items include:
• Java code, in a java/ directory
• Resources, in a res/ directory
• Assets, in an assets/ directory, representing other static files you wish
packaged with the application for deployment onto the device
• Your AndroidManifest.xml file
71
CONTENTS OF ANDROID PROJECTS
Figure 45: Android Studio Project Explorer, Showing EmPubLite
Some projects will have additional items, usually tied to specific add-on tools that
the project happens to employ.
What You Get Out Of It
As part of running your app on a device or emulator, the IDE will generate an APK
file. You will find this in the build/outputs/apk directory of your module’s
directory, (e.g., app/build/outputs/apk for a traditional Android Studio project).
The APK file is a ZIP archive containing your compiled Java classes along with
packaged versions of the rest of your source (e.g., resources, manifest). The APK is
what gets distributed to your users, whether through an app distribution service like
Google’s Play Store or through other means.
72
Introducing Gradle and the Manifest
In the discussion of Android Studio, this book has mentioned something called
“Gradle”, without a lot of explanation.
In this chapter, the mysteries of Gradle will be revealed to you.
(well, OK, some of the mysteries…)
We also mentioned in passing in the previous chapter the concept of the “manifest”
— AndroidManifest.xml — as being a special file in our Android projects.
On the one hand, Gradle and the manifest are not strictly related. On the other
hand, some (but far from all) of the things that we can set up in the manifest can be
overridden in Gradle.
So, in this chapter, we will review both what Gradle is, what the manifest is, what
each of their roles are, and the basics of how they tie together.
Gradle: The Big Questions
First, let us “set the stage” by examining what this is all about, through a series of
fictionally-asked questions (FAQs).
What is Gradle?
Gradle is software for building software, otherwise known as “build automation
software” or “build systems”. You may have used other build systems before in other
environments, such as make (C/C++), rake (Ruby), Ant (Java), Maven (Java), etc.
73
INTRODUCING GRADLE AND THE MANIFEST
These tools know — via intrinsic capabilities and rules that you teach them — how
to determine what needs to be created (e.g., based on file changes) and how to
create them. A build system does not compile, link, package, etc. applications
directly, but instead directs separate compilers, linkers, and packagers to do that
work.
Gradle uses a domain-specific language (DSL) built on top of Groovy to accomplish
these tasks.
What is Groovy?
There are many programming languages that are designed to run on top of the Java
VM. Some of these, like JRuby and Jython, are implementations of other common
programming languages (Ruby and Python, respectively). Other languages are
unique, and Groovy is one of those.
Groovy scripts look a bit like a mashup of Java and Ruby. As with Java, Groovy
supports:
•
•
•
•
•
Defining classes with the class keyword
Creating subclasses using extends
Importing classes from external JARs using import
Defining method bodies using braces ({ and })
Objects are created via the new operator
As with Ruby, though:
• Statements can be part of a class, or simply written in an imperative style,
like a scripting language
• Parameters and local variables are not typed
• Values can be automatically patched into strings, though using slightly
different syntax ("Hello, $name" for Groovy instead of "Hello, #{name}"
for Ruby)
Groovy is an interpreted language, like Ruby and unlike Java. Groovy scripts are run
by executing a groovy command, passing it the script to run. The Groovy runtime,
though, is a Java JAR and requires a JVM in order to operate.
One of Groovy’s strengths is in creating a domain-specific language (or DSL).
Gradle, for example, is a Groovy DSL for doing software builds. Gradle-specific
capabilities appear to be first-class language constructs, generally indistinguishable
74
INTRODUCING GRADLE AND THE MANIFEST
from capabilities intrinsic to Groovy. Yet, the Groovy DSL is largely declarative, like
an XML file.
To some extent, we get the best of both worlds: XML-style definitions (generally
with less punctuation), yet with the ability to “reach into Groovy” and do custom
scripting as needed.
What Does Android Have To Do with Gradle?
Google has published the Android Gradle Plugin, which gives Gradle the ability to
build Android projects. Google is also using Gradle and the Android Gradle Plugin
as the build system behind Android Studio.
Obtaining Gradle
As with any build system, to use it, you need the build system’s engine itself.
If you will only be using Gradle in the context of Android Studio, the IDE will take
care of getting Gradle for you. If, however, you are planning on using Gradle outside
of Android Studio (e.g., command-line builds), you will want to consider where your
Gradle is coming from. This is particularly important for situations where you want
to build the app with no IDE in sight, such as using a continuous integration (CI)
server, like Jenkins.
Also, the way that Android Studio works with Gradle — called the Gradle Wrapper –
opens up security issues for your development machine, if you are the sort to
download open source projects from places like GitHub and try using them.
Direct Installation
What most developers looking to use Gradle outside of Android Studio will wind up
doing is installing Gradle directly.
The Gradle download page contains links to ZIP archives for Gradle itself: binaries,
source code, or both.
You can unZIP this archive to your desired location on your development machine.
75
INTRODUCING GRADLE AND THE MANIFEST
Linux Packages
You may be able to obtain Gradle via a package manager on Linux environments. For
example, there is an Ubuntu PPA for Gradle.
The gradlew Wrapper
If you are starting from a project that somebody else has published, you may find a
gradlew and gradlew.bat file in the project root, along with a gradle/ directory.
This represents the “Gradle Wrapper”.
The Gradle Wrapper consists of three pieces:
• the batch file (gradlew.bat) or shell script (gradlew)
• the JAR file used by the batch file and shell script (in the gradle/wrapper/
directory)
• the gradle-wrapper.properties file (also in the gradle/wrapper/ directory)
Android Studio uses the gradle-wrapper.properties file to determine where to
download Gradle from, for use in your project, from the distributionUrl property
in that file:
#Sun Nov 05 06:56:08 EST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\:
\://services.gradle.org/distributions/gradle-4.1-all.zip
(from Basic/Button/gradle/wrapper/gradle-wrapper.properties)
When you create or import a project, or if you change the version of Gradle
referenced in the properties file, Android Studio will download the Gradle pointed
to by the distributionUrl property and install it to a .gradle/ directory (note the
leading .) in your project. That version of Gradle will be what Android Studio uses.
RULE #1: Only use a distributionUrl that you trust.
If you are importing an Android project from a third party — such as the samples for
this book — and they contain the gradle/wrapper/gradle-wrapper.properties
file, examine it to see where the distributionUrl is pointing to. If it is loading from
services.gradle.org, or from an internal enterprise server, it is probably
76
INTRODUCING GRADLE AND THE MANIFEST
trustworthy. If it is pointing to a URL located somewhere else, consider whether you
really want to use that version of Gradle, considering that it may have been
tampered with.
The batch file, shell script, and JAR file are there to support command-line builds. If
you run the gradlew command, it will use a local copy of Gradle installed in
.gradle/ in the project. If there is no such copy of Gradle, gradlew will download
Gradle from the distributionUrl, as does Android Studio. Note that Android
Studio does not use gradlew for this role — that logic is built into Android Studio
itself.
RULE #2: Only use a gradlew that you REALLY trust.
It is relatively easy to examine a .properties file to check a URL to see if it seems
valid. Making sense of a batch file or shell script can be cumbersome. Decompiling a
JAR file and making sense of it can be rather difficult. Yet, if you use gradlew that
you obtained from somebody, that script and JAR are running on your development
machine, as is the copy of Gradle that they install. If that code was tampered with,
the malware has complete access to your development machine and anything that it
can reach, such as servers within your organization.
Note that you do not have to use the Gradle Wrapper at all. If you would rather not
worry about it, install a version of Gradle on your development machine yourself
and remove the Gradle Wrapper files. You can use the gradle command to build
your app (if your Gradle’s bin/ directory is in your PATH), and Android Studio will
use your Gradle installation (if you teach it where to find it, such as via the
GRADLE_HOME environment variable).
Versions of Gradle and the Android Gradle Plugin
The Android Gradle Plugin that we will use to give Gradle “super Android powers!” is
updated periodically. Each update has its corresponding required version of Gradle.
Google maintains a page listing the Gradle versions supported by each Android
Gradle Plugin version
If you are using the Gradle Wrapper, you are using an installation of Gradle that is
local to the project. So long as the version of Gradle in the project matches the
version of the Android Gradle Plugin requested in the project’s build.gradle file —
as will be covered later in this chapter — you should be in fine shape.
77
INTRODUCING GRADLE AND THE MANIFEST
If you are not using the Gradle Wrapper, you will need to decide when to take on a
new Android Gradle Plugin release and plan to update your Gradle installation and
build.gradle files in tandem at that point.
Gradle Environment Variables
If you installed Gradle yourself, you will want to define a GRADLE_HOME environment
variable, pointing to where you installed Gradle, and to add the bin/ directory inside
of Gradle to your PATH environment variable.
You may also consider setting up a GRADLE_USER_HOME environment variable,
pointing to a directory in which Gradle can create a .gradle/ subdirectory, for peruser caches and related materials. By default, Gradle will use your standard home
directory.
Examining the Gradle Files
An Android Studio project usually has two build.gradle files, one at the project
level and one at the “module” level (e.g., in the app/ directory).
The Project-Level File
The build.gradle file in the project directory controls the Gradle configuration for
all modules in your project. Right now, most likely you only have one module, and
many apps only ever use one module. However, it is possible for you to add other
modules to this project, and we will explore reasons for doing so later in this book.
Here is a typical top-level build.gradle file:
// Top-level build file where you can add configuration options common to all
sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
78
INTRODUCING GRADLE AND THE MANIFEST
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
buildscript
In Groovy terms, a “closure” is a block of code wrapped in braces ({ }).
The buildscript closure in Gradle is where you configure the JARs and such that
Gradle itself will use for interpreting the rest of the file. Hence, here you are not
configuring your project so much as you are configuring the build itself.
The repositories closure inside the buildscript closure indicates where plugins
can come from. Here, jcenter() is a built-in method that teaches Gradle about
JCenter, a popular location for obtaining open source libraries. Similarly, google() is
a built-in method that teaches Gradle about a site where it can download plugins
from Google.
The dependencies closure indicates what is required to be able to run the rest of the
build script. classpath 'com.android.tools.build:gradle:3.0.0' is not especially
well-documented by the Gradle team. However the
'com.android.tools.build:gradle:3.0.0' portion means:
• Find the com.android.tools.build group of plugins
• Find the gradle artifact within that group
• Ensure that we have version 3.0.0 of the plugin
The first time you run your build, with the buildscript closure as shown above,
Gradle will notice that you do not have this dependency. It will then download that
artifact from Google, as Google serves up its plugin from its own site nowadays.
79
INTRODUCING GRADLE AND THE MANIFEST
Sometimes, the last segment of the version is replaced with a + sign (e.g., 3.0.+).
This tells Gradle to download the latest version, thereby automatically upgrading
you to the latest patch-level (e.g., 3.0.1 at some point).
allprojects
The allprojects closure says “apply these settings to all modules in this project”.
Here, we are setting up jcenter() and google() as places to find libraries used in
any of the modules in our project. We will use lots of libraries in our projects —
having these “repositories” set up in allprojects makes it simpler for us to request
them.
The Module-Level Gradle File
In your app/ module, you will also find a build.gradle file. This has settings unique
for this module, independent of any other module that your project may have in the
future.
Here is a typical module-level build.gradle file:
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.commonsware.myapplication"
minSdkVersion 21
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
80
INTRODUCING GRADLE AND THE MANIFEST
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
For now, let’s focus on some key elements of this file.
dependencies
This build.gradle file also has a dependencies closure. Whereas the dependencies
closure in the buildscript closure in the top-level build.gradle file is for libraries
used by the build process, the dependencies closure in the module’s build.gradle
file is for libraries used by your code in that module. We will get into the concept of
these libraries later in the book.
android
The android closure contains all of the Android-specific configuration information.
This closure is what the Android plugin enables, where the plugin itself comes from
the apply plugin: 'com.android.application' line at the top, coupled with the
classpath line from the project-level build.gradle file.
But before we get into what is in this closure, we should “switch gears” and talk
about the manifest file, as what goes in the android closure is related to what goes in
the manifest file.
Introducing the Manifest
The foundation for any Android application is the manifest file:
AndroidManifest.xml. This will be in your app module’s src/main/ directory (the
main source set) for typical Android Studio projects.
Here is where you declare what is inside your application — the activities, the
services, and so on. You also indicate how these pieces attach themselves to the
overall Android system; for example, you indicate which activity (or activities)
should appear on the device’s main menu (a.k.a., launcher).
When you create your application, you will get a starter manifest generated for you.
For a simple application, offering a single activity and nothing else, the autogenerated manifest will probably work out fine, or perhaps require a few minor
81
INTRODUCING GRADLE AND THE MANIFEST
modifications. On the other end of the spectrum, the manifest file for the Android
API demo suite is over 1,000 lines long. Your production Android applications will
probably fall somewhere in the middle.
As mentioned previously, some items can be defined in both the manifest and in a
build.gradle file. The approach of putting that stuff in the manifest still works. For
Android Studio users, you will probably use the Gradle file and not have those
common elements be defined in the manifest.
Things In Common Between the Manifest and
Gradle
There are a few key items that can be defined in the manifest and can be overridden
in build.gradle statements. These items are fairly important to the development
and operation of our Android apps as well.
Package Name and Application ID
The root of all manifest files is, not surprisingly, a manifest element:
>
Note the android namespace declaration. You will only use the namespace on many
of the attributes, not the elements (e.g., , not ).
The biggest piece of information you need to supply on the element is
the package attribute.
The package attribute will always need to be in the manifest, even for Android
Studio projects. The package attribute will control where some source code is
generated for us, notably some R and BuildConfig classes that we will encounter
later in the book.
Since the package value is used for Java code generation, it has to be a valid Java
package name. Java convention says that the package name should be based on a
reverse domain name (e.g., com.commonsware.myapplication), where you own the
domain in question. That way, it is unlikely that anyone else will accidentally collide
with the same name.
82
INTRODUCING GRADLE AND THE MANIFEST
The package also serves as our app’s default “application ID”. This needs to be a
unique identifier, such that:
• no two apps can be installed on the same device at the same time with the
same application ID
• no two apps can be uploaded to the Play Store with the same application ID
(and other distribution channels may have the same limitation)
By default, the application ID is the package value, but Android Studio users can
override it in their Gradle build files. Specifically, inside of the android closure can
be a defaultConfig closure, and inside of there can be an applicationId statement:
android {
// other stuff
defaultConfig {
applicationId "com.commonsware.myapplication"
// more other stuff
}
}
Not only can Android Studio users override the application ID in the defaultConfig
closure, but there are ways of having different application ID values for different
scenarios, such as a debug build versus a release build. We will explore that more
later in the book.
minSdkVersion and targetSdkVersion
Your defaultConfig closure inside the android closure in your module’s
build.gradle file has a pair of properties named minSdkVersion and
targetSdkVersion. Technically, these override values that could be defined via a
element in the manifest, though few projects will have such an element
nowadays.
Of the two, the more critical one is minSdkVersion. This indicates what is the oldest
version of Android you are testing with your application. The value of the attribute
is an integer representing the Android API level. So, if you are only testing your
application on Android 4.1 and newer versions of Android, you would set your
minSdkVersion to be 16. The initial value is what you requested when you had
Android Studio create the project.
83
INTRODUCING GRADLE AND THE MANIFEST
You can also specify a targetSdkVersion. This indicates what version of Android
you are thinking of as you are writing your code. If your application is run on a
newer version of Android, Android may do some things to try to improve
compatibility of your code with respect to changes made in the newer Android.
Nowadays, most Android developers should specify a target SDK version of 15 or
higher. We will start to explore more about the targetSdkVersion as we get deeper
into the book; for the moment, whatever your IDE gives you as a default value is
probably a fine starting point.
Version Code and Version Name
Similarly, the defaultConfig closure has versionCode and versionName properties.
In principle, these override android:versionName and android:versionCode
attributes on the root element in the manifest, though you will not find
many projects using those XML attributes.
These two values represent the versions of your application. The versionName value
is what the user will see for a version indicator in the Applications details screen for
your app in their Settings application. Also, the version name is used by the Play
Store listing, if you are distributing your application that way. The version name can
be any string value you want.
The versionCode, on the other hand, must be an integer, and newer versions must
have higher version codes than do older versions. Android and the Play Store will
compare the version code of a new APK to the version code of an installed
application to determine if the new APK is indeed an update. The typical approach
is to start the version code at 1 and increment it with each production release of
your application, though you can choose another convention if you wish. During
development, you can leave these alone, but when you move to production, these
attributes will matter greatly.
Other Gradle Items of Note
The android closure has a compileSdkVersion property. compileSdkVersion
specifies the API level to be compiled against, usually as a simple API level integer
(e.g., 19). This indicates what Java classes, methods, and so on are available to you
when you write your app. Typically, you set this to be the latest production release of
Android, using the values noted earlier in the book.
84
INTRODUCING GRADLE AND THE MANIFEST
The android closure may have a buildToolsVersion property. buildToolsVersion
indicates the version of the Android SDK build tools that you wish to use with this
project. The Android Gradle Plugin really is a thin wrapper around a series of “build
tools” that handle most of the work of creating an APK out of your project. If your
android closure does not have buildToolsVersion, the Android Gradle Plugin will
use its own default version of these build tools, and for many projects this will
suffice. In this book, most projects will state their buildToolsVersion, though some
will skip that line and use the plugin-provided default.
Where’s the GUI?
You might wonder why we have to slog through all of this Groovy code and wonder
if there is some GUI for affecting Gradle settings.
The answer is yes… and no.
There is the project structure dialog, that allows you to maintain some of this stuff.
And you are welcome to try it. However, the more complex your build becomes, the
more likely it is that the GUI will not suffice, and you will need to work with the
Gradle build files more directly. Hence, this book will tend to focus on the build
files.
The Rest of the Manifest
Not everything in the manifest can be overridden in the Gradle build files. Here are a
few key items that will always be defined in the manifest, not in a build.gradle file.
An Application For Your Application
In your initial project’s manifest, the primary child of the element is an
element.
By default, when you create a new Android project, you get a single
element inside the element:
>
>
>
The element supplies android:name for the class implementing the
activity, android:label for the display name of the activity, and (sometimes) an
child element describing under what conditions this activity will
be displayed. The stock element sets up your activity to appear in the
launcher, so users can choose to run it. As we’ll see later in this book, you can have
several activities in one project, if you so choose.
The android:name attribute, in this case, has a bare Java class name (MainActivity).
Sometimes, you will see android:name with a fully-qualified class name (e.g.,
com.commonsware.myapplication.MainActivity). Sometimes, you will see a Java
class name with a single dot as a prefix (e.g., .MainActivity). Both MainActivity
and .MainActivity refer to a Java class that will be in your project’s package — the
one you declared in the package attribute of the element.
Supporting Multiple Screens
Android devices come with a wide range of screen sizes, from 2.8” tiny smartphones
to 46” TVs. Android divides these into four buckets, based on physical size and the
distance at which they are usually viewed:
1.
2.
3.
4.
Small (under 3”)
Normal (3” to around 4.5”)
Large (4.5” to around 10”)
Extra-large (over 10”)
86
INTRODUCING GRADLE AND THE MANIFEST
By default, your application will support small and normal screens. It also will
support large and extra-large screens via some automated conversion code built into
Android.
To truly support all the screen sizes you want, you should consider adding a
element to your manifest. This enumerates the screen sizes you
have explicit support for. For example, if you are providing custom UI support for
large or extra-large screens, you will want to have the element.
So, while the starting manifest file works, handling multiple screen sizes is
something you will want to think about.
You wind up with an element akin to:
Much more information about providing solid support for all screen sizes, including
samples of the element, will be found later in this book as we
cover large-screen strategies.
Other Stuff
As we proceed through the book, you will find other elements being added to the
manifest, such as:
• , to tell the user that you need permission to use certain
device capabilities, such as accessing the Internet
• , to tell Android that you need the device to have certain
features (e.g., a camera), and therefore your app should not be installed on
devices lacking such features
• , for bits of information needed by particular extensions to
Android, such as by FileProvider.
These and other elements will be introduced elsewhere in the book.
87
INTRODUCING GRADLE AND THE MANIFEST
Learning More About Gradle
This book will go into more about Gradle, both in the core chapters and in the trails.
But, the focus will be on the Android Gradle Plugin, and Gradle itself offers a lot
more than that. The Gradle Web site hosts documentation, links to Gradle-specific
books, and links to other Gradle educational resources.
Visit the Trails!
There are a few more chapters in this book getting into more details about the use of
Gradle and the Android Gradle Plugin.
• Gradle and Tasks explains how we ask Gradle to do things on our behalf
(“tasks”), such as compile our APK for us
• Gradle and Build Variants gets into what capabilities we get from the Gradle
project structure, including the ability to configure “build types” and
“product flavors”
There is also the “Advanced Gradle for Android Tips” chapter for other Gradle topics,
and the chapter on manifest merging in Gradle.
88
Tutorial #3 - Manifest Changes
As we build EmPubLite, we will need to make a number of changes to our project’s
manifest. In this tutorial, we will take care of a couple of these changes, to show you
how to manipulate the AndroidManifest.xml file. Future tutorials will make yet
more changes.
Android Studio users will also get their first chance to work with the build.gradle
file.
This is a continuation of the work we did in the previous tutorial.
You can find the results of the previous tutorial and the results of this tutorial in the
book’s GitHub repository.
Some Notes About Relative Paths
In these tutorials, you will see references to relative paths, like
AndroidManifest.xml, res/layout/, and so on.
You should interpret these paths as being relative to the app/src/main/ directory
within the project, except as otherwise noted. So, for example, Step #1 below will ask
you to open AndroidManifest.xml — that file can be found in app/src/main/
AndroidManifest.xml from the project root.
Step #1: Supporting Screens
Our application will restrict its supported screen sizes. Tablets make for ideal ebook
readers. Phones can also be used, but the smaller the phone, the more difficult it
89
TUTORIAL #3 - MANIFEST CHANGES
will be to come up with a UI that will let the user do everything that is needed, yet
still have room for more than a sentence or two of the book at a time.
We will get into screen size strategies and their details later in this book. For the
moment, though, we will add a element to keep our
application off “small” screen devices (under 3” diagonal size).
Android Studio users can double-click on AndroidManifest.xml in the project
explorer.
As a child of the root element, add a element as
follows:
/>
Step #2: Blocking Backups
If you look at the element, you will see that it has a few attributes,
including android:allowBackup="true". This attribute indicates that EmPubLite
should participate in Android’s automatic backup system.
That is not a good idea, until you understand the technical and legal ramifications of
that choice, which we will explore much later in this book.
In the short term, change android:allowBackup to be false.
Step #3: Ignoring Lint
Even after that change, the application element name may have a beige
background. If you hover your mouse over it and look at the explanatory tooltip, you
will see that it is complaining that this app is not indexable, and that you should add
an ACTION_VIEW activity to the app.
This is ridiculous. This app (hopefully) will never wind up on the Play Store, and so
Google’s “app indexing” capability will never be relevant.
90
TUTORIAL #3 - MANIFEST CHANGES
Put your text cursor somewhere inside the application element name and press
Alt-Enter (or Option-Return on macOS). This should bring up a popup
window showing some “quick fixes” for the problem:
Figure 46: Quick Fixes
Choose the “suppress” option. Then, press Ctrl-Alt-L (or Command-Option-L
on macOS) to reformat the file. You will wind up with something like:
>
>
>
91
TUTORIAL #3 - MANIFEST CHANGES
(from EmPubLite-AndroidStudio/T3-Manifest/EmPubLite/app/src/main/AndroidManifest.xml)
The element now has a tools:ignore="GoogleAppIndexingWarning"
attribute, and the root element defines the tools XML namespace. The
net effect is that we are telling the build tools — specifically the Lint utility – that it
should ignore this particular issue.
In Our Next Episode…
… we will make some changes to the resources of our tutorial project
92
Some Words About Resources
It is quite likely that by this point in time, you are “chomping at the bit” to get into
actually writing some code. This is understandable. That being said, before we dive
into the Java source code for our stub project, we really should chat briefly about
resources.
Resources are static bits of information held outside the Java source code. As we
discussed previously, resources are stored as files under the res/ directory in your
source set (e.g., app/src/main/res/). Here is where you will find all your icons and
other images, your externalized strings for internationalization, and more.
These are separate from the Java source code not only because they are different in
format. They are separate because you can have multiple definitions of a resource, to
use in different circumstances. For example, with internationalization, you will have
strings for different languages. Your Java code will be able to remain largely oblivious
to this, as Android will choose the right resource to use, from all candidates, in a
given circumstance (e.g., choose the Spanish string if the device’s locale is set to
Spanish).
We will cover all the details of these resource sets later in the book. Right now, we
need to discuss the resources in use by our stub project, plus one more.
This chapter will refer to the res/ directory as a shorthand for the app/src/main/
res/ directory of the project.
String Theory
Keeping your labels and other bits of text outside the main source code of your
application is generally considered to be a very good idea. In particular, it helps with
93
SOME WORDS ABOUT RESOURCES
internationalization (I18N) and localization (L10N). Even if you are not going to
translate your strings to other languages, it is easier to make corrections if all the
strings are in one spot instead of scattered throughout your source code.
Plain Strings
Generally speaking, all you need to do is have an XML file in the res/values
directory (typically named res/values/strings.xml), with a resources root
element, and one child string element for each string you wish to encode as a
resource. The string element takes a name attribute, which is the unique name for
this string, and a single text element containing the text of the string:
>The quick brown fox...
>He who laughs last...
One tricky part is if the string value contains a quote or an apostrophe. In those
cases, you will want to escape those values, by preceding them with a backslash (e.g.,
These are the times that try men\'s souls). Or, if it is just an apostrophe, you
could enclose the value in quotes (e.g., "These are the times that try men's
souls.").
For example, a project’s strings.xml file could look like this:
>EmPubLite
(from EmPubLite-AndroidStudio/T3-Manifest/EmPubLite/app/src/main/res/values/strings.xml)
We can reference these string resources from various locations, in our Java source
code and elsewhere. For example, the app_name string resource often is used in the
AndroidManifest.xml file:
>
>
>
(from EmPubLite-AndroidStudio/T3-Manifest/EmPubLite/app/src/main/AndroidManifest.xml)
Here, the android:label attribute of the element refers to the
app_name string resource. This will appear in a few places in the application, notably
in the list of installed applications in Settings. So, if you wish to change how your
application’s name appears in these places, simply adjust the app_name string
resource to suit.
The syntax @string/app_name tells Android “find the string resource named
app_name”. This causes Android to scan the appropriate strings.xml file (or any
other file containing string resources in your res/values/ directory) to try to find
app_name.
Um, Wait, My Manifest Does Not Look Like That
When you view a manifest like that in Android Studio, it may appear as though you
are not using resources, as you may not see @string/... references:
95
SOME WORDS ABOUT RESOURCES
Figure 47: AndroidManifest.xml, As Initially Viewed in Android Studio
Here, android:label looks as though it is the hard-coded value “EmPubLite”.
However, notice that the attribute value is formatted differently than the others. The
rest are green text with a white background, while this one is gray text with a shaded
background.
That is because Android Studio is lying to you.
If you hover your mouse over the value, you will see the real attribute appear just
below it:
96
SOME WORDS ABOUT RESOURCES
Figure 48: AndroidManifest.xml, With Mouse Hovering Over “EmPubLite”
And, if you click on the fake value, you will see the real XML, with the real string
resource value.
What is happening is that Android Studio, by default, will substitute a candidate
value for the resource in its presentation of the manifest, other resources that refer
to resources, and even Java code. Any time you see that gray-on-light-blue
formatting, remember that this is not the real value, and that you have to uncover
the real value via hovering over it or clicking on it.
Styled Text
Many things in Android can display rich text, where the text has been formatted
using some lightweight HTML markup: , , and . Your string resources
support this, simply by using the HTML tags as you would in a Web page:
>This has
bold
in it.
>Whereas this has
italics
!
97
SOME WORDS ABOUT RESOURCES
CDATA. CDATA Run. Run, DATA, Run.
Since a strings resource XML file is an XML file, if your message contains <, >, or &
characters (other than the formatting tags listed above), you will need to use a CDATA
section:
>
TPS Report for: {{reportDate}}
Here are the contents of the TPS report:
{{message}}
If you have any questions regarding this report, please
do
not
ask Mark Murphy.