Cover Page

PROFESSIONAL Android®

 

Fourth Edition

 

 

Reto Meier

Ian Lake

 

 

 

 

 

 

 

Wiley Logo

 

To Kris.

 

RETO

 

 

To Andrea and Hannah.

 

IAN

ABOUT THE AUTHORS

RETO MEIER has been working to help Android developers create the best applications possible for their users since the initial Android release in 2007. Reto grew up in Perth, Western Australia, and then spent “the next 18 months” in London for a total of 6 years, before settling in the San Francisco Bay Area with his wife in 2011.

Reto has spent 10 years as a Developer Advocate at Google, contributing articles, online training, conference talks, and YouTube videos to the developer community.

Before smartphones were invented, Reto spent over 10 years as a software developer in various industries, including offshore oil and gas and finance.

You can learn more about Reto’s thoughts on Android development, ask him questions, and see pictures of his cats on Twitter at www.twitter.com/retomeier, where he shares more than he probably should, and read longer thoughts on Medium at medium.com/@retomeier.

IAN LAKE has lived in nine states across the United States before settling in the San Francisco Bay Area in 2013.

Ian is a member of the Android Toolkit team at Google, focused on providing the libraries and APIs needed for modern Android development. His prior experience includes that as an Android Developer Advocate, Android app developer, and enterprise application developer back when Android wasn’t even an option.

You can connect with Ian on Google+ (plus.google.com/+IanLake) or Twitter (www.twitter.com/ianhlake) to learn more about his wonderful family, hobbies (mostly Android development), and interests.

While Reto and Ian work at Google, the views and opinions expressed in this book are theirs alone and do not necessarily represent those of their employer.

ABOUT THE TECHNICAL EDITORS

DANIEL ULERY is a Senior Software Engineer who lives near Lewiston, Idaho. His experience includes software engineering projects using technologies such as Java Enterprise, C# WinForms, SQL Server, Raspberry Pi, and Android. Dan received his Bachelor of Science in Computer Science from the University of Idaho in 2004. When he’s not working on software projects, he’s likely working on one of many DIY projects.

ED WOODWARD is a Senior Development Manager and Android Developer for OpenStax at Rice University. He currently manages the Devops team and is tech lead on the Business Intelligence team along with developing OpenStax’s Android app. Prior to joining OpenStax, Ed was a Vice President/Application Architect at JPMorganChase. Ed was a Band Director at the high school and middle school level for several years before transitioning to programming.

CHAIM KRAUSE is an expert computer programmer with more than 30 years of experience to prove it. He has worked as a lead tech support engineer for ISPs as early as 1995, as a senior developer support engineer with Borland for Delphi, and has worked in Silicon Valley for over a decade in various roles, including technical support engineer and developer support engineer. He is currently a military simulation specialist for the US Army’s Command and General Staff College, working on projects such as developing serious games for use in training exercises. He has also authored several video training courses on Linux topics, and has been a technical reviewer for over 20 books, including Amazon Web Services for Mobile Developers (Sybex, 2017) and Professional Swift (Wrox, 2015). It seems only natural then that he would be an avid gamer and have his own electronics lab and server room in his basement. He currently resides in Leavenworth, Kansas, with his beautiful partner Ivana and a menagerie of four-legged companions: their two dogs, Dasher and Minnie, and their three cats, Pudems, Talyn, and Alaska.

MURAT YENER is a code geek, open source committer, Java Champion, and ex-Google Developer Expert on Android, who is working at Google. He is the author of Expert Android Studio (Wiley, 2016) and Professional Java EE Design Patterns (Wiley, 2015). He has extensive experience with developing Android, Java, web, JavaEE, and OSGi applications, in addition to teaching courses and mentoring. Murat was an Eclipse committer and one of the initial committers of the Eclipse Libra project. Murat had been a user group leader at GDG Istanbul and in GDG San Francisco, organizing, participating, and speaking at events. He is also a regular speaker at major conferences, such as DroidCon, JavaOne, and Devoxx.

CREDITS

  • PROJECT EDITOR
    John Sleeva
  • TECHNICAL EDITORS
    Daniel Ulery
    Ed Woodward
    Chaim Krause
    Murat Yener
  • PRODUCTION EDITOR
    Barath Kumar Rajasekaran
  • COPY EDITOR
    Kimberly A. Cofer
  • PRODUCTION MANAGER
    Kathleen Wisor
  • CONTENT ENABLEMENT AND OPERATIONS MANAGER
    Pete Gaughan
  • MARKETING MANAGER
    Christie Hilbrich
  • EXECUTIVE EDITOR
    Jim Minatel
  • PROJECT COORDINATOR, COVER
    Brent Savage
  • PROOFREADER
    Nancy Bell
  • INDEXER
    Johnna VanHoose Dinse
  • COVER DESIGNER
    Wiley
  • COVER IMAGE
    © 1971yes/iStock.com

ACKNOWLEDGMENTS

FIRST, I’D LIKE TO THANK MY WIFE KRISTY, whose love and support makes everything I do possible.

A big thank you to my friends and colleagues at Google, particularly all the amazing people in the Android team, without whom I’d have nothing to write about, and the developer relations team who inspire me every day.

I also thank our army of technical editors, including Dan Ulery, Ed Woodward, Chaim Krause, Murat Yener, James Harmon, and Chad Darby, without whom this book would contain far more errors than it does. Those that remain are entirely my fault. Thank you to the whole team at Wrox, especially John Sleeva and Jim Minatel, whose patience and support in getting this book completed was non-trivial.

An extra big thank you goes out to the incredible Android community, made up of passionate, generous, and hard working developers who seem to spend as much time helping each other as they do building amazing apps. Your efforts have been critical in making Android the huge success that it is. Thank you.

—RETO

MY FAMILY, ANDREA AND HANNAH, are what make everything worth it. Without their support, I wouldn’t be able to do much of anything, much less write this book.

I’d like to echo Reto’s thanks for everyone involved in publishing and making this book a reality, the Android team for giving us plenty to talk about, and the Android developer community for sharing our passion around building better apps.

—IAN

INTRODUCTION

For many people, smartphones have become an extension of themselves. Now running on over 2 billion monthly-active devices, Android is the most common smartphone operating system in use world-wide, with users installing an average of 50 apps each, resulting in over 94 billion apps downloaded from the Play app store in 2017 alone.

Ubiquitous and indispensable, smartphones are so advanced and personal that studies have shown people become anxious if they misplace their device, lose connectivity, or run low on battery.

In the 10 years since launching in 2008, Android has expanded beyond mobile phones to become a development platform for a wide range of hardware, with 24,000 devices from over 1,300 brands, including everything from tablets to televisions, watches, cars, and Internet of Things (IoT) devices. Over the same period, there have been 28 platform and SDK releases.

These innovations, combined with the size of the ecosystem, provide unparalleled opportunities for developers to create innovative new applications for a global audience of users.

Android offers an open platform for mobile application development. Without artificial barriers, Android developers are free to write apps that take full advantage of an incredible range of devices. Using Google Play for distribution, developers can distribute free and paid applications to compatible Android devices globally.

This book is a hands-on guide to building Android applications for all Android devices. It’s written based on version 8.1 of the Android SDK, using Android Studio 3.1. Chapter by chapter, it takes you through a series of sample projects, each introducing new features and techniques to get the most out of Android. It covers all the basic functionality to get started, as well as the information for experienced mobile developers to take full advantage of the features of Android, to enhance existing products or create innovative new ones.

The Android team releases a new major platform every year, a new version of Android Studio every few months, and incremental changes to Jetpack, such as the support library and Android Architecture Components, many times each year. With such rapid release cycles, there are regular changes, additions, and improvements to the tools, platform APIs, and development libraries you’ll use—and which are described in this book. To minimize the impact of these changes, the Android engineering team works hard to ensure backward compatibility.

However, future releases will date some of the information provided in this book, and not all active Android devices will be running the latest platform release. To mitigate this, wherever possible, we have used backward-compatible support libraries, and included details on which platform releases support the functionality described—and which alternatives may exist to provide support for users of devices running earlier platforms.

Further, the explanations and examples included will give you the grounding and knowledge needed to write compelling mobile applications using the current SDK, along with the flexibility to quickly adapt to future enhancements.

WHO THIS BOOK IS FOR

This book is for anyone interested in creating applications for the Android platform. It includes information that will be valuable, whether you’re an experienced mobile developer on other platforms, making your first foray into writing mobile apps, and if you have some Android development experience.

It will help if you’ve used a smartphone (particularly an Android device), but it’s not necessary, nor is prior experience in mobile application development.

It’s expected that you’ll have experience in software development and be familiar with basic object-oriented paradigms. An understanding of Java syntax is expected, though not a strict necessity.

Chapters 1 and 2 introduce mobile development and the Android development platform, and contain instructions to get you started. Beyond that, there’s no requirement to read the chapters in order, although a good understanding of the core components described in Chapters 3–7 is important before you venture into the remaining chapters. Chapter 11 covers important details on how to ensure your apps are responsive and efficient, while Chapters 12–14 describe how to provide a rich and consistent user experience. The remaining chapters cover a variety of functionality whose relevance will vary based on your application, and can be read in whatever order interest or need dictates.

WHAT THIS BOOK COVERS

Chapter 1 introduces Android, including what it is and how it fits into the mobile development ecosystem. What Android offers as a development platform and why it’s an exciting opportunity for creating mobile phone applications are then examined in greater detail.

Chapter 2 covers some best practices for mobile development and explains how to download and install Android Studio and the Android SDK. It then introduces some of the tools and features included with Android Studio, and demonstrates how they can be used to create and debug new applications.

Chapters 3–7 take an in-depth look at the fundamental Android application components—starting by examining the components that make up an Android application, and then moving on to “Activities” and “Fragments,” and their associated lifetimes and lifecycles.

You’ll then be introduced to the application manifest and the Gradle build system, before learning more about the external resource framework used to support devices used in different counties, with different languages, and in a variety of shapes and sizes.

You’ll learn how to create basic user interfaces with layouts, Views, and Fragments, before being introduced to the Intent and Broadcast Receiver mechanisms used to perform actions and send messages between application components. Accessing Internet resources is then covered, followed by a detailed look at data storage, retrieval, and sharing. You’ll start with the preference-saving mechanism and then move on to file handling, databases, and Content Providers—including accessing data from the native databases.

This section finishes with an examination of how to ensure your app is always responsive, and is efficient in its use of battery when running in the background. You’ll be introduced to threading APIs that enable asynchronous execution, and mechanisms that support efficient scheduling of background work. You’ll also learn how to create and display interactive Notifications.

Chapters 12–14 build on the UI framework introduced in Chapter 5. You’ll learn to enhance the user experience through the principles of material design and to make your applications accessible and optimized for a variety of screen sizes and resolutions. You’ll further improve the user experience by understanding the variety of navigation options available, adding movement through animations, and the use of Toolbars and Menus.

Chapters 15–19 look at more advanced topics. You’ll learn how to use Google Play services to add interactive maps, find the user’s location, and how to create geo- and awareness-fences. Using movement and environmental Sensors—including the compass, accelerometers, and the barometer—you’ll make your applications react to their environment.

After looking at how to play and record multimedia, as well as how to use the camera to take pictures and record video, you’ll be introduced to Android’s communication capabilities, including Bluetooth, NFC, and Wi-Fi Direct. Next, you’ll learn how your applications can interact with users directly from the home screen using dynamic Widgets, Live Wallpaper, and the Application Shortcuts.

Chapter 20 discusses several advanced development topics, including security, using the fingerprint sensor, and Strict Mode, followed by the telephony APIs and the APIs used to send and receive SMS messages.

Finally, Chapter 21 examines the process for building, releasing, monitoring, and monetizing your applications. In particular, it includes details for publishing and distributing your applications within Google Play.

HOW THIS BOOK IS STRUCTURED

This book is structured in a logical sequence to help readers of different development backgrounds learn how to write advanced Android applications. There’s no requirement to read each chapter sequentially, but several of the sample projects are developed over the course of multiple chapters, adding new functionality and other enhancements at each stage.

Experienced mobile developers who have already installed Android Studio, and those with a working knowledge of Android development, can skim the first two chapters—which are an introduction to mobile development and instructions for creating your development environment—and then dive in at Chapters 3–7. These chapters cover the fundamentals of Android development, so it’s important to have a solid understanding of the concepts they describe.

With this covered, you can move on to the remaining chapters, which look at material design, maps, location-based services, background applications, and more advanced topics, such as hardware interaction and networking.

WHAT YOU NEED TO USE THIS BOOK

To use the code samples in this book, you will need to create an Android development environment by downloading Android Studio and the Android SDK. It’s also possible to use other IDEs, or even to build your apps from the command-line. We’ll assume, however, you’re using Android Studio.

Android development is supported on Windows, macOS, and Linux, with Android Studio and the SDK available from the Android website.

You do not need an Android device to use this book or develop Android applications—though it can be useful, particularly when testing.

CONVENTIONS

To help you get the most from the text and keep track of what’s happening, we’ve used a number of conventions throughout the book.

As for styles in the text:

  • We show file names, URLs, and code within the text like so: persistence.properties.
  • To help readability, class names in text are often represented using a regular font but capitalized like so: Content Provider.
  • We present code in two different ways:
    We use a monofont type with no highlighting for most code examples.
    We use bold to indicate changes or additions from a similar previous code snippet. 
  • In some code samples, you’ll see lines marked as follows:

    [… Existing code …]

    or

    [… Implement something here …]

    These represent instructions to replace the entire line (including the square brackets) with actual code, either from a previous code snippet (in the former case) or with your own implementation (in the latter).

  • To keep the code samples reasonably concise, we have not always included every package definition or import statement required in the code snippets. The downloadable code samples described below include all the required import statements. Additionally, if you are developing using Android Studio, you can enable auto-import or use the keyboard shortcut Ctrl+Space (Cmd+Space) to add the required import statements.

SOURCE CODE

As you work through the examples in this book, you may choose either to type in all the code manually, or to use the source code files that accompany the book. All the source code used in this book is available for download at www.wrox.com. When at the site, simply locate the book’s title (use the Search box or one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.

Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

ERRATA

We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration, and at the same time, you will be helping us provide even higher quality information.

To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page, you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list, including links to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml.

If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.