Professional Android, 4th Edition shows developers how to leverage the latest features of Android to create robust and compelling mobile apps. This hands-on approach provides in-depth coverage through a series of projects, each introducing a new Android platform feature and highlighting the techniques and best practices that exploit its utmost functionality. The exercises begin simply, and gradually build into advanced Android development. Clear, concise examples show you how to quickly construct real-world mobile applications.
This book is your guide to smart, efficient, effective Android development.
- Learn the best practices that get more out of Android
- Understand the anatomy, lifecycle, and UI metaphor of Android apps
- Design for all mobile platforms, including tablets
- Utilize both the Android framework and Google Play services
Table of Contents
INTRODUCTION xxxi
CHAPTER 1: HELLO, ANDROID 1
Android Application Development 1
A Little Background 2
The Not-So-Distant Past 3
Living in the Future 3
The Android Ecosystem 3
Pre-installed Android Applications 4
Android SDK Features 5
What Does Android Run On? 6
Why Develop for Mobile? 6
Why Develop for Android? 7
Introducing the Development Framework 7
What Comes in the Box 8
Understanding the Android Software Stack 8
The Android Run Time 10
Android Application Architecture 11
Android Libraries 12
CHAPTER 2: GETTING STARTED 13
Getting Started Developing Android Apps 14
Developing for Android 15
What You Need to Begin 15
Creating Your First Android Application 20
Getting Started Writing Android Apps Using Kotlin 35
Using the Android Support Library Package 36
Developing for Mobile and Embedded Devices 39
Hardware-Imposed Design Considerations 39
Considering the User’s Environment 43
Developing for Android 44
Android Development Tools 48
Android Studio 49
The Android Virtual Device Manager 51
The Android Emulator 51
Android Profiler 52
The Android Debug Bridge 54
APK Analyzer 54
The Lint Tool 55
Monkey, Monkey Runner, and Espresso UI Testing 55
Gradle 56
CHAPTER 3: APPLICATIONS AND ACTIVITIES AND FRAGMENTS, OH MY! 57
Applications, Activities, and Fragments 58
The Components of an Android Application 58
The Android Application Life Cycle, Priority, and Process States 59
Introducing the Android Application Class 61
A Closer Look at Android Activities 61
Creating Activities 62
Using the AppCompatActivity 63
The Activity Life Cycle 64
Responding to Memory Pressure 71
Introducing Fragments 73
Creating New Fragments 73
The Fragment Life Cycle 74
Introducing the Fragment Manager 79
Adding Fragments to Activities 79
Communicating Between Fragments and Activities 85
Fragments without User Interfaces 86
Building an Earthquake Viewer Application 87
CHAPTER 4: DEFINING THE ANDROID MANIFEST AND GRADLE BUILD FILES, AND EXTERNALIZING RESOURCES 95
The Manifest, Build Files, and Resources 96
Introducing the Android Manifest 96
Configuring the Gradle Build 101
Gradle Settings File 101
Project Gradle Build File 102
Module Gradle Build Files 102
Externalizing Resources 107
Creating Resources 108
Using Resources 119
Creating Resources for Different Languages and Hardware 122
Runtime Configuration Changes 126
CHAPTER 5: BUILDING USER INTERFACES 129
Fundamental Android Design 130
Density-Independent Design 130
Android User Interface Fundamentals 131
Assigning User Interfaces to Activities 132
Introducing Layouts 132
Defining Layouts 134
Using Layouts to Create Device-Independent User Interfaces 136
Optimizing Layouts 139
The Android Widget Toolbox 143
Working with Lists and Grids 144
Recycler View and Layout Managers 145
Introducing Adapters 146
Returning to the Earthquake Viewer Application 149
Introducing Data Binding 150
Enabling Data Binding 151
Variables in Data Binding 152
Data Binding for the Earthquake Viewer Application 153
Creating New Views 155
Modifying Existing Views 155
Creating Compound Controls 159
Creating Simple Compound Controls as a Layout 161
Creating Custom Views 162
Using Custom Controls 176
CHAPTER 6: INTENTS AND BROADCAST RECEIVERS 177
Using Intents and Broadcast Receivers 178
Using Intents to Launch Activities 178
Explicitly Starting New Activities 179
Implicit Intents and Late Runtime Binding 179
Determining If an Intent Will Resolve 180
Returning Results from Activities 181
Using Platform-Native Actions to Launch Activities 184
Creating Intent Filters to Receive Implicit Intents 186
Defining an Intent Filter 186
Using Intent Filters for Plug-Ins and Extensibility 194
Introducing Linkify 198
Native Linkify Link Types 198
Creating Custom Link Strings 199
Using the Match Filter 200
Using the Transform Filter 200
Using Intents to Broadcast Events 200
Broadcasting Events with Intents 201
Listening for Intent Broadcasts with Broadcast Receivers 202
Registering Broadcast Receivers in Code 203
Registering Broadcast Receivers in Your Application Manifest 204
Managing Manifest Receivers at Run Time 204
Monitoring Device State Changes through Broadcast Intents 205
Introducing the Local Broadcast Manager 207
Introducing Pending Intents 208
CHAPTER 7: USING INTERNET RESOURCES 211
Connecting to the Internet 211
Connecting, Downloading, and Parsing Internet Resources 212
Why Build a Native Internet App? 212
Connecting to an Internet Resource 213
Performing Network Operations on Background Threads Using View Models, Live Data, and Asynchronous Tasks 214
Parsing XML Using the XML Pull Parser 219
Connecting the Earthquake Viewer to the Internet 220
Parsing JSON Using the JSON Parser 228
Using the Download Manager 233
Downloading Files 233
Customizing Download Manager Notifications 235
Specifying a Download Location 237
Canceling and Removing Downloads 238
Querying the Download Manager 238
Best Practices for Downloading Data without Draining the Battery 241
An Introduction to Internet Services and Cloud Computing 242
CHAPTER 8: FILES, SAVING STATE, AND USER PREFERENCES 245
Saving Files, States, and Preferences 246
Saving and Restoring Activity and Fragment Instance
State Using the Lifecycle Handlers 246
Retaining Instance State with Headless Fragments and View Models 248
View Models and Live Data 248
Headless Fragments 251
Creating and Saving Shared Preferences 252
Retrieving Shared Preferences 253
Introducing On Shared Preference Change Listeners 254
Configuring Auto Backup of Application Files and Shared Preferences 254
Building a Preference UI 256
Using the Preference Support Library 256
Defining a Preference Screen Layout in XML 257
Introducing the Preference Fragment 260
Creating a Settings Activity for the Earthquake Monitor 261
Including Static Files as Resources 267
Working with the Filesystem 267
File-Management Tools 267
Creating Files on Application-Specifi c Internal Storage 268
Creating Files on Application-Specifi c External Storage 268
Accessing Public Directories Using Scoped Directory Access 270
Sharing Files Using File Provider 274
Creating a File Provider 274
Sharing a File Using a File Provider 275
Receiving a File from a File Provider 275
Accessing Files from Other Applications Using the Storage Access Framework 275
Requesting Temporary Access to Files 276
Requesting Persistent Access to Files 277
Requesting Access to Directories 277
Creating New Files 278
Using URI-Based Permissions 278
CHAPTER 9: CREATING AND USING DATABASES 281
Introducing Structured Data Storage in Android 282
Storing Data Using the Room Persistence Library 282
Adding the Room Persistence Library 283
Defining a Room Database 284
Persisting Complex Objects Using Type Convertors 286
Defining Room Database Interactions Using Data Access Objects 288
Performing Room Database Interactions 291
Monitoring Query Result Changes with Live Data 292
Persisting Earthquakes to a Database with Room 294
Working with SQLite Databases 298
Input Validation and SQL Injection 299
Cursors and Content Values 299
Defining a Database Contract 300
Introducing the SQLiteOpenHelper 300
Opening Databases with the SQLite Open Helper 302
Opening and Creating Databases without the SQLite Open Helper 303
Adding, Updating, and Deleting Rows 303
Querying a Database 305
Extracting Values from a Cursor 307
Introducing the Firebase Realtime Database 308
Adding Firebase to Your App 309
Defining a Firebase Database and Defining Access Rules 311
Adding, Modifying, Deleting, and Querying Data from a Firebase Realtime Database 313
CHAPTER 10: CONTENT PROVIDERS AND SEARCH 317
Introducing Content Providers 318
Why Should I Use Content Providers? 318
Creating Content Providers 319
Creating the Content Provider’s Database 320
Registering Content Providers 321
Publishing Your Content Provider’s URI Address 321
Implementing Content Provider Queries 322
Content Provider Transactions 325
Sharing Files Using a Content Provider 327
Adding Permission Requirements to Content Providers 328
Accessing Content Providers with Content Resolvers 330
Querying Content Providers 330
Cancelling Queries 333
Querying for Content Asynchronously with a Cursor Loader 333
Adding, Deleting, and Updating Content 336
Accessing Files Stored in Content Providers 338
Accessing Permission-Restricted Content Providers 339
Using Native Android Content Providers 341
Accessing the Call Log 341
Using the Media Store Content Provider 342
Using the Contacts Content Provider 344
Using the Calendar Content Provider 351
Adding Search to Your Application 354
Defining Your Search Metadata 354
Creating a Search Results Activity 355
Searching a Content Provider 357
Using the Search View Widget 360
Providing Search Suggestions Using a Content Provider 362
CHAPTER 11: WORKING IN THE BACKGROUND 377
Working in the Background 378
Using Background Threads 379
Using Asynchronous Tasks to Run Tasks Asynchronously 379
Manual Thread Creation Using Handler Threads 383
Scheduling Background Jobs 385
Creating a Job Service for the Job Scheduler 386
Scheduling Jobs with the Job Scheduler 388
Scheduling Jobs with the Firebase Job Dispatcher 391
Scheduling Work with the Work Manager 393
An Earthquake-Monitoring Job Service Example 396
Using Notifications to Notify Users 401
Introducing the Notification Manager 401
Working with Notification Channels 402
Creating Notifications 403
Setting a Notification’s Priority 407
Adding Notification Actions 411
Adding Direct Reply Actions 412
Grouping Multiple Notifications 413
Adding Notifications to the Earthquake Monitor 414
Using Firebase Cloud Messaging 417
Triggering Notifications Remotely with Firebase Notifications 418
Receiving Data with Firebase Cloud Messaging 421
Using Alarms 422
Creating, Setting, and Canceling Alarms 423
Setting an Alarm Clock 424
Introducing Services 424
Using Bound Services 425
Creating a Started Service 427
CHAPTER 12: IMPLEMENTING THE ANDROID
DESIGN PHILOSOPHY 433
Introducing the Android Design Philosophy 434
Designing for Every Screen 434
Resolution Independence 435
Supporting and Optimizing for Different Screen Sizes 436
Creating Scalable Graphics Assets 439
Introducing Material Design 445
Thinking in Terms of Paper and Ink 446
Using Color and Keylines as Guides 447
Continuity through Motion 449
Material Design UI Elements 452
The App Bar 452
Applying Material Design to the Earthquake Monitor 455
Using Cards to Display Content 456
Floating Action Buttons 460
CHAPTER 13: IMPLEMENTING A MODERN ANDROID USER EXPERIENCE 463
The Modern Android UI 464
Creating Consistent, Modern User Interfaces
Using AppCompat 464
Creating and Applying Themes Using AppCompat 465
Creating Theme Overlays for Specific Views 466
Adding a Menu and Actions to the App Bar 467
Defining a Menu Resource 467
Adding a Menu to an Activity 468
Adding a Menu to a Fragment 469
Updating Menu Items Dynamically 469
Handling Menu Selections 470
Adding Action Views and Action Providers 470
Going Beyond the Default App Bar 472
Replacing Your App Bar with a Toolbar 472
Advanced Scrolling Techniques for the Toolbar 473
Incorporating Menus without the App Bar 476
Improving the Earthquake Monitor’s App Bar 477
App Navigation Patterns 479
Navigating with Tabs 479
Implementing a Bottom Navigation Bar 482
Using a Navigation Drawer 485
Combining Navigation Patterns 491
Adding Tabs to the Earthquake Monitor 492
Choosing the Right Level of Interruption 496
Initiating a Dialog 497
Let’s Make a Toast 498
Inline Interruptions with Snackbars 499
CHAPTER 14: ADVANCED CUSTOMIZATION OF YOUR USER INTERFACE 501
Expanding the User Experience 502
Supporting Accessibility 502
Supporting Navigation without a Touch Screen 502
Providing a Textual Description of Each View 503
Introducing Android Text-to-Speech 503
Using Speech Recognition 505
Using Speech Recognition for Voice Input 506
Using Speech Recognition for Search 507
Controlling Device Vibration 508
Going Full Screen 508
Working with Property Animations 510
Enhancing Your Views 513
Advanced Canvas Drawing 514
Creating Interactive Controls 530
Composite Drawable Resources 536
Transformative Drawables 536
Layer Drawables 537
State List Drawables 537
Level List Drawables 538
Copy, Paste, and the Clipboard 539
Copying Data to the Clipboard 539
Pasting Clipboard Data 539
CHAPTER 15: LOCATION, CONTEXTUAL AWARENESS,AND MAPPING 541
Adding Location, Maps, and Contextual Awareness to Your
Applications 542
Introducing Google Play Services 542
Adding Google Play Services to Your Application 543
Determining the Availability of Google Play Services 545
Finding Device Location Using Google Location Services 546
Using the Emulator to Test Location-Based Functionality 548
Finding the Last Known Location 549
“Where Am I” Example 551
Requesting Location Change Updates 555
Changing Device Location Settings 560
Updating the Location in the “Where Am I” Example 563
Best Practices When Using Location 566
Setting and Managing Geofences 567
Using the Legacy Platform Location-Based Services 571
Selecting a Location Provider 572
Finding the Last Known Location 574
Requesting Location Change Updates 575
Best Practice for Using the Legacy Location-Based Services 577
Using the Geocoder 580
Reverse Geocoding 581
Forward Geocoding 582
Geocoding Where Am I 583
Creating Map-Based Activities 585
Getting Your Maps API Key 586
Creating a Map-Based Activity 586
Configuring Google Maps 589
Changing the Camera Position with Camera Updates 590
Mapping Where Am I 592
Displaying the Current Location with the My Location Layer 596
Displaying Interactive Map Markers 596
Adding Shapes to Google Maps 599
Adding Image Overlays to Google Maps 602
Adding Markers and Shapes to Where Am I 602
Mapping the Earthquake Example 605
Adding Contextual Awareness 609
Connecting to the Google Play Services API Client and Obtaining API Keys 610
Using Awareness Snapshots 612
Setting and Monitoring Awareness Fences 613
Awareness Best Practices 617
CHAPTER 16: HARDWARE SENSORS 619
Introducing Android Sensors 620
Using the Sensor Manager 620
Understanding the Android Sensors 621
Discovering and Identifying Sensors 623
Determining Sensor Capabilities 625
Wakeup and Non-Wakeup Sensors 627
Monitoring Sensor Results 627
Interpreting Sensor Values 632
Testing Sensors with the Android Virtual Device and Emulator 635
Best Practices for Working with Sensors 637
Monitoring a Device’s Movement and Orientation 637
Determining the Natural Orientation of a Device 638
Introducing Accelerometers 639
Detecting Acceleration Changes 640
Creating a Gravitational Force Meter 642
Determining a Device’s Orientation 645
Creating a Compass and Artificial Horizon 650
Using the Environmental Sensors 654
Using the Barometer Sensor 654
Creating a Weather Station 655
Using Body Sensors 659
User Activity Recognition 662
CHAPTER 17: AUDIO, VIDEO, AND USING THE CAMERA 665
Playing Audio and Video, and Using the Camera 666
Playing Audio and Video 666
Introducing the Media Player 667
Using Media Player for Video Playback 669
Using ExoPlayer for Video Playback 672
Requesting and Managing Audio Focus 674
Pausing Playback When the Output Changes 676
Responding to the Volume Controls 677
Working with a Media Session 678
Using the Media Router and Cast Application Framework 682
Background Audio Playback 686
Building an Audio Playback Service 686
Using a Media Browser to Connect Your Activity to a
Media Browser Service 688
Life Cycle of a Media Browser Service 690
Playing Audio as a Foreground Service 691
Creating Media Style Notifications 693
Using the Media Recorder to Record Audio 695
Using the Camera for Taking Pictures 697
Using Intents to Take Pictures 697
Controlling the Camera Directly 699
Reading and Writing JPEG EXIF Image Details 706
Recording Video 706
Using Intents to Record Video 707
Using the Media Recorder to Record Video 707
Adding Media to the Media Store 710
Inserting Media Using the Media Scanner 710
Inserting Media Manually 711
CHAPTER 18: COMMUNICATING WITH BLUETOOTH,NFC, AND WI-FI PEER-TO-PEER 713
Networking and Peer-to-Peer Communication 713
Transferring Data Using Bluetooth 714
Managing the Local Bluetooth Device Adapter 714
Being Discoverable and Remote Device Discovery 716
Bluetooth Communications 720
Bluetooth Profiles 725
Bluetooth Low Energy 726
Transferring Data Using Wi-Fi Peer-to-Peer 728
Initializing the Wi-Fi Peer-to-Peer Framework 729
Discovering Peers 731
Connecting with Peers 732
Transferring Data between Peers 733
Using Near Field Communication 735
Reading NFC Tags 735
Using the Foreground Dispatch System 736
Using Android Beam 738
Creating Android Beam Messages 739
Assigning the Android Beam Payload 740
Receiving Android Beam Messages 742
CHAPTER 19: INVADING THE HOME SCREEN 743
Customizing the Home Screen 743
Introducing Home Screen Widgets 744
Defining the Widget Layout 745
Defining Your Widget Size and Other Metadata 746
Implementing Your Widget 748
Updating the Widget UI Using the App Widget Manager and Remote Views 749
Forcing Refreshes of Your Widget Data and UI 753
Creating and Using a Widget Configuration Activity 756
Creating an Earthquake Widget 757
Introducing Collection View Widgets 763
Creating Collection View Widget Layouts 764
Updating Collection View Items with a Remote Views Factory 765
Updating Collection View Items with a Remote Views Service 767
Populating Collection View Widgets Using a Remote Views Service 768
Adding Interactivity to the Items within a Collection View Widget 769
Refreshing Your Collection View Widgets 770
Creating an Earthquake Collection View Widget 770
Creating Live Wallpaper 777
Creating a Live Wallpaper Definition Resource 778
Creating a Wallpaper Service Engine 778
Creating a Wallpaper Service 780
Creating App Shortcuts 781
Static Shortcuts 783
Dynamic Shortcuts 784
Tracking App Shortcut Use 785
CHAPTER 20: ADVANCED ANDROID DEVELOPMENT 787
Advanced Android 788
Paranoid Android 788
Linux Kernel Security 788
Re-introducing Permissions 789
Storing Keys in the Android Keystore 792
Using the Fingerprint Sensor 792
Dealing with Different Hardware and Software Availability 793
Specifying Required Hardware 794
Confirming Hardware Availability 795
Building Backward-Compatible Applications 795
Optimizing UI Performance with Strict Mode 797
Telephony and SMS 798
Telephony 799
Sending and Receiving SMS Messages 806
CHAPTER 21: RELEASING, DISTRIBUTING, AND MONITORING APPLICATIONS 825
Preparing for Release 826
Preparing Release Support Material 826
Preparing Your Code for a Release Build 827
Updating Application Metadata in Your Application Manifest 828
Reviewing Application Installation Restrictions 828
Application Versioning 830
Signing Production Builds of Your Application 830
Creating a Keystore and Signing Key with Android Studio 832
Obtaining API Keys Based on Your Private Release Key 833
Building and Signing a Production Release 834
Distributing Your Application on the Google Play Store 835
Introducing the Google Play Store 835
Getting Started with the Google Play Store 836
Creating an Application on the Google Play Store 837
Publishing Your Application 845
Monitoring Your Application in Production 848
An Introduction to Monetizing Applications 853
Application Marketing, Promotion, and Distribution Strategies 854
Application Launch Strategies 854
Internationalization 855
Using Firebase to Monitor Your Application 856
Adding Firebase to Your Application 856
Using Firebase Analytics 857
Firebase Performance Monitoring 860
INDEX 863