Android App Development

ffirs.indd ii

25/01/12 8:34 AM

BEGINNING ANDROID™ 4 APPLICATION DEVELOPMENT INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi CHAPTER 1

Getting Started with Android Programming . . . . . . . . . . . . . . . . . . . . . . . . . 1


Activities, Fragments, and Intents. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35


Getting to Know the Android User Interface. . . . . . . . . . . . . . . . . . . . . . 105


Designing Your User Interface with Views . . . . . . . . . . . . . . . . . . . . . . . 159


Displaying Pictures and Menus with Views. . . . . . . . . . . . . . . . . . . . . . . 219


Data Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251


Content Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293


Messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321


Location-Based Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351


Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393


Developing Android Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429


Publishing Android Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463


Using Eclipse for Android Development . . . . . . . . . . . . . . . . . . . . . . . . . 483


Using the Android Emulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499


Answers to Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521

ffirs.indd i

25/01/12 8:34 AM

ffirs.indd ii

25/01/12 8:34 AM


Android™ 4 Application Development

ffirs.indd iii

25/01/12 8:34 AM

ffirs.indd iv

25/01/12 8:34 AM


Android™ 4 Application Development Wei-Meng Lee

John Wiley & Sons, Inc.

ffirs.indd v

25/01/12 8:34 AM

Beginning Android™ 4 Application Development Published by John Wiley & Sons, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 Copyright © 2012 by John Wiley & Sons, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-1-118-19954-1 ISBN: 978-1-118-22824-1 (ebk) ISBN: 978-1-118-24067-0 (ebk) ISBN: 978-1-118-26538-3 (ebk) Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read. For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http:// For more information about Wiley products, visit Library of Congress Control Number: 2011945560 Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affi liates, in the United States and other countries, and may not be used without written permission. Android is a trademark of Google, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.

ffirs.indd vi

25/01/12 8:34 AM

To my family: Thanks for the understanding and support while I worked on getting this book ready. I love you all!

ffirs.indd vii

25/01/12 8:34 AM

ffirs.indd viii

25/01/12 8:34 AM


WEI-MENG LEE is a technologist and founder of Developer Learning Solutions (www.learn2develop .net), a technology company specializing in hands-on training on the latest mobile technologies.

Wei-Meng has many years of training experience and his training courses place special emphasis on the learning-by-doing approach. This hands-on approach to learning programming makes understanding the subject much easier than reading books, tutorials, and other documentation. Wei-Meng is also the author of Beginning iOS 5 Application Development (Wrox, 2010) and Beginning Android Application Development (Wrox, 2011). Contact Wei-Meng at [email protected]


CHAIM KRAUSE is a Simulation Specialist at the US Army’s Command and General Staff College

where he develops various software products on a multitude of platforms, from iOS and Android devices to Windows desktops and Linux servers, among other duties. Python is his preferred language, but he is multilingual and also codes in Java and JavaScript/HTML5/CSS, and others. He was fortunate to begin his professional career in the software field at Borland where he was a Senior Developer Support Engineer for Delphi. Outside of computer geek stuff, Chaim enjoys techno and dubstep music and scootering with his two sled dogs, Dasher and Minnie.

ffirs.indd ix

25/01/12 8:34 AM

ffirs.indd x

25/01/12 8:34 AM




Robert Elliott

Tim Tate



Ami Sullivan




Neil Edde


Jim Minatel


Katie Crocker



David Mayhew

ffirs.indd xi

Nancy Carassco INDEXER

Johnna VanHoose Dinse



Ashley Zurcher

Ryan Sneed



Amy Knies

© Viktoriya Sukhanova / iStockPhoto

25/01/12 8:34 AM

ffirs.indd xii

25/01/12 8:34 AM


WRITING THIS BOOK HAS been a roller-coaster ride. Working with just-released software is always

a huge challenge. When I fi rst started working on this book, the Android 4 SDK had just been released; and wading through the documentation was like fi nding a needle in a haystack. To add to the challenge, the Android emulator for the tablet is extremely slow and unstable, making the development process very laborious. Now that the book is done, I hope your journey will not be as eventful as mine. Like any good guide, my duty is to make your foray into Android tablet development an enjoyable and fruitful experience. The book you are now holding is the result of the collaborative efforts of many people, and I wish to take this opportunity to acknowledge them here. First, my personal gratitude to Bob Elliott, executive editor at Wrox. Bob is always ready to lend a listening ear and to offer help when it’s needed. It is a great pleasure to work with Bob, as he is one of the most responsive persons I have ever worked with! Thank you, Bob, for the help and guidance! Of course, I cannot forget Ami Sullivan, my editor (and friend!), who is always a pleasure to work with. After working together on four books, we now know each other so well that we know the content of incoming e-mail messages even before we open them! Thank you, Ami! Nor can I forget the heroes behind the scenes: copyeditor Luann Rouff and technical editor Chaim Krause. They have been eagle-eye editing the book, making sure that every sentence makes sense — both grammatically and technically. Thanks, Luann and Chaim! Last, but not least, I want to thank my parents and my wife, Sze Wa, for all the support they have given me. They have selflessly adjusted their schedules to accommodate my busy schedule when I was working on this book. My wife, as always, has stayed up with me on numerous nights as I was furiously working to meet the deadlines, and for this I would like to say to her and my parents, “I love you all!” Finally, to our lovely dog, Ookii, thanks for staying by our side.

ffirs.indd xiii

25/01/12 8:34 AM

ffirs.indd xiv

25/01/12 8:34 AM



What Is Android? Android Versions Features of Android Architecture of Android Android Devices in the Market The Android Market The Android Developer Community

Obtaining the Required Tools Android SDK Installing the Android SDK Tools Configuring the Android SDK Manager Eclipse Android Development Tools (ADT) Creating Android Virtual Devices (AVDs)

Creating Your First Android Application Anatomy of an Android Application Summary CHAPTER 2: ACTIVITIES, FRAGMENTS, AND INTENTS

Understanding Activities Applying Styles and Themes to an Activity Hiding the Activity Title Displaying a Dialog Window Displaying a Progress Dialog Displaying a More Sophisticated Progress Dialog

Linking Activities Using Intents Resolving Intent Filter Collision Returning Results from an Intent Passing Data Using an Intent Object

Fragments Adding Fragments Dynamically Life Cycle of a Fragment Interactions between Fragments

ftoc.indd xv

xxi 1

2 2 3 4 6 8 9

9 10 11 12 14 15 17

20 29 33 35

36 41 41 42 47 50

53 58 59 63

69 73 76 80

25/01/12 8:35 AM


Calling Built-In Applications Using Intents Understanding the Intent Object Using Intent Filters Adding Categories


Understanding the Components of a Screen Views and ViewGroups LinearLayout AbsoluteLayout TableLayout RelativeLayout FrameLayout ScrollView

Adapting to Display Orientation Anchoring Views Resizing and Repositioning

85 89 91 96

98 103 105

105 106 107 115 116 117 118 121

123 125 127

Managing Changes to Screen Orientation


Persisting State Information during Changes in Configuration Detecting Orientation Changes Controlling the Orientation of the Activity

133 135 135

Utilizing the Action Bar Adding Action Items to the Action Bar Customizing the Action Items and Application Icon

Creating the User Interface Programmatically Listening for UI Notifications Overriding Methods Defined in an Activity Registering Events for Views


Using Basic Views TextView View Button, ImageButton, EditText, CheckBox, ToggleButton, RadioButton, and RadioGroup Views ProgressBar View AutoCompleteTextView View

Using Picker Views

136 139 144

146 148 149 152

156 159

160 160 161 171 177



ftoc.indd xvi

25/01/12 8:35 AM


TimePicker View DatePicker View

Using List Views to Display Long Lists ListView View Using the Spinner View

Understanding Specialized Fragments Using a ListFragment Using a DialogFragment Using a PreferenceFragment


Using Image Views to Display Pictures Gallery and ImageView Views ImageSwitcher GridView

Using Menus with Views Creating the Helper Methods Options Menu Context Menu

Some Additional Views AnalogClock and DigitalClock Views WebView


Saving and Loading User Preferences Accessing Preferences Using an Activity Programmatically Retrieving and Modifying the Preferences Values Changing the Default Name of the Preferences File

Persisting Data to Files Saving to Internal Storage Saving to External Storage (SD Card) Choosing the Best Storage Option Using Static Resources

Creating and Using Databases Creating the DBAdapter Helper Class Using the Database Programmatically Pre-Creating the Database


179 184

191 191 199

202 202 207 210

214 219

219 220 226 231

234 235 238 240

242 242 243

249 251

251 252 259 261

263 263 268 271 272

273 273 279 285

289 xvii

ftoc.indd xvii

25/01/12 8:35 AM



Sharing Data in Android Using a Content Provider Predefined Query String Constants Projections Filtering Sorting

Creating Your Own Content Providers Using the Content Provider Summary CHAPTER 8: MESSAGING

SMS Messaging Sending SMS Messages Programmatically Getting Feedback after Sending a Message Sending SMS Messages Using Intent Receiving SMS Messages Caveats and Warnings


Displaying Maps Creating the Project Obtaining the Maps API Key Displaying the Map Displaying the Zoom Control Changing Views Navigating to a Specific Location Adding Markers Getting the Location That Was Touched Geocoding and Reverse Geocoding

Getting Location Data Monitoring a Location Project — Building a Location Tracker Summary CHAPTER 10: NETWORKING

Consuming Web Services Using HTTP Downloading Binary Data


293 294 300 303 304 305

305 314 319 321

321 322 325 328 329 344

345 347 351

352 352 353 355 358 361 363 366 369 371

375 384 385 390 393

393 396


ftoc.indd xviii

25/01/12 8:35 AM


Downloading Text Content Accessing Web Services Using the GET Method

Consuming JSON Services Sockets Programming Summary CHAPTER 11: DEVELOPING ANDROID SERVICES

Creating Your Own Services

402 404

409 417 426 429


Performing Long-Running Tasks in a Service 433 Performing Repeated Tasks in a Service 439 Executing Asynchronous Tasks on Separate Threads Using IntentService 442

Establishing Communication between a Service and an Activity Binding Activities to Services Understanding Threading Summary

445 449 454 460



Preparing for Publishing Versioning Your Application Digitally Signing Your Android Applications

Deploying APK Files Using the adb.exe Tool Using a Web Server Publishing on the Android Market


Getting Around in Eclipse Workspaces Package Explorer Using Projects from Other Workspaces Using Editors within Eclipse Understanding Eclipse Perspectives Automatically Importing Packages Using the Code Completion Feature Refactoring

Debugging your Application Setting Breakpoints Dealing with Exceptions

463 464 466

471 471 474 476

481 483

483 483 485 486 487 490 490 491 492

494 495 497


ftoc.indd xix

25/01/12 8:35 AM




Uses of the Android Emulator Creating Snapshots SD Card Emulation Emulating Devices with Different Screen Sizes Emulating Physical Capabilities Sending SMS Messages to the Emulator Making Phone Calls Transferring Files into and out of the Emulator Resetting the Emulator

499 501 502 504 506 508 509 511 513






ftoc.indd xx

25/01/12 8:35 AM


I FIRST STARTED PLAYING WITH THE ANDROID SDK before it was officially released as version 1.0.

Back then, the tools were unpolished, the APIs in the SDK were unstable, and the documentation was sparse. Fast-forward three and a half years, Android is now a formidable mobile operating system, with a following no less impressive than the iPhone. Having gone through all the growing pains of Android, I think now is the best time to start learning about Android programming — the APIs have stabilized, and the tools have improved. One challenge remains, however: Getting started is still an elusive goal for many. What’s more, Google has recently released their latest version of the Android SDK — 4.0, a unified mobile OS for both smartphones and tablets. The Android 4.0 SDK includes several new features for tablet developers, and understanding all these new features requires some effort on the part of beginners. It was with this challenge in mind that I was motivated to write this book, one that could benefit beginning Android programmers and enable them to write progressively more sophisticated applications. As a book written to help jump-start beginning Android developers, it covers the necessary topics in a linear manner so that you can build on your knowledge without being overwhelmed by the details. I adopt the philosophy that the best way to learn is by doing — hence, the numerous Try It Out sections in each chapter, which first show you how to build something and then explain how everything works. I have also taken this opportunity to further improve the previous edition of this book, addressing feedback from readers and adding additional topics that are important to beginning Android developers. Although Android programming is a huge topic, my aim for this book is threefold: to get you started with the fundamentals, to help you understand the underlying architecture of the SDK, and to appreciate why things are done in certain ways. It is beyond the scope of any book to cover everything under the sun related to Android programming, but I am confident that after reading this book (and doing the exercises), you will be well equipped to tackle your next Android programming challenge.

WHO THIS BOOK IS FOR This book is targeted for the beginning Android developer who wants to start developing applications using Google’s Android SDK. To truly benefit from this book, you should have some background in programming and at least be familiar with object-oriented programming concepts. If you are totally new to Java — the language used for Android development — you might want to take a programming course in Java programming first, or grab one of many good books on Java programming. In my experience, if you already know C# or VB.NET, learning Java is not too much of an effort; you should be comfortable just following along with the Try It Outs. For those totally new to programming, I know the lure of developing mobile apps and making some money is tempting. However, before attempting to try out the examples in this book, I think a better starting point would be to learn the basics of programming fi rst.

flast.indd xxi

25/01/12 8:35 AM


NOTE All the examples discussed in this book were written and tested using version 4.0 of the Android SDK. While every effort is made to ensure that all the tools used in this book are the latest, it is always possible that by the time you read this book, a newer version of the tools may be available. If so, some of the instructions and/or screenshots may differ slightly. However, any variations should be manageable.

WHAT THIS BOOK COVERS This book covers the fundamentals of Android programming using the Android SDK. It is divided into 12 chapters and three appendixes. Chapter 1: Getting Started with Android Programming covers the basics of the Android OS and its current state. You will learn about the features of Android devices, as well as some of the popular devices on the market. You will also learn how to download and install all the required tools to develop Android applications and then test them on the Android emulator. Chapter 2: Activities, Fragments, and Intents gets you acquainted with these three fundamental concepts in Android programming. Activities and fragments are the building blocks of an Android application. You will learn how to link activities together to form a complete Android application using intents, one of the unique characteristics of the Android OS. Chapter 3: Getting to Know the Android User Interface covers the various components that make up the UI of an Android application. You will learn about the various layouts you can use to build the UI of your application, and the numerous events that are associated with the UI when users interact with the application. Chapter 4: Designing Your User Interface with Views walks you through the various basic views you can use to build your Android UI. You will learn three main groups of views: basic views, picker views, and list views. You will also learn about the specialized fragments available in Android 3.0 and 4.0. Chapter 5: Displaying Pictures and Menus with Views continues the exploration of views. Here, you will learn how to display images using the various image views, as well as display options and context menus in your application. This chapter ends with some additional cool views that you can use to spice up your application. Chapter 6: Data Persistence shows you how to save, or store, data in your Android application. In addition to learning the various techniques to store user data, you will also learn file manipulation and how to save fi les onto internal and external storage (SD card). In addition, you will learn how to create and use a SQLite database in your Android application.


flast.indd xxii

25/01/12 8:35 AM


Chapter 7: Content Providers discusses how data can be shared among different applications on an Android device. You will learn how to use a content provider and then build one yourself. Chapter 8: Messaging explores two of the most interesting topics in mobile programming — sending SMS messages and e-mail. You will learn how to programmatically send and receive SMS and e-mail messages, and how to intercept incoming SMS messages so that the built-in Messaging application will not be able to receive any messages. Chapter 9: Location-Based Services demonstrates how to build a location-based service application using Google Maps. You will also learn how to obtain geographical location data and then display the location on the map. Chapter 10: Networking explores how to connect to web servers to download data. You will see how XML and JSON web services can be consumed in an Android application. This chapter also explains sockets programming, and you will learn how to build a chat client in Android. Chapter 11: Developing Android Services demonstrates how you can write applications using services. Services are background applications that run without a UI. You will learn how to run your services asynchronously on a separate thread, and how your activities can communicate with them. Chapter 12: Publishing Android Applications discusses the various ways you can publish your Android applications when you are ready. You will also learn about the necessary steps to publishing and selling your applications on the Android Market. Appendix A: Using Eclipse for Android Development provides a brief overview of the many features in Eclipse. Appendix B: Using the Android Emulator provides some tips and tricks on using the Android emulator for testing your applications. Appendix C: Answers to Exercises contains the solutions to the end-of-chapter exercises found in every chapter.

HOW THIS BOOK IS STRUCTURED This book breaks down the task of learning Android programming into several smaller chunks, enabling you to digest each topic before delving into a more advanced one. If you are a total beginner to Android programming, start with Chapter 1 fi rst. Once you have familiarized yourself with the basics, head over to the appendixes to read more about Eclipse and the Android emulator. When you are ready, continue with Chapter 2 and gradually move into more advanced topics. A feature of this book is that all the code samples in each chapter are independent of those discussed in previous chapters. This gives you the flexibility to dive into the topics that interest you and start working on the Try It Out projects.


flast.indd xxiii

25/01/12 8:35 AM


WHAT YOU NEED TO USE THIS BOOK All the examples in this book run on the Android emulator (which is included as part of the Android SDK). However, to get the most out of this book, having a real Android device would be useful (though not absolutely necessary).

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


These Are Exercises or Examples for You to Follow

The Try It Out sections appear once or more per chapter. These are exercises to work through as you follow the related discussion in the text.

1. 2.

They consist of a set of numbered steps. Follow the steps with your copy of the project files.

How It Works After each Try It Out, the code you’ve typed is explained in detail. As for other conventions in the text: ➤

New terms and important words are highlighted in italics when first introduced.

Keyboard combinations are treated like this: Ctrl+R.

Filenames, URLs, and code within the text are treated like so:

Code is presented in two different ways: We use a monofont type with no highlighting for most code examples. We use bolding to emphasize code that is of particular importance in the present context.

NOTE Notes, tips, hints, tricks, and asides to the current discussion look like this.


flast.indd xxiv

25/01/12 8:35 AM


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 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. You’ll fi nd the fi lename of the project you need in a CodeNote such as this at the beginning of the Try it Out features: code snippet filename

After you download the code, just decompress it with your favorite compression tool. Alternatively, go to the main Wrox code download page at to see the code available for this book and for all other Wrox books.

NOTE Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-1-118-19954-1.

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 fi nd an error in one of our books, such as 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 help us provide even higher-quality information. To fi nd the errata page for this book, go to 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.

NOTE A complete book list, including links to each book’s errata, is also available at

If you don’t spot “your” error on the Book Errata page, go to 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.


flast.indd xxv

25/01/12 8:35 AM


P2P.WROX.COM For author and peer discussion, join the P2P forums at The forums are a web-based system for you to post messages relating to Wrox books and related technologies and to interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums. At, you will fi nd a number of different forums that will help you not only as you read this book but also as you develop your own applications. To join the forums, just follow these steps:

1. 2. 3. 4.

Go to and click the Register link. Read the terms of use and click Agree. Complete the required information to join as well as any optional information you want to provide and click Submit. You will receive an e-mail with information describing how to verify your account and complete the joining process.

NOTE You can read messages in the forums without joining P2P, but in order to post your own messages, you must join.

After you join, you can post new messages and respond to messages that other users post. You can read messages at any time on the web. If you want to have new messages from a particular forum e-mailed to you, click the Subscribe to This Forum icon by the forum name in the forum listing. For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works, as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.


flast.indd xxvi

25/01/12 8:35 AM

1 Getting Started with Android Programming WHAT YOU WILL LEARN IN THIS CHAPTER ➤

What is Android?

Android versions and its feature set

The Android architecture

The various Android devices on the market

The Android Market application store

How to obtain the tools and SDK for developing Android applications

How to develop your first Android application

Welcome to the world of Android! When I was writing my fi rst book on Android (which was just less than a year ago), I stated that Android was ranked second in the U.S. smartphone market, second to Research In Motion’s (RIM) BlackBerry, and overtaking Apple’s iPhone. Shortly after the book went to press, comScore (a global leader in measuring the digital world and the preferred source of digital marketing intelligence) reported that Android has overtaken BlackBerry as the most popular smartphone platform in the U.S. A few months later, Google released Android 3.0, code named Honeycomb. With Android 3.0, Google’s focus in the new Software Development Kit was the introduction of several new features

c01.indd 1

25/01/12 1:04 PM



designed for widescreen devices, specifically tablets. If you are writing apps for Android smartphones, Android 3.0 is not really useful, as the new features are not supported on smartphones. At the same time that Android 3.0 was released, Google began working on the next version of Android, which can be used on both smartphones and tablets. In October 2011, Google released Android 4.0, code named Ice Cream Sandwich, and that is the focus of this book. In this chapter you will learn what Android is, and what makes it so compelling to both developers and device manufacturers alike. You will also get started with developing your fi rst Android application, and learn how to obtain all the necessary tools and set them up so that you can test your application on an Android 4.0 emulator. By the end of this chapter, you will be equipped with the basic knowledge you need to explore more sophisticated techniques and tricks for developing your next killer Android application.

WHAT IS ANDROID? Android is a mobile operating system that is based on a modified version of Linux. It was originally developed by a startup of the same name, Android, Inc. In 2005, as part of its strategy to enter the mobile space, Google purchased Android and took over its development work (as well as its development team). Google wanted Android to be open and free; hence, most of the Android code was released under the open source Apache License, which means that anyone who wants to use Android can do so by downloading the full Android source code. Moreover, vendors (typically hardware manufacturers) can add their own proprietary extensions to Android and customize Android to differentiate their products from others. This simple development model makes Android very attractive and has thus piqued the interest of many vendors. This has been especially true for companies affected by the phenomenon of Apple’s iPhone, a hugely successful product that revolutionized the smartphone industry. Such companies include Motorola and Sony Ericsson, which for many years have been developing their own mobile operating systems. When the iPhone was launched, many of these manufacturers had to scramble to find new ways of revitalizing their products. These manufacturers see Android as a solution — they will continue to design their own hardware and use Android as the operating system that powers it. The main advantage of adopting Android is that it offers a unified approach to application development. Developers need only develop for Android, and their applications should be able to run on numerous different devices, as long as the devices are powered using Android. In the world of smartphones, applications are the most important part of the success chain. Device manufacturers therefore see Android as their best hope to challenge the onslaught of the iPhone, which already commands a large base of applications.

Android Versions Android has gone through quite a number of updates since its fi rst release. Table 1-1 shows the various versions of Android and their codenames.

c01.indd 2

25/01/12 1:04 PM

What Is Android?

❘ 3

TABLE 1-1: A Brief History of Android Versions ANDROID VERSION




9 February 2009


30 April 2009



15 September 2009



26 October 2009



20 May 2010



6 December 2010



22 February 2011



19 October 2011

Ice Cream Sandwich

In February 2011, Google released Android 3.0, a tablet-only release supporting widescreen devices. The key changes in Android 3.0 are as follows. ➤

New user interface optimized for tablets

3D desktop with new widgets

Refined multi-tasking

New web browser features, such as tabbed browsing, form auto-fill, bookmark synchronization, and private browsing

Support for multi-core processors

Applications written for versions of Android prior to 3.0 are compatible with Android 3.0 devices, and they run without modifications. Android 3.0 tablet applications that make use of the newer features available in 3.0, however, will not be able to run on older devices. To ensure that an Android tablet application can run on all versions of devices, you must programmatically ensure that you only make use of features that are supported in specific versions of Android. In October 2011, Google released Android 4.0, a version that brought all the features introduced in Android 3.0 to smartphones, along with some new features such as facial recognition unlock, data usage monitoring and control, Near Field Communication (NFC), and more.

Features of Android Because Android is open source and freely available to manufacturers for customization, there are no fixed hardware or software configurations. However, Android itself supports the following features:

c01.indd 3

Storage — Uses SQLite, a lightweight relational database, for data storage. Chapter 6 discusses data storage in more detail.

Connectivity — Supports GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth (includes A2DP and AVRCP), Wi-Fi, LTE, and WiMAX. Chapter 8 discusses networking in more detail.

25/01/12 1:04 PM



Messaging — Supports both SMS and MMS. Chapter 8 discusses messaging in more detail.

Web browser — Based on the open source WebKit, together with Chrome’s V8 JavaScript engine

Media support — Includes support for the following media: H.263, H.264 (in 3GP or MP4 container), MPEG-4 SP, AMR, AMR-WB (in 3GP container), AAC, HE-AAC (in MP4 or 3GP container), MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP

Hardware support — Accelerometer Sensor, Camera, Digital Compass, Proximity Sensor, and GPS

Multi-touch — Supports multi-touch screens

Multi-tasking — Supports multi-tasking applications

Flash support — Android 2.3 supports Flash 10.1.

Tethering — Supports sharing of Internet connections as a wired/wireless hotspot

Architecture of Android In order to understand how Android works, take a look at Figure 1-1, which shows the various layers that make up the Android operating system (OS). The Android OS is roughly divided into five sections in four main layers:

c01.indd 4

Linux kernel — This is the kernel on which Android is based. This layer contains all the lowlevel device drivers for the various hardware components of an Android device.

Libraries — These contain all the code that provides the main features of an Android OS. For example, the SQLite library provides database support so that an application can use it for data storage. The WebKit library provides functionalities for web browsing.

Android runtime — At the same layer as the libraries, the Android runtime provides a set of core libraries that enable developers to write Android apps using the Java programming language. The Android runtime also includes the Dalvik virtual machine, which enables every Android application to run in its own process, with its own instance of the Dalvik virtual machine (Android applications are compiled into Dalvik executables). Dalvik is a specialized virtual machine designed specifically for Android and optimized for battery-powered mobile devices with limited memory and CPU.

Application framework — Exposes the various capabilities of the Android OS to application developers so that they can make use of them in their applications.

Applications — At this top layer, you will find applications that ship with the Android device (such as Phone, Contacts, Browser, etc.), as well as applications that you download and install from the Android Market. Any applications that you write are located at this layer.

25/01/12 1:04 PM

c01.indd 5

25/01/12 1:04 PM


Contacts Phone

FreeType SSL

Camera Driver Wi-Fi Driver


Display Driver Keypad Driver




Audio Drivers


Power Management

Binder (IPC) Driver

Dalvik Virtual Machine

Core Libraries


Notification Manager

View System

Location Manager


Flash Memory Driver


Media Framework

Surface Manager


Resource Manager

Content Providers


Telephony Manager

Activity Manager Package Manager





Android Devices in the Market Android devices come in all shapes and sizes. As of late November 2011, the Android OS powers the following types of devices: ➤



E-reader devices


MP4 players

Internet TVs

Chances are good that you own at least one of the preceding devices. Figure 1-2 shows (left to right) the Samsung Galaxy S II, the Motorola Atrix 4G, and the HTC EVO 4G smartphones.


Another popular category of devices that manufacturers are rushing out is the tablet. Tablets typically come in two sizes: seven inches and ten inches, measured diagonally. Figure 1-3 shows the Samsung Galaxy Tab 10.1 (left) and the Asus Eee Pad Transformer TF101 (right), both 10.1-inch tablets. Both the Samsung Galaxy 10.1 and the Asus Eee Pad Transfer TF101 run on Android 3.

c01.indd 6

25/01/12 1:04 PM

What Is Android?

❘ 7


Besides smartphones and tablets, Android is also beginning to appear in dedicated devices, such as e-book readers. Figure 1-4 shows the Barnes and Noble’s NOOK Color (left) and Amazon’s Kindle Fire (right), both of which are color e-Book readers running the Android OS.


In addition to these popular mobile devices, Android is also slowly fi nding its way into your living room. People of Lava, a Swedish company, has developed an Android-based TV, called the Scandinavia Android TV (see Figure 1-5). Google has also ventured into a proprietary smart TV platform based on Android and codeveloped with companies such as Intel, Sony, and Logitech. Figure 1-6 shows Sony’s Google TV.

c01.indd 7

25/01/12 1:04 PM





At the time of writing, the Samsung Galaxy Nexus (see Figure 1-7) is the only device running on Android 4.0. However, Google has promised that existing devices (such as the Nexus S) will be able to upgrade to Android 4.0. By the time you are reading this, there should be a plethora of devices running Android 4.0.


The Android Market As mentioned earlier, one of the main factors determining the success of a smartphone platform is the applications that support it. It is clear from the success of the iPhone that applications play a very vital role in determining whether a new platform swims or sinks. In addition, making these applications accessible to the general user is extremely important.

c01.indd 8

25/01/12 1:04 PM

Obtaining the Required Tools

❘ 9

As such, in August 2008, Google announced Android Market, an online application store for Android devices, and made it available to users in October 2008. Using the Market application that is preinstalled on their Android device, users can simply download third-party applications directly onto their devices. Both paid and free applications are supported on the Android Market, though paid applications are available only to users in certain countries due to legal issues. Similarly, in some countries, users can buy paid applications from the Android Market, but developers cannot sell in that country. As an example, at the time of writing, users in India can buy apps from the Android Market, but developers in India cannot sell apps on the Android Market. The reverse may also be true; for example, users in South Korea cannot buy apps, but developers in South Korea can sell apps on the Android Market.

NOTE Chapter 12 discusses more about the Android Market and how you can sell your own applications in it.

The Android Developer Community With Android in its fourth version, there is a large developer community all over the world. It is now much easier to get solutions to problems, and fi nd like-minded developers to share app ideas and exchange experiences. Here are some developer communities/sites that you can turn to for help if you run into problems while working with Android: ➤

Stack Overflow ( — Stack Overflow is a collaboratively edited question and answer site for developers. If you have a question about Android, chances are someone at Stack Overflow is probably already discussing the same question and someone else had already provided the answer. Best of all, other developers can vote for the best answer so that you can know which are the answers that are trustworthy.

Google Android Training ( .html) — Google has launched the Android Training site that contains a number of useful classes grouped by topics. At the time of writing, the classes mostly contain useful code snippets that are very useful to Android developers once they have started with the basics. Once you have learned the basics in this book, I strongly suggest you take a look at the classes.

Android Discuss ( — Android Discuss is a discussion group hosted by Google using the Google Groups service. Here, you will be able to discuss the various aspects of Android programming. This group is monitored closely by the Android team at Google, and so this is good place to clarify your doubts and learn new tips and tricks.

OBTAINING THE REQUIRED TOOLS Now that you know what Android is and what its feature set contains, you are probably anxious to get your hands dirty and start writing some applications! Before you write your fi rst app, however, you need to download the required tools and SDKs.

c01.indd 9

25/01/12 1:04 PM



For Android development, you can use a Mac, a Windows PC, or a Linux machine. All the tools needed are free and can be downloaded from the Web. Most of the examples provided in this book should work fi ne with the Android emulator, with the exception of a few examples that require access to the hardware. For this book, I am using a Windows 7 computer to demonstrate all the code samples. If you are using a Mac or Linux computer, the screenshots should look similar; some minor differences may be present, but you should be able to follow along without problems. Let the fun begin!

JAVA JDK The Android SDK makes use of the Java SE Development Kit (JDK). If your computer does not have the JDK installed, you should start by downloading it from and installing it prior to moving to the next section.

Android SDK The fi rst and most important piece of software you need to download is, of course, the Android SDK. The Android SDK contains a debugger, libraries, an emulator, documentation, sample code, and tutorials. You can download the Android SDK from (see Figure 1-8).


c01.indd 10

25/01/12 1:04 PM

Obtaining the Required Tools

❘ 11

The Android SDK is packaged in a zip fi le. You can download it and unzip its content (the android-sdk-windows folder) into a folder, say C:\Android 4.0\. For Windows user, Google recommends that you download the installer_r15-windows.exe fi le instead and use it to set up the tools for you automatically. The following steps walk you through the installation process using this approach.

Installing the Android SDK Tools When you have downloaded the installer_r15-windows.exe fi le, double-click it to start the installation of the Android tools. In the welcome screen of the Setup Wizard, click Next to continue. If your computer does not have Java installed, you will see the error dialog shown in Figure 1-9. However, even if you have Java installed, you may still see this error. If this is the case, click the Report error button and then click Next.


You will be asked to provide a destination folder to install the Android SDK tools. Enter a destination path (see Figure 1-10) and click Next. When you are asked to choose a Start Menu folder to create the program’s shortcut, take the default “Android SDK Tools” and click Install. When the setup is done, check the “Start SDK Manager (to download system images, etc.)” option and click Finish (see Figure 1-11). This will start the SDK Manager.

c01.indd 11

25/01/12 1:04 PM





Configuring the Android SDK Manager The Android SDK Manager manages the various versions of the Android SDK currently installed on your computer. When it is launched, you will see a list of items and whether or not they are currently installed on your computer (see Figure 1-12). Check the relevant tools, documentation, and platforms you need for your project. Once you have selected the items you want, click the Install button to download them. Because it takes a while to download from Google’s server, it is a good idea to download only what you need immediately, and download the rest when you have more time. For now, you may want to check the items shown in the figure.

c01.indd 12

25/01/12 1:04 PM

Obtaining the Required Tools

❘ 13


NOTE For a start, you should at least select the latest Android 4.0 SDK platform and the Extras. At the time of writing, the latest SDK platform is SDK Platform Android 4.0, API 14.

Each version of the Android OS is identified by an API level number. For example, Android 2.3.3 is level 10 (API 10), while Android 3.0 is level 11 (API 11), and so on. For each level, two platforms are available. For example, level 14 offers the following: ➤

SDK Platform

Google APIs by Google Inc.

The key difference between the two is that the Google APIs platform contains additional APIs provided by Google (such as the Google Maps library). Therefore, if the application you are writing requires Google Maps, you need to create an AVD using the Google APIs platform (more on this is provided in Chapter 9, “Location-Based Services.”

c01.indd 13

25/01/12 1:04 PM



You will be asked to choose the packages to install (see Figure 1-13). Check the Accept All option and click Install.


The SDK Manager will proceed to download the packages that you have selected. The installation takes some time, so be patient. When all the packages are installed, you will be asked to restart the ADB (Android Debug Bridge). Click Yes.

Eclipse The next step is to obtain the integrated development environment (IDE) for developing your Android applications. In the case of Android, the recommended IDE is Eclipse, a multi-language software development environment featuring an extensible plug-in system. It can be used to develop various types of applications, using languages such as Java, Ada, C, C++, COBOL, Python, and others. For Android development, you should download the Eclipse IDE for Java EE Developers ( Six editions are available: Windows (32- and 64-bit), Mac OS X (Cocoa 32- and 64), and Linux (32- and 64-bit). Simply select the relevant one for your operating system. All the examples in this book were tested using the 32-bit version of Eclipse for Windows. Once the Eclipse IDE is downloaded, unzip its content (the eclipse folder) into a folder, say C:\Android 4.0\. Figure 1-14 shows the content of the eclipse folder.


To launch Eclipse, double-click on the eclipse.exe fi le. You are fi rst asked to specify your workspace. In Eclipse, a workspace is a folder where you store all your projects. Take the default suggested (or you can specify your own folder as the workspace) and click OK.

c01.indd 14

25/01/12 1:04 PM

Obtaining the Required Tools

❘ 15

Android Development Tools (ADT) When Eclipse is launched, select Help ➪ Install New Software (see Figure 1-15) to install the Android Development Tools (ADT) plug-in for Eclipse.


The ADT is an extension to the Eclipse IDE that supports the creation and debugging of Android applications. Using the ADT, you will be able to do the following in Eclipse: ➤

Create new Android application projects.

Access the tools for accessing your Android emulators and devices.

Compile and debug Android applications.

Export Android applications into Android Packages (APKs).

Create digital certificates for code-signing your APK.

In the Install dialog that appears, specify and press Enter. After a while, you will see the Developer Tools item appear in the middle of the window (see Figure 1-16). Expand it to reveal its content: Android DDMS, Android Development Tools, Android Hierarchy Viewer, and Android Traceview. Check all of them and click Next twice.

c01.indd 15

25/01/12 1:05 PM




NOTE If you have any problems downloading the ADT, check out Google’s help at

You will be asked to review and accept the licenses. Check the “I accept the terms of the license agreements” option and click Finish. Once the installation is completed, you will be asked to restart Eclipse. Go ahead and restart Eclipse now. When Eclipse is restarted, you are asked to configure your Android SDK (see Figure 1-17). As the Android SDK has already been downloaded earlier in the previous section, check the “Use existing SDKs” option and specify the directory where you have installed the Android SDK. Click Next. After this step, you are asked to send your usage statistics to Google. Once you have selected your choice, click Finish.

c01.indd 16


25/01/12 1:05 PM

Obtaining the Required Tools

❘ 17

NOTE As each new version of the SDK is released, the installation steps tend to differ slightly. If you do not experience the same steps as described here, don’t worry — just follow the instructions on screen.

Creating Android Virtual Devices (AVDs) The next step is to create an Android Virtual Device (AVD) to be used for testing your Android applications. An AVD is an emulator instance that enables you to model an actual device. Each AVD consists of a hardware profi le; a mapping to a system image; as well as emulated storage, such as a secure digital (SD) card. You can create as many AVDs as you want in order to test your applications with several different configurations. This testing is important to confi rm the behavior of your application when it is run on different devices with varying capabilities.

NOTE Appendix B discusses some of the capabilities of the Android emulator.

To create an AVD, select Window ➪ AVD Manager (see Figure 1-18).


c01.indd 17

25/01/12 1:05 PM



In the Android Virtual Device Manager dialog (see Figure 1-19), click the New... button to create a new AVD.


In the Create new Android Virtual Device (AVD) dialog, enter the items as shown in Figure 1-20. Click the Create AVD button when you are done.


c01.indd 18

25/01/12 1:05 PM

Obtaining the Required Tools

❘ 19

In this case, you have created an AVD (put simply, an Android emulator) that emulates an Android device running version 4.0 of the OS with a built-in 10-MB SD card. In addition to what you have created, you also have the option to emulate the device with different screen densities and resolutions.

NOTE Appendix B explains how to emulate the different types of Android devices.

It is preferable to create a few AVDs with different API levels and hardware configurations so that your application can be tested on different versions of the Android OS. Once your ADV has been created, it is time to test it. Select the AVD that you want to test and click the Start… button. The Launch Options dialog will appear (see Figure 1-21). If you have a small monitor, it is recommended that you check the “Scale display to real size” option so that you can set the emulator to a smaller size. Click the Launch button to start the emulator.


The Android emulator will start, and after a while it will be ready for use (see Figure 1-22). Go ahead and try out the emulator. It will behave just like a real Android device. After that, in the next section you will learn how to write your fi rst Android application!

c01.indd 19

25/01/12 1:05 PM




CREATING YOUR FIRST ANDROID APPLICATION With all the tools and the SDK downloaded and installed, it is now time to start your engine. As in all programming books, the fi rst example uses the ubiquitous Hello World application. This will give you a detailed look at the various components that make up an Android project.


Creating Your First Android Application codefile available for download at


c01.indd 20

Using Eclipse, create a new project by selecting File ➪ New ➪ Project . . . (see Figure 1-23).

25/01/12 1:05 PM

Creating Your First Android Application

❘ 21


NOTE After you have created your first Android application, subsequent Android projects can be created by selecting File ➪ New ➪ Android Project.

2. 3.

Expand the Android folder and select Android Project (see Figure 1-24). Click Next. Name the Android project HelloWorld, as shown in Figure 1-25, and then click Next.


c01.indd 21

25/01/12 1:05 PM




4. 5.

Select the Android 4.0 target and click Next. Fill in the Application Info details as shown in Figure 1-26. Click Finish.


c01.indd 22

25/01/12 1:05 PM

Creating Your First Android Application

❘ 23

NOTE You need to have at least a period (.) in the package name. The recommended convention for the package name is to use your domain name in reverse order, followed by the project name. For example, my company’s domain name is; hence, my package name would be net.learn2develop.HelloWorld.


The Eclipse IDE should now look like Figure 1-27.


c01.indd 23


In the Package Explorer (located on the left of the Eclipse IDE), expand the HelloWorld project by clicking on the various arrows displayed to the left of each item in the project (see Figure 1-28). In the res/layout folder, double-click the main.xml fi le.


The main.xml fi le defi nes the user interface (UI) of your application. The default view is the Layout view, which lays out the activity graphically. To modify the UI by hand, click the main.xml tab located at the bottom (see Figure 1-29).

25/01/12 1:05 PM






Add the following code in bold to the main.xml fi le:
c01.indd 24

25/01/12 1:05 PM

Creating Your First Android Application

❘ 25

android:layout_height=”fill_parent” android:orientation=”vertical” >

Android App Development

ffirs.indd ii 25/01/12 8:34 AM BEGINNING ANDROID™ 4 APPLICATION DEVELOPMENT INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

60MB Sizes 3 Downloads 44 Views

Recommend Documents

Eye on Android App Development | Codecademy
Eye on Android App Development. ... The reason for this is that the Android SDK (Software Development Kit) is abstractin

Android App Development Tutorial In Hindi - mechanic37
Android app कैसे बनाएं Android Studio या Eclipse का Use करके Basic Tutorial In Hindi .

Install App android terbaru - Download App android
Install App android free - App android new terbaik update aplikasi gratis di google store terbaru. multi-gudang kategori

InfoJobs android app - Uplabs
Here're some mockups of the newly designed InfoJobs app for Android. We have followed the Google's material design style

App Inventor for Android
high school, such as exponent, modulus, and cosine; these functions let you do nearly any mathematical function, includi

Android App Roundup - Tested
Datally also offers a list of local WiFi hotspots if you need to get a lot of downloading done while you're out. This li

TomTom App for Android
Esta función sólo está disponible si tiene TomTom Traffic. Otras opciones de Ir a. Cuando toca Ir a en el menú princ

Kotlin – New Programming Language for Android App Development
Jun 27, 2017 - What is Kotlin really and why is it touted to be the next big programming language for Android App Develo

O App - Android
Sep 10, 2014 - Keeping data in sync with the cloud is an important part of many applications, and the Google I/O App is

Working with Images in Your Android App Development - Developer
Jan 9, 2012 - Android APIs for Processing Images. Android's APIs cover lots of great features, including: SQLite for str

Objetivos para móviles | Chatroom | NTSF:SD:SUV::