Table of ContentsLearning Android ........................................................................................................... xixPrerequisites .......................................................................................................... xixWhat’s New in the Third Edition? ............................................................................. xixHow to Use This Book ............................................................................................. xxHow This Book Is Organized .................................................................................... xxChallenges ..................................................................................................... xxiAre you more curious? .................................................................................... xxiCode Style ............................................................................................................. xxiTypographical Conventions ...................................................................................... xxiiAndroid Versions ................................................................................................... xxiiThe Necessary Tools ..................................................................................................... xxiiiDownloading and Installing Android Studio .............................................................. xxiiiDownloading Earlier SDK Versions ......................................................................... xxiiiA Hardware Device ............................................................................................... xxiv1. Your First Android Application ........................................................................................ 1App Basics ............................................................................................................... 2Creating an Android Project ........................................................................................ 3Navigating in Android Studio ...................................................................................... 8Laying Out the UI ..................................................................................................... 9The view hierarchy .......................................................................................... 13Widget attributes ............................................................................................. 14Creating string resources ................................................................................... 15Previewing the layout ....................................................................................... 16From Layout XML to View Objects ........................................................................... 17Resources and resource IDs ............................................................................... 18Wiring Up Widgets .................................................................................................. 21Getting references to widgets ............................................................................. 22Setting listeners ............................................................................................... 23Making Toasts ......................................................................................................... 25Using code completion ..................................................................................... 26Running on the Emulator .......................................................................................... 27For the More Curious: Android Build Process .............................................................. 30Android build tools .......................................................................................... 31Challenges .............................................................................................................. 32Challenge: Customizing tAndroid ProgrammingviiiAdding an Icon ....................................................................................................... 48Adding resources to a project ............................................................................ 49Referencing resources in XML .......................................................................... 51Challenge: Add a Listener to the TextView .................................................................. 52Challenge: Add a Previous Button .............................................................................. 52Challenge: From Button to ImageButton ...................................................................... 533. The Activity Lifecycle .................................................................................................. 55Logging the Activity Lifecycle .................................................................................. 57Making log messages ....................................................................................... 57Using Logcat .................................................................................................. 59Exploring the activity lifecycle by example .......................................................... 60Rotation and the Activity Lifecycle ............................................................................ 63Device configurations and alternative resources ..................................................... 63Saving Data Across Rotation ..................................................................................... 68Overriding onSaveInstanceState(Bundle) .............................................................. 69The Activity Lifecycle, Revisited ............................................................................... 70For the More Curious: Current State of Activity Cleanup ................................................ 72For the More Curious: Log Levels and Methods ........................................................... 73Challenge: Preventing Repeat Answers ........................................................................ 74Challenge: Graded Quiz ............................................................................................ 744. Debugging Android Apps .............................................................................................. 75Exceptions and Stack Traces ..................................................................................... 76Diagnosing misbehaviors .................................................................................. 78Logging stack traces ........................................................................................ 78Setting breakpoints .......................................................................................... 80Using exception breakpoints .............................................................................. 83Android-Specific Debugging ...................................................................................... 85Using Android Lint .......................................................................................... 85Issues with the R class ..................................................................................... 87Challenge: Exploring the Layout Inspector ................................................................... 88Challenge: Exploring Allocation Tracking .................................................................... 895. Your Second Activity ................................................................................................... 91Setting Up a Second Activity .................................................................................... 93Creating a new activity ..................................................................................... 93A new activity subclass .................................................................................... 96Declaring activities in the manifest ..................................................................... 97Adding a cheat button to QuizActivity ................................................................ 98Starting an Activity .................................................................................................. 99Communicating with intents ............................................................................ 100Passing Data Between Activities ............................................................................... 101Using intent extras ......................................................................................... 102Getting a result back from a child activity .......................................................... 105How Android Sees Your Activities ............................................................................ 109Challenge: Closing Loopholes for Cheaters ................................................................ 1126. Android SDK Versions and Compatibility ....................................................................... 113Android SDK Versions ........................................................................................... 113Compatibility and Android Programming ................................................................... 114A sane minimum ........................................................................................... 114Android ProgrammingixMinimum SDK version ................................................................................... 117Target SDK version ........................................................................................ 117Compile SDK version ..................................................................................... 117Adding code from later APIs safely .................................................................. 118Using the Android Developer Documentation ............................................................. 120Challenge: Reporting the Build Version ..................................................................... 122Challenge: Limited Cheats ....................................................................................... 1227. UI Fragments and the Fragment Manager ....................................................................... 123The Need for UI Flexibility ..................................................................................... 124Introducing Fragments ............................................................................................ 125Starting CriminalIntent ............................................................................................ 126Creating a new project .................................................................................... 129Two types of fragments ................................................................................... 130Adding dependencies in Android Studio ............................................................ 131Creating the Crime class ................................................................................. 134Hosting a UI Fragment ........................................................................................... 136The fragment lifecycle .................................................................................... 136Two approaches to hosting .............................................................................. 137Defining a container view ............................................................................... 137Creating a UI Fragment .......................................................................................... 139Defining CrimeFragment’s layout ..................................................................... 139Creating the CrimeFragment class ..................................................................... 142Adding a UI Fragment to the FragmentManager .......................................................... 148Fragment transactions ..................................................................................... 149The FragmentManager and the fragment lifecycle ................................................ 152Application Architecture with Fragments ................................................................... 153The reason all our activities will use fragments ................................................... 154For the More Curious: Fragments and the Support Library ............................................ 155For the More Curious: Why Support Fragments Are Superior ........................................ 1568. Displaying Lists with RecyclerView .............................................................................. 157Updating CriminalIntent’s Model Layer ..................................................................... 159Singletons and centralized data storage .............................................................. 159An Abstract Activity for Hosting a Fragment .............................................................. 161A generic fragment-hosting layout .................................................................... 161An abstract Activity class ................................................................................ 162RecyclerView, Adapter, and ViewHolder .................................................................... 167ViewHolders and Adapters .............................................................................. 168Using a RecyclerView .................................................................................... 171A view to display .......................................................................................... 173Implementing a ViewHolder and an Adapter ....................................................... 173Binding List Items ................................................................................................. 176Responding to Presses ............................................................................................ 178For the More Curious: ListView and GridView ........................................................... 179For the More Curious: Singletons ............................................................................. 179Challenge: RecyclerView ViewTypes ......................................................................... 1809. Creating User Interfaces with Layouts and Widgets .......................................................... 181Using the Graphical Layout Tool .............................................................................. 182Introducing ConstraintLayout ................................................................................... 183Android ProgrammingxUsing ConstraintLayout .................................................................................. 184The graphical editor ....................................................................................... 186Making room ................................................................................................ 188Adding widgets ............................................................................................. 190ConstraintLayout’s inner workings .................................................................... 194Editing properties ........................................................................................... 195Making list items dynamic .............................................................................. 199More on Layout Attributes ...................................................................................... 200Screen pixel densities and dp and sp ................................................................. 200Margins vs padding ........................................................................................ 202Styles, themes, and theme attributes .................................................................. 203Android’s design guidelines ............................................................................. 204The Graphical Layout Tools and You ........................................................................ 204Challenge: Formatting the Date ................................................................................ 20410. Using Fragment Arguments ........................................................................................ 205Starting an Activity from a Fragment ........................................................................ 205Putting an extra ............................................................................................. 207Retrieving an extra ......................................................................................... 207Updating CrimeFragment’s view with Crime data ................................................ 208The downside to direct retrieval ........................................................................ 209Fragment Arguments .............................................................................................. 210Attaching arguments to a fragment .................................................................... 210Retrieving arguments ...................................................................................... 211Reloading the List .................................................................................................. 212Getting Results with Fragments ................................................................................ 215For the More Curious: Why Use Fragment Arguments? ................................................ 216Challenge: Efficient RecyclerView Reloading ............................................................. 216Challenge: Improving CrimeLab Performance ............................................................. 21611. Using ViewPager ...................................................................................................... 217Creating CrimePagerActivity .................................................................................... 219ViewPager and PagerAdapter ........................................................................... 219Integrating CrimePagerActivity ......................................................................... 221FragmentStatePagerAdapter vs FragmentPagerAdapter ................................................. 223For the More Curious: How ViewPager Really Works .................................................. 224For the More Curious: Laying Out Views in Code ....................................................... 225Challenge: Restoring CrimeFragment’s Margins .......................................................... 226Challenge: Adding First and Last Buttons .................................................................. 22612. Dialogs ................................................................................................................... 227Creating a DialogFragment ...................................................................................... 228Showing a DialogFragment .............................................................................. 231Setting a dialog’s contents ............................................................................... 232Passing Data Between Two Fragments ....................................................................... 235Passing data to DatePickerFragment .................................................................. 236Returning data to CrimeFragment ..................................................................... 238Challenge: More Dialogs ......................................................................................... 245Challenge: A Responsive DialogFragment .................................................................. 24513. The Toolbar ............................................................................................................. 247AppCompat ........................................................................................................... 248Android ProgrammingxiUsing the AppCompat library .......................................................................... 248Menus .................................................................................................................. 250Defining a menu in XML ................................................................................ 250Creating the menu .......................................................................................... 256Responding to menu selections ......................................................................... 259Enabling Hierarchical Navigation ............................................................................. 260How hierarchical navigation works ................................................................... 261An Alternative Action Item ..................................................................................... 262Toggling the action item title ........................................................................... 263“Just one more thing...” ................................................................................... 265For the More Curious: Action Bar vs Toolbar ............................................................. 267Challenge: Deleting Crimes ..................................................................................... 267Challenge: Plural String Resources ........................................................................... 268Challenge: An Empty View for the RecyclerView ........................................................ 26814. SQLite Databases ..................................................................................................... 269Defining a Schema ................................................................................................. 270Building Your Initial Database ................................................................................. 271Exploring files using Android Device Monitor .................................................... 274Debugging database issues .............................................................................. 276Gutting CrimeLab .................................................................................................. 277Writing to the Database .......................................................................................... 278Using ContentValues ...................................................................................... 278Inserting and updating rows ............................................................................. 279Reading from the Database ...................................................................................... 281Using a CursorWrapper .................................................................................. 282Converting to model objects ............................................................................ 284For the More Curious: More Databases ..................................................................... 287For the More Curious: The Application Context .......................................................... 288Challenge: Deleting Crimes ..................................................................................... 28815. Implicit Intents ......................................................................................................... 289Adding Buttons ..................................................................................................... 290Adding a Suspect to the Model Layer ....................................................................... 291Using a Format String ............................................................................................ 293Using Implicit Intents ............................................................................................. 294Parts of an implicit intent ................................................................................ 295Sending a crime report .................................................................................... 296Asking Android for a contact ........................................................................... 299Checking for responding activities .................................................................... 302Challenge: ShareCompat ......................................................................................... 304Challenge: Another Implicit Intent ............................................................................ 30416. Taking Pictures with Intents ....................................................................................... 305A Place for Your Photo ........................................................................................... 305File Storage .......................................................................................................... 308Using FileProvider ......................................................................................... 309Designating a picture location .......................................................................... 310Using a Camera Intent ............................................................................................ 311Firing the intent ............................................................................................. 311Scaling and Displaying Bitmaps ............................................................................... 313Android ProgrammingxiiDeclaring Features ................................................................................................. 316Challenge: Detail Display ........................................................................................ 316Challenge: Efficient Thumbnail Load ........................................................................ 31617. Two-Pane Master-Detail Interfaces ............................................................................... 317Adding Layout Flexibility ....................................................................................... 319Modifying SingleFragmentActivity ................................................................... 320Creating a layout with two fragment containers ................................................... 321Using an alias resource ................................................................................... 323Creating tablet alternatives ............................................................................... 324Activity: Fragment Boss .......................................................................................... 325Fragment callback interfaces ............................................................................ 326For the More Curious: More on Determining Device Size ............................................. 335Challenge: Adding Swipe to Dismiss ........................................................................ 33518. Localization ............................................................................................................. 337Localizing Resources .............................................................................................. 338Default resources ........................................................................................... 341Checking string coverage using Translations Editor .............................................. 344Targeting a region .......................................................................................... 345Configuration Qualifiers .......................................................................................... 348Prioritizing alternative resources ....................................................................... 349Multiple qualifiers .......................................................................................... 351Finding the best-matching resources .................................................................. 352Testing Alternative Resources .................................................................................. 353Challenge: Localizing Dates .................................................................................... 35419. Accessibility ............................................................................................................ 355TalkBack .............................................................................................................. 355Explore by Touch .......................................................................................... 359Linear navigation by swiping ........................................................................... 359Making Non-Text Elements Readable by TalkBack ...................................................... 362Adding content descriptions ............................................................................. 362Making a widget focusable .............................................................................. 364Creating a Comparable Experience ........................................................................... 365Using labels to provide context ........................................................................ 367For the More Curious: Using Accessibility Scanner ..................................................... 370Challenge: Improving the List .................................................................................. 373Challenge: Providing Enough Context for Data Entry ................................................... 373Challenge: Announcing Events ................................................................................. 37320. Data Binding and MVVM .......................................................................................... 375Different Architectures: Why Bother? ........................................................................ 376Creating BeatBox ................................................................................................... 376Simple data binding ....................................................................................... 378Importing Assets .................................................................................................... 382Getting At Assets ................................................................................................... 384Wiring Up Assets for Use ....................................................................................... 386Binding to Data ..................................................................................................... 389Creating a ViewModel .................................................................................... 391Binding to a ViewModel ................................................................................. 392Observable data ............................................................................................. 394Android ProgrammingxiiiAccessing Assets ................................................................................................... 396For the More Curious: More About Data Binding ........................................................ 396Lambda expressions ....................................................................................... 397More syntactic sugar ...................................................................................... 397BindingAdapters ............................................................................................ 397For the More Curious: Why Assets, Not Resources ...................................................... 398For the More Curious: Non-Assets? .......................................................................... 39821. Unit Testing and Audio Playback ................................................................................ 399Creating a SoundPool ............................................................................................. 399Loading Sounds ..................................................................................................... 400Playing Sounds ...................................................................................................... 402Test Dependencies .................................................................................................. 402Creating a Test Class .............................................................................................. 403Setting Up Your Test .............................................................................................. 405Using mocked dependencies ............................................................................ 405Writing Tests ......................................................................................................... 407Testing object interactions ............................................................................... 407Data Binding Callbacks .......................................................................................... 411Unloading Sounds .................................................................................................. 412Rotation and Object Continuity ................................................................................ 413Retaining a fragment ...................................................................................... 414Rotation and retained fragments ....................................................................... 414For the More Curious: Whether to Retain .................................................................. 416For the More Curious: Espresso and Integration Testing ................................................ 417For the More Curious: Mocks and Testing .................................................................. 418Challenge: Playback Speed Control ........................................................................... 41922. Styles and Themes .................................................................................................... 421Color Resources .................................................................................................... 422Styles ................................................................................................................... 422Style inheritance ............................................................................................ 424Themes ................................................................................................................ 425Modifying the theme ...................................................................................... 426Adding Theme Colors ............................................................................................ 428Overriding Theme Attributes .................................................................................... 429Theme spelunking .......................................................................................... 429Modifying Button Attributes .................................................................................... 433For the More Curious: More on Style Inheritance ........................................................ 435For the More Curious: Accessing Theme Attributes ..................................................... 43623. XML Drawables ....................................................................................................... 437Making Uniform Buttons ........................................................................................ 438Shape Drawables ................................................................................................... 439State List Drawables ............................................................................................... 441Layer List Drawables ............................................................................................. 443For the More Curious: Why Bother with XML Drawables? ........................................... 444For the More Curious: Mipmap Images ..................................................................... 445For the More Curious: 9-Patch Images ...................................................................... 446Challenge: Button Themes ....................................................................................... 45224. More About Intents and Tasks .................................................................................... 453Android ProgrammingxivSetting Up NerdLauncher ........................................................................................ 454Resolving an Implicit Intent ..................................................................................... 456Creating Explicit Intents at Runtime .......................................................................... 460Tasks and the Back Stack ........................................................................................ 462Switching between tasks ................................................................................. 462Starting a new task ......................................................................................... 464Using NerdLauncher as a Home Screen ..................................................................... 466Challenge: Icons .................................................................................................... 468For the More Curious: Processes vs Tasks .................................................................. 468For the More Curious: Concurrent Documents ............................................................ 47125. HTTP and Background Tasks ..................................................................................... 473Creating PhotoGallery ............................................................................................ 475Networking Basics ................................................................................................. 477Asking permission to network .......................................................................... 479Using AsyncTask to Run on a Background Thread ...................................................... 479You and Your Main Thread ..................................................................................... 481Beyond the main thread .................................................................................. 482Fetching JSON from Flickr ..................................................................................... 483Parsing JSON text .......................................................................................... 487From AsyncTask Back to the Main Thread ................................................................. 491Cleaning Up AsyncTasks ........................................................................................ 495For the More Curious: More on AsyncTask ................................................................ 496For the More Curious: Alternatives to AsyncTask ........................................................ 497Challenge: Gson .................................................................................................... 498Challenge: Paging .................................................................................................. 498Challenge: Dynamically Adjusting the Number of Columns .......................................... 49826. Loopers, Handlers, and HandlerThread ......................................................................... 499Preparing RecyclerView to Display Images ................................................................ 499Downloading Lots of Small Things ........................................................................... 502Communicating with the Main Thread ....................................................................... 502Assembling a Background Thread ............................................................................ 504Messages and Message Handlers .............................................................................. 506Message anatomy ........................................................................................... 506Handler anatomy ............................................................................................ 507Using handlers .............................................................................................. 508Passing handlers ............................................................................................ 512For the More Curious: AsyncTasks vs Threads ............................................................ 518For the More Curious: Solving the Image Downloading Problem .................................... 518For the More Curious: StrictMode ............................................................................ 519Challenge: Preloading and Caching ........................................................................... 52027. Search .................................................................................................................... 521Searching Flickr .................................................................................................... 521Using SearchView .................................................................................................. 526Responding to SearchView user interactions ....................................................... 530Simple Persistence with Shared Preferences ................................................................ 532Polishing Your App ................................................................................................ 536Challenge: Polishing Your App Some More ................................................................ 53628. Background Services ................................................................................................. 537Android ProgrammingxvCreating an IntentService ........................................................................................ 537What Services Are For ........................................................................................... 540Safe background networking ............................................................................ 540Looking for New Results ........................................................................................ 542Delayed Execution with AlarmManager ..................................................................... 544Being a good citizen: using alarms the right way ................................................. 545PendingIntent ................................................................................................ 547Managing alarms with PendingIntent ................................................................. 547Controlling Your Alarm .......................................................................................... 548Notifications .......................................................................................................... 551Challenge: Notifications on Android Wear .................................................................. 553For the More Curious: Service Details ....................................................................... 553What a service does (and does not do) ............................................................... 553A service’s lifecycle ....................................................................................... 554Non-sticky services ........................................................................................ 554Sticky services ............................................................................................... 554Bound services .............................................................................................. 555For the More Curious: JobScheduler and JobServices ................................................... 556JobScheduler and the future of background work ................................................. 559Challenge: Using JobService on Lollipop ................................................................... 559For the More Curious: Sync Adapters ....................................................................... 55929. Broadcast Intents ...................................................................................................... 561Regular Intents vs Broadcast Intents .......................................................................... 561Receiving a System Broadcast: Waking Up on Boot ..................................................... 562Creating and registering a standalone receiver ..................................................... 562Using receivers .............................................................................................. 565Filtering Foreground Notifications ...........................................Android ProgrammingxviSetting Up the DragAndDraw Project ........................................................................ 598Creating a Custom View ......................................................................................... 600Creating BoxDrawingView .............................................................................. 600Handling Touch Events ........................................................................................... 602Tracking across motion events .......................................................................... 604Rendering Inside onDraw(Canvas) ............................................................................ 606Challenge: Saving State .......................................................................................... 608Challenge: Rotating Boxes ...................................................................................... 60832. Property Animation ................................................................................................... 609Building the Scene ................................................................................................. 609Simple Property Animation ..................................................................................... 612View transformation properties ......................................................................... 614Using different interpolators ............................................................................ 616Color evaluation ............................................................................................ 616Playing Animators Together ..................................................................................... 618For the More Curious: Other Animation APIs ............................................................. 620Legacy animation tools ................................................................................... 620Transitions .................................................................................................... 620Challenges ............................................................................................................ 62033. Locations and Play Services ....................................................................................... 621Locations and Libraries ........................................................................................... 622Google Play Services ...................................................................................... 622Creating Locatr ...................................................................................................... 623Play Services and Location Testing on Emulators ........................................................ 623Mock location data ......................................................................................... 624Building Out Locatr ............................................................................................... 627Setting Up Google Play Services .............................................................................. 629Location permissions ...................................................................................... 630Using Google Play Services ..................................................................................... 631Flickr Geosearch .................................................................................................... 633Getting a Location Fix ............................................................................................ 634Asking for Permission at Runtime ............................................................................ 637Checking for permissions ................................................................................ 638Find and Display an Image ...................................................................................... 644Challenge: Permissions Rationale ............................................................................. 646Challenge: Progress ................................................................................................ 64634. Maps ...................................................................................................................... 647Importing Play Services Maps .................................................................................. 647Mapping on Android .............................................................................................. 647Getting a Maps API Key ......................................................................................... 648Setting Up Your Map ............................................................................................. 650Getting More Location Data .................................................................................... 652Working with Your Map ......................................................................................... 654Drawing on the map ....................................................................................... 657For the More Curious: Teams and API Keys ............................................................... 65935. Material Design ........................................................................................................ 661Material Surfaces ................................................................................................... 662Elevation and Z values .................................................................................... 664Android ProgrammingxviiState list animators ......................................................................................... 665Animation Tools .................................................................................................... 667Circular reveal ............................................................................................... 667Shared element transitions ............................................................................... 669View Components .................................................................................................. 673Cards ........................................................................................................... 673Floating action buttons .................................................................................... 675Snackbars ..................................................................................................... 676More on Material Design ........................................................................................ 67736. Afterword ................................................................................................................ 679The Final Challenge ............................................................................................... 679Shameless Plugs .................................................................................................... 679Thank You ............................................................................................................ 680Index ........................................................................................................................... 681
评论