Hello, Android Introducing Google’s Mobile Development Platform, 3rd Edition Contents Acknowledgments 9 Preface 10 What Makes Android Special? 10 Who Should Read This Book? . 11 What’s in This Book? 12 What’s New in the Third Edition? . 12 Online Resources 14 Fast-Forward >> 14 I Introducing Android 16 1 Quick Start 17 1.1 Installing the Tools . 17 1.2 Creating Your First Program 23 1.3 Running on the Emulator . 23 1.4 Running on a Real Phone . 28 1.5 Fast-Forward >> . 29 2 Key Concepts 30 2.1 The Big Picture . 30 2.2 It’s Alive! . 35 2.3 Building Blocks . 39 2.4 Using Resources 40 2.5 Safe and Secure . 40 2.6 Fast-Forward >> . 41 CONTENTS 6 II Android Basics 42 3 Designing the User Interface 43 3.1 Introducing the Sudoku Example . 43 3.2 Designing by Declaration . 44 3.3 Creating the Opening Screen . 45 3.4 Using Alternate Resources . 55 3.5 Implementing an About Box 57 3.6 Applying a Theme 61 3.7 Adding a Menu . 64 3.8 Adding Settings . 65 3.9 Starting a New Game 66 3.10 Debugging 69 3.11 Exiting the Game 71 3.12 Fast-Forward >> . 71 4 Exploring 2D Graphics 73 4.1 Learning the Basics . 73 4.2 Adding Graphics to Sudoku 78 4.3 Handling Input . 87 4.4 The Rest of the Story 93 4.5 Making More Improvements 103 4.6 Fast-Forward >> . 103 5 Multimedia 105 5.1 Playing Audio 105 5.2 Playing Video 112 5.3 Adding Sounds to Sudoku . 115 5.4 Fast-Forward >> . 119 6 Storing Local Data 120 6.1 Adding Options to Sudoku . 120 6.2 Continuing an Old Game . 122 6.3 Remembering the Current Position 124 6.4 Accessing the Internal File System 126 6.5 Accessing SD Cards 127 6.6 Fast-Forward >> . 128 CONTENTS 7 III Beyond the Basics 129 7 The Connected World 130 7.1 Browsing by Intent . 131 7.2 Web with a View . 135 7.3 From JavaScript to Java and Back 140 7.4 Using Web Services . 147 7.5 Fast-Forward >> . 160 8 Locating and Sensing 161 8.1 Location, Location, Location 161 8.2 Set Sensors to Maximum . 168 8.3 Bird’s-Eye View . 172 8.4 Fast-Forward >> . 177 9 Putting SQL to Work 178 9.1 Introducing SQLite . 178 9.2 SQL 101 . 179 9.3 Hello, Database . 181 9.4 Data Binding . 189 9.5 Using a ContentProvider 192 9.6 Implementing a ContentProvider . 195 9.7 Fast-Forward >> . 196 10 3D Graphics in OpenGL 198 10.1 Understanding 3D Graphics 198 10.2 Introducing OpenGL 199 10.3 Building an OpenGL Program . 200 10.4 Rendering the Scene 202 10.5 Building a Model 206 10.6 Lights, Camera, 209 10.7 Action! 212 10.8 Applying Texture 212 10.9 Peekaboo . 216 10.10 Measuring Smoothness 217 10.11 Fast-Forward >> . 218 CONTENTS 8 IV The Next Generation 219 11 Multi-Touch 220 11.1 Introducing Multi-Touch 220 11.2 Building the Touch Example . 222 11.3 Understanding Touch Events . 225 11.4 Setting Up for Image Transformation 228 11.5 Implementing the Drag Gesture 229 11.6 Implementing the Pinch Zoom Gesture . 230 11.7 Fast-Forward >> . 232 12 There’s No Place Like Home 233 12.1 Hello, Widget . 233 12.2 Live Wallpaper 242 12.3 Fast-Forward >> . 254 13 Write Once, Test Everywhere 256 13.1 Gentlemen, Start Your Emulators 257 13.2 Building for Multiple Versions . 257 13.3 Evolving with Android APIs 259 13.4 Bug on Parade 265 13.5 All Screens Great and Small 267 13.6 Installing on the SD Card . 268 13.7 Fast-Forward >> . 270 14 Publishing to the Android Market 271 14.1 Preparing . 271 14.2 Signing 272 14.3 Publishing 273 14.4 Updating . 275 14.5 Closing Thoughts 276 V Appendixes 277 A Java vs. the Android Language and APIs 278 A.1 Language Subset 278 A.2 Standard Library Subset 280 A.3 Third-Party Libraries 281 B Bibliography 282 Index 283 Preface Android is an open source software toolkit for mobile phones that was created by Google and the Open Handset Alliance. It’s inside millions of cell phones and other mobile devices, making Android a major platform for application developers. Whether you’re a hobbyist or a professional programmer, whether you are doing it for fun or for profit, it’s time to learn more about developing for Android. This book will help you get started. What Makes Android Special? There are already many mobile platforms on the market today, including Symbian, iPhone, Windows Mobile, BlackBerry, Java Mobile Edition, Linux Mobile (LiMo), and more. When I tell people about Android, their first question is often, Why do we need another mobile standard? Where’s the “wow”? Although some of its features have appeared before, Android is the first environment that combines the following: ã A truly open, free development platform based on Linux and open source: Handset makers like it because they can use and customize the platform without paying a royalty. Developers like it because they know that the platform “has legs” and is not locked into any one vendor that may go under or be acquired. ã A component-based architecture inspired by Internet mashups: Parts of one application can be used in another in ways not originally envisioned by the developer. You can even replace built-in components with your own improved versions. This will unleash a new round of creativity in the mobile space. ã Tons of built-in services out of the box: Location-based services use GPS or cell tower triangulation to let you customize the user experience depending on where you are. A full-powered SQL database WHO SHOULD READ THIS BOOK? 11 lets you harness the power of local storage for occasionally connected computing and synchronization. Browser and map views can be embedded directly in your applications. All these built-in capabilities help raise the bar on functionality while lowering your development costs. ã Automatic management of the application life cycle: Programs are isolated from each other by multiple layers of security, which will provide a level of system stability not seen before in smart phones. The end user will no longer have to worry about what applications are active or close some programs so that others can run. Android is optimized for low-power, low-memory devices in a fundamental way that no previous platform has attempted. ã High-quality graphics and sound: Smooth, antialiased 2D vector graphics and animation inspired by Flash are melded with 3Daccelerated OpenGL graphics to enable new kinds of games and business applications. Codecs for the most common industrystandard audio and video formats are built right in, including H.264 (AVC), MP3, and AAC. ã Portability across a wide range of current and future hardware: All your programs are written in Java and executed by Android’s Dalvik virtual machine, so your code will be portable across ARM, x86, and other architectures. Support for a variety of input methods is included such as keyboard, touch, and trackball. User interfaces can be customized for any screen resolution and orientation. Android offers a fresh take on the way mobile applications interact with users, along with the technical underpinnings to make it possible. But the best part of Android is the software that you are going to write for it. This book will help you get off to a great start. Who Should Read This Book? The only requirement is a basic understanding of programming in Java or a similar object-oriented language (C# will do in a pinch). You don’t need any prior experience developing software for mobile devices. In fact, if you do, it’s probably best if you try to forget that experience. Android is so different that it’s good to start with an open mind. WHAT’S IN THIS BOOK? 12 What’s in This Book? Hello, Android is divided into four parts. Roughly speaking, the book progresses from less advanced to more advanced topics, or from more common to less common aspects of Android. Several chapters share a common example: an Android Sudoku game. By gradually adding features to the game, you’ll learn about many aspects of Android programming including user interfaces, multimedia, and the Android life cycle. In Part I, we’ll start with an introduction to Android. This is where you’ll learn how to install the Android emulator and how to use an integrated development environment (IDE) to write your first program. Then we’ll introduce a few key concepts like the Android life cycle. Programming in Android is a little different from what you’re probably used to, so make sure you get these concepts before moving on. Part II talks about Android’s user interface, two-dimensional graphics, multimedia components, and simple data access. These features will be used in most programs you write. Part III digs deeper into the Android platform. Here you’ll learn about connecting to the outside world, location-based services, the built-in SQLite database, and three-dimensional graphics. Part IV wraps things up with a discussion on using advanced input techniques including multi-touch and extending your home screen with widgets and live wallpaper. Finally, we’ll explore making your app compatible with multiple Android devices and versions and then publishing it on the Android Market. At the end of the book, you’ll find an appendix that covers the differences between Android and Java Standard Edition (SE), along with a bibliography. What’s New in the Third Edition? The third edition has been updated to support all versions of Android from 1.5 through 2.2 and beyond. Here’s a summary of the new features introduced in each version and the corresponding sections that cover those features. WHAT’S NEW IN THE THIRD EDITION? 13 New for Cupcake Android 1.5 (Cupcake) introduced a large number of enhancements to the Android platform including support for soft (onscreen) keyboards, video recording, and application widgets. Under the covers, there were more than 1,000 changes to the Android API between 1.1 and 1.5.1 Widgets are covered in Section 12.1, Hello, Widget, on page 233. New for Donut Android 1.6 (Donut) added support for high- and low-density displays, plus a number of minor changes that don’t affect most developers.2 You can learn how to support these different device form factors in Section 13.5, All Screens Great and Small, on page 267. New for Eclair Android 2.0 (Eclair) added support for multi-touch, virtual keys, centralized account management, synchronization APIs, docking, HTML5, and more.3 The 2.0 version was quickly replaced by Android 2.0.1 (also called Eclair), which contains all the changes in the 2.0 version plus a few bug fixes.4 Multi-touch is covered in Chapter 11, Multi-Touch, on page 220. New for Eclair MR1 Android 2.1 (Eclair Maintenance Release 1) added support for live wallpapers, more HTML5 support, and other minor improvements.5 Home screen enhancements, including live wallpapers and widgets, are covered in Chapter 12, There’s No Place Like Home, on page 233. New for FroYo and Beyond Android 2.2 (FroYo) supports application installation on external storage (SD cards), a much faster Java virtual machine, OpenGL ES 2.0 APIs, and more.6 Section 13.6, Installing on the SD Card, on page 268 explains how to set up your program to install on external storage and when you should and shouldn’t do that. 1. http://d.android.com/sdk/api_diff/3/changes.html 2. http://d.android.com/sdk/api_diff/4/changes.html 3. http://d.android.com/sdk/api_diff/5/changes.html 4. http://d.android.com/sdk/api_diff/6/changes.html 5. http://d.android.com/sdk/api_diff/7/changes.html 6. http://d.android.com/sdk/api_diff/8/changes.html ONLINE RESOURCES 14 Android 1.5 (or newer) is now available for all shipping Android devices. All new devices have it installed, and Google says that almost all older devices have upgraded. See the Android Device Dashboard7 for the latest market share of active Android devices in the wild. This edition of the book does not cover version 1.1 or earlier. Note: It may be a while before all devices are upgraded to the latest version of Android (if ever), so Chapter 13, Write Once, Test Everywhere, on page 256 covers how to create a single program that supports multiple versions. All the examples in this book have been tested on versions 1.5 through 2.2. Online Resources At the website for this book (http://pragprog.com/titles/eband3), you’ll find the following: ã The full source code for all the sample programs used in this book ã An errata page, listing any mistakes in the current edition (let’s hope that will be empty!) ã A discussion forum where you can communicate directly with the author and other Android developers (let’s hope that will be full!) You are free to use the source code in your own applications as you see fit. Note: If you’re reading the ebook, you can also click the little gray rectangle before the code listings to download that source file directly. Fast-Forward >> Although most authors expect you to read every word in their books, I know you’re not going to do that. You want to read just enough to let you get something done, and then maybe you’ll come back later and read something else to let you get another piece done. So, I’ve tried to provide you with a little help so you won’t get lost. Each chapter in this book ends with a “Fast-Forward >>” section. These sections will provide some guidance for where you should go next when you need to read the book out of order. You’ll also find pointers to other resources such as books and online documentation here in case you want to learn more about the subject. 7. http://d.android.com/resources/dashboard/platform-versions.html FAST -FORWARD >> 15 So, what are you waiting for? The next chapter—Chapter 1, Quick Start, on page 17—drops you right into the deep end with your first Android program. Chapter 2, Key Concepts, on page 30 takes a step back and introduces you to the basic concepts and philosophy of Android, and Chapter 3, Designing the User Interface, on page 43 digs into the user interface, which will be the most important part of most Android programs. Your ultimate goal will be to make your apps available for sale or free download in the Android Market. When you’re ready, Chapter 14, Publishing to the Android Market, on page 271 will show you how to take that final step.