SlideShare una empresa de Scribd logo
1 de 585
Descargar para leer sin conexión
Android in Action
SECOND EDITION
W. FRANK ABLESON
ROBI SEN
CHRIS KING
Revised Edition of Unlocking Android
M A N N I N G
Greenwich
(74° w. long.)
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
180 Broad St.
Suite 1323
Stamford, CT 06901
Email: orders@manning.com
©2011 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in
any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books
are printed on paper that is at least 15 percent recycled and processed without the use of
elemental chlorine
Manning Publications Co. Development editor: Troy Mott
180 Broad St. Copyeditors: Joan Celmer, Liz Welch
Suite 1323 Typesetter: Dottie Marsico
Stamford, CT 06901 Cover designer: Marija Tudor
ISBN 978-1-935182-72-6
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – MAL – 16 15 14 13 12 11
v
brief contents
PART 1 WHAT IS ANDROID?—THE BIG PICTURE ........................1
1 ■ Introducing Android 3
2 ■ Android’s development environment 31
PART 2 EXERCISING THE ANDROID SDK ..................................61
3 ■ User interfaces 63
4 ■ Intents and Services 101
5 ■ Storing and retrieving data 129
6 ■ Networking and web services 159
7 ■ Telephony 187
8 ■ Notifications and alarms 205
9 ■ Graphics and animation 222
10 ■ Multimedia 246
11 ■ Location, location, location 267
PART 3 ANDROID APPLICATIONS............................................291
12 ■ Putting Android to work in a field service application 293
13 ■ Building Android applications in C 338
BRIEF CONTENTSvi
PART 4 THE MATURING PLATFORM ........................................365
14 ■ Bluetooth and sensors 367
15 ■ Integration 387
16 ■ Android web development 421
17 ■ AppWidgets 454
18 ■ Localization 491
19 ■ Android Native Development Kit 506
vii
contents
preface xvii
preface to the first edition xix
acknowledgments xxi
about this book xxiv
about the cover illustration xxix
PART 1 WHAT IS ANDROID?—THE BIG PICTURE ...............1
1 Introducing Android 3
1.1 The Android platform 4
1.2 Understanding the Android market 5
Mobile operators 5 ■ Android vs. the feature phones 6
Android vs. the smartphones 7 ■ Android vs. itself 8
Licensing Android 9
1.3 The layers of Android 10
Building on the Linux kernel 11 ■ Running in the
Dalvik VM 12
1.4 The Intent of Android development 12
Empowering intuitive UIs 13 ■ Intents and how they work 13
CONTENTSviii
1.5 Four kinds of Android components 17
Activity 17 ■ Service 18 ■ BroadcastReceiver 19
ContentProvider 22
1.6 Understanding the AndroidManifest.xml file 24
1.7 Mapping applications to processes 25
1.8 Creating an Android application 26
1.9 Summary 30
2 Android’s development environment 31
2.1 Introducing the Android SDK 32
Core Android packages 33 ■ Optional packages 34
2.2 Exploring the development environment 34
The Java perspective 35 ■ The DDMS perspective 37
Command-line tools 40
2.3 Building an Android application in Eclipse 43
The Android Project Wizard 43 ■ Android sample
application code 44 ■ Packaging the application 50
2.4 Using the Android emulator 51
Setting up the emulated environment 52
Testing your application in the emulator 56
2.5 Debugging your application 57
2.6 Summary 58
PART 2 EXERCISING THE ANDROID SDK .........................61
3 User interfaces 63
3.1 Creating the Activity 65
Creating an Activity class 66 ■ Exploring the Activity
lifecycle 71
3.2 Working with views 74
Exploring common views 75 ■ Using a ListView 77
Multitasking with Handler and Message 81
Creating custom views 82 ■ Understanding layout 84
Handling focus 86 ■ Grasping events 87
3.3 Using resources 89
Supported resource types 89 ■ Referencing resources in Java 89
Defining views and layouts through XML resources 92
Externalizing values 94 ■ Providing animations 97
CONTENTS ix
3.4 Exploring the AndroidManifest file 98
3.5 Summary 99
4 Intents and Services 101
4.1 Serving up RestaurantFinder with Intent 102
Defining Intents 102 ■ Implicit and explicit invocation 103
Adding external links to RestaurantFinder 104 ■ Finding your
way with Intent 106 ■ Taking advantage of Android-provided
activities 108
4.2 Checking the weather with a custom URI 109
Offering a custom URI 109 ■ Inspecting a custom Uri 111
4.3 Checking the weather with broadcast receivers 113
Broadcasting Intent 113 ■ Creating a receiver 115
4.4 Building a background weather service 115
4.5 Communicating with the WeatherAlertService
from other apps 119
Android Interface Definition Language 119 ■ Binder and
Parcelable 121 ■ Exposing a remote interface 122
Binding to a Service 123 ■ Starting versus binding 126
Service lifecycle 127
4.6 Summary 128
5 Storing and retrieving data 129
5.1 Using preferences 130
Working with SharedPreferences 130 ■ Preference access
permissions 133
5.2 Using the filesystem 136
Creating files 136 ■ Accessing files 137 ■ Files as raw
resources 138 ■ XML file resources 139 ■ External storage
via an SD card 141
5.3 Persisting data to a database 144
Building and accessing a database 144 ■ Using the
sqlite3 tool 149
5.4 Working with ContentProvider classes 149
Using an existing ContentProvider 150 ■ Creating a
ContentProvider 151
5.5 Summary 158
CONTENTSx
6 Networking and web services 159
6.1 An overview of networking 161
Networking basics 161 ■ Clients and servers 163
6.2 Checking the network status 164
6.3 Communicating with a server socket 165
6.4 Working with HTTP 168
Simple HTTP and java.net 169 ■ Robust HTTP with
HttpClient 170 ■ Creating an HTTP and HTTPS helper 172
6.5 Web services 178
POX—Putting it together with HTTP and XML 179
REST 181 ■ To SOAP or not to SOAP, that is the question 184
6.6 Summary 185
7 Telephony 187
7.1 Exploring telephony background and terms 188
Understanding GSM 189 ■ Understanding CDMA 189
7.2 Accessing telephony information 190
Retrieving telephony properties 191 ■ Obtaining phone state
information 193
7.3 Interacting with the phone 195
Using intents to make calls 195 ■ Using phone number-related
utilities 196 ■ Intercepting outbound calls 198
7.4 Working with messaging: SMS 199
Sending SMS messages 199 ■ Receiving SMS messages 202
7.5 Summary 203
8 Notifications and alarms 205
8.1 Introducing Toast 206
Creating an SMS example with a Toast 206 ■ Receiving an
SMS message 207
8.2 Introducing notifications 210
The Notification class 210 ■ Notifying a user of an SMS 211
8.3 Introducing Alarms 215
Creating a simple alarm example 215 ■ Using notifications
with Alarms 218
8.4 Summary 220
CONTENTS xi
9 Graphics and animation 222
9.1 Drawing graphics in Android 223
Drawing with XML 224 ■ Exploring XML drawable
shapes 225
9.2 Creating animations with Android’s Graphics API 227
Android’s frame-by-frame animation 227 ■ Programmatically
creating an animation 230
9.3 Introducing OpenGL for Embedded Systems 233
Creating an OpenGL context 234 ■ Drawing a rectangle with
OpenGL ES 238 ■ Three-dimensional shapes and surfaces with
OpenGL ES 241
9.4 Summary 245
10 Multimedia 246
10.1 Introduction to multimedia and OpenCORE 247
10.2 Playing audio 248
10.3 Playing video 250
10.4 Capturing media 251
Understanding the camera 252 ■ Capturing audio 257
10.5 Recording video 259
10.6 Summary 265
11 Location, location, location 267
11.1 Simulating your location within the emulator 269
Sending in your coordinates with the DDMS tool 269
The GPS Exchange Format 271 ■ The Google Earth
Keyhole Markup Language 272
11.2 Using LocationManager and LocationProvider 275
Accessing location data with LocationManager 275
Using a LocationProvider 277 ■ Receiving location
updates with LocationListener 279
11.3 Working with maps 281
Extending MapActivity 282 ■ Using a MapView 282
Placing data on a map with an Overlay 285
11.4 Converting places and addresses with Geocoder 288
11.5 Summary 290
CONTENTSxii
PART 3 ANDROID APPLICATIONS ...................................291
12 Putting Android to work in a field service application 293
12.1 Designing a real-world Android application 294
Core requirements of the application 295 ■ Managing the
data 296 ■ Application architecture and integration 297
12.2 Mapping out the application flow 298
Mapping out the field service application 298 ■ List of source
files 300 ■ Field service application’s AndroidManifest.xml 302
12.3 Application source code 302
Splash Activity 302 ■ Preferences used by the FieldService
Activity 304 ■ Implementing the FieldService Activity 306
Settings 307 ■ Managing job data 309
12.4 Source code for managing jobs 316
RefreshJobs 317 ■ Managing jobs: The ManageJobs
Activity 320 ■ Working with a job with the ShowJob Activity 323
Capturing a signature with the CloseJob Activity 327
12.5 Server code 333
Dispatcher user interface 334 ■ Database 334 ■ PHP
dispatcher code 335 ■ PHP mobile integration code 336
12.6 Summary 337
13 Building Android applications in C 338
13.1 Building Android apps without the SDK 339
The C compiler and linker tools 339 ■ Building a Hello World
application 340 ■ Installing and running the application 342
C application build script 344
13.2 Solving the problem with dynamic linking 344
Android system libraries 345 ■ Building a dynamically linked
application 346 ■ exit() versus return() 349 ■ Startup
code 350
13.3 What time is it? The DayTime Server 352
DayTime Server application 352 ■ daytime.c 353
The SQLite database 355 ■ Building and running the
DayTime Server 358
13.4 Daytime Client 360
Activity 360 ■ Socket Client 361 ■ Testing the Daytime
Client 362
13.5 Summary 362
CONTENTS xiii
PART 4 THE MATURING PLATFORM ...............................365
14 Bluetooth and sensors 367
14.1 Exploring Android’s Bluetooth capabilities 368
Replacing cables 369 ■ Primary and secondary roles and
sockets 369 ■ Trusting a device 370 ■ Connecting to a remote
device 372 ■ Capturing Bluetooth events 374 ■ Bluetooth
permissions 375
14.2 Interacting with the SensorManager 375
Types of sensors 376 ■ Reading sensor values 377
Enabling and disabling sensors 378
14.3 Building the SenseBot application 379
User interface 380 ■ Interpreting sensor values 382
Driving the robot 383 ■ Communication with the robot 384
14.4 Summary 385
15 Integration 387
15.1 Understanding the Android contact model 388
Choosing open-ended records 388 ■ Dealing with multiple
accounts 390 ■ Unifying a local view from diverse remote
stores 392 ■ Sharing the playground 393
15.2 Getting started with LinkedIn 393
15.3 Managing contacts 395
Leveraging the built-in contacts app 395 ■ Requesting operations
from your app 398 ■ Directly reading and modifying the contacts
database 399 ■ Adding contacts 400
15.4 Keeping it together 403
The dream of sync 403 ■ Defining accounts 404
Telling secrets: The AccountManager service 405
15.5 Creating a LinkedIn account 406
Not friendly to mobile 406 ■ Authenticating to LinkedIn 407
15.6 Synchronizing to the backend with SyncAdapter 414
The synchronizing lifecycle 414 ■ Synchronizing LinkedIn
data 414
15.7 Wrapping up: LinkedIn in action 417
Finalizing the LinkedIn project 417 ■ Troubleshooting tips 418
Moving on 419
15.8 Summary 419
CONTENTSxiv
16 Android web development 421
16.1 What’s Android web development? 422
Introducing WebKit 422 ■ Examining the architectural
options 423
16.2 Optimizing web applications for Android 424
Designing with mobile in mind 424 ■ Adding the viewport
tag 426 ■ Selectively loading content 428 ■ Interrogating the
user agent 428 ■ The media query 429 ■ Considering a made-
for-mobile application 430
16.3 Storing data directly in the browser 431
Setting things up 432 ■ Examining the code 433 ■ The user
interface 433 ■ Opening the database 435 ■ Unpacking the
transaction function 436 ■ Inserting and deleting rows 438
Testing the application with WebKit tools 439
16.4 Building a hybrid application 440
Examining the browser control 440 ■ Wiring up the control 441
Implementing the JavaScript handler 443 ■ Accessing the code
from JavaScript 445 ■ Digging into the JavaScript 445
Security matters 447 ■ Implementing a WebViewClient 448
Augmenting the browser 448 ■ Detecting navigation events 449
Implementing the WebChromeClient 452
16.5 Summary 453
17 AppWidgets 454
17.1 Introducing the AppWidget 455
What’s an AppWidget? 455 ■ AppWidget deployment
strategies 457
17.2 Introducing SiteMonitor 458
Benefits of SiteMonitor 458 ■ The user experience 459
17.3 SiteMonitor application architecture 462
Bird’s-eye view of the application 462 ■ File by file 464
17.4 AppWidget data handling 465
17.5 Implementing the AppWidgetProvider 469
AppWidgetProvider method inventory 469 ■ Implementing
SiteMonitorWidgetImpl 470 ■ Handling zombie widgets 472
17.6 Displaying an AppWidget with RemoteViews 473
Working with RemoteViews 473 ■ UpdateOneWidget
explained 474
CONTENTS xv
17.7 Configuring an instance of the AppWidget 476
AppWidget metadata 477 ■ Working with Intent data 478
Confirming widget creation 479
17.8 Updating the AppWidget 480
Comparing services to alarms 481 ■ Triggering the update 482
Updating the widgets, finally! 484
17.9 Tying it all together with AndroidManifest.xml 488
17.10 Summary 489
18 Localization 491
18.1 The need for localization 492
18.2 Exploring locales 493
18.3 Strategies for localizing an application 494
Identifying target locales and data 494 ■ Identifying and
managing strings 495 ■ Drawables and layouts 497
Dates, times, numbers, and currencies 498 ■ Working with
the translation team 499
18.4 Leveraging Android resource capabilities 500
More than locale 500 ■ Assigning strings in resources 500
18.5 Localizing in Java code 502
18.6 Formatting localized strings 503
18.7 Obstacles to localization 504
18.8 Summary 505
19 Android Native Development Kit 506
19.1 Introducing the NDK 507
Uses for the NDK 507 ■ Looking at the NDK 508
19.2 Building an application with the NDK 509
Demonstrating the completed application 510
Examining the project structure 511
19.3 Building the JNI library 512
Understanding JNI 512 ■ Implementing the library 513
Compiling the JNI library 518
19.4 Building the user interface 519
User interface layout 519 ■ Taking a photo 521
Finding the edges 523
CONTENTSxvi
19.5 Integrating the NDK into Eclipse 524
19.6 Summary 526
appendix A Installing the Android SDK 527
appendix B Publishing applications 538
index 551
xvii
preface
When we set out to write the first version of this book, many friends and family won-
dered just what this Android thing was all about. Now, two years after the publication
of the first edition, Android is nearly a household term.
The first edition of the book, Unlocking Android, enjoyed enough success that we
were privileged to have the opportunity to write this second edition, renamed as
Android in Action. The first thirteen chapters of the book have been refreshed and/or
rewritten to bring the content up to date with Android 2.2+. Six chapters were added,
bringing in more topics of interest that stray from the simplistic but are still within the
realm of instructional and informational. The new content extends beyond the basics
of Android development, including some topics that I’ve envisioned for a long time
but lacked the proper platform to bring them to fruition. We could have written many
more chapters, but we had to draw the line somewhere!
The second edition of this book was written by Frank Ableson, Robi Sen, and Chris
King. Chris updated chapters 4, 5, 7, and 11. Some excellent content originally writ-
ten by Charlie Collins remains in this second edition. Early on in the project Chris
and I were discussing the need to bring social networking into the book. Chris exam-
ined the available social networks and came back with a clever mechanism to integrate
the Android contacts database with the popular business networking service
LinkedIn. His work is shown in chapter 15, “Integration.” The application from chap-
ter 15 is available as a free download in the Android Market.
Robi updated his chapters on notifications, graphics, and media, while I focused
on some new content areas of interest, including Bluetooth communications, sen-
sors, localization, AppWidgets, native development in C, and web development for
Android.
PREFACExviii
In addition to the LinkedIn application from chapter 15, two more applications
from this book are available in the Market as free downloads. The first is SenseBot—
an application that allows you to drive a LEGO Mindstorms-powered robot by tilting
your phone. The application demonstrates both the sensor subsystem of Android, as
well as communicating with Bluetooth. The other application available in the Market
is called FindEdges. FindEdges demonstrates the Android Native Development Kit as
it exercises an image processing algorithm written in the C language.
All in all, writing a book for Android is both exciting and challenging. Android
continues to mature and promises to be a major player for years to come. Many thanks
are owed to readers of the first edition, for without you, there wouldn’t be a second
edition!
FRANK ABLESON
xix
preface to the first edition
The first mobile applications I had the opportunity to work with were inventory con-
trol programs used in retail and manufacturing settings. The “terminals,” as we called
them at the time, were heavy and expensive. They had big antennas, lots of clunky
keys, grayscale LCD displays, and they looked like they came straight from the set of a
science fiction movie.
From that austere beginning, my mobile horizons expanded when the Palm Pilot
became the craze in the mid to late 1990s. My first significant PalmOS project was to
develop an IrDA communications library for an application that printed calendars,
contacts, and task-lists. Back then, the hip printers had an IrDA port and it was cool to
beam your business card to someone. Ironically, I always enjoyed designing and writ-
ing the software more than using the devices themselves.
Fast forward ten years, and I have had the privilege of working on some very chal-
lenging and engaging mobile software projects for numerous clients along the way.
Much of my career to date can be traced back to relationships stemming from my
early mobile development experiences—and what a blessing it has been for me. I just
love the question, “would it be possible to…?” And more often than not, the answer
has been “Yes!” What I particularly enjoy is helping change the way a business operates
or the way problems are solved through the application of mobile software. Mobile
technology can and will continue to change the way we live, work, and play…and this
brings me to Android and this book.
In the fall of 2007, I was speaking with my friend Troy Mott, who happens to be an
editor for Manning, the publisher of this book. Troy and I were discussing the mobile
marketplace, something we’ve been doing for years. We started kicking around the
PREFACE TO THE FIRST EDITIONxx
idea of writing a book on Android. The challenge was that Android didn’t really exist.
Yet. We knew from some of the preliminary information that the platform promised to
be open, capable, and popular. We felt that those ingredients could make for an inter-
esting and valuable topic, so we began thinking about what that book might look like,
taking it on faith that the platform would actually come to fruition.
Before long, we convinced ourselves (and Manning) that this was a good idea and
the work began in early 2008. Beyond the usual challenges of putting a book together,
we had the additional obstacle that our subject matter has been in a steady, though
unpredictable, state of change over the past year. In essence, we’ve written this book
twice because the SDK has been changed multiple times and Android-equipped
phones have become available, accelerating the interest and demand for the plat-
form. Every time a significant change occurred, we went back and revisited portions of
the book, sometimes rewriting entire chapters to accommodate the latest develop-
ments in the Android platform.
I say “we” because in the process of writing this book, Troy and I decided to share
the fun and brought in two experienced authors to contribute their expertise and
enthusiasm for this platform. It has been a pleasure getting to know and working with
both Charlie Collins and Robi Sen. While I focused on the first and third parts of the
book in the first edition, Charlie and Robi wrote part 2, which covers the important
fundamentals of writing Android applications. Thanks to their contributions, I
enjoyed the freedom to express my vision of what Android means to the mobile space
in the first part of the book, and then to work on a couple of more advanced applica-
tions at the end of the book.
We hope that you enjoy reading this book and that it proves to be a valuable
resource for years to come as together we contribute to the future of the Android
platform.
FRANK ABLESON
xxi
acknowledgments
Perhaps the only thing more challenging than writing a technical book is writing the
second edition. There is a lot of excitement when writing the proposed table of con-
tents for the updated edition but at some point the work must commence. The size and
scope of this project meant working together as a team from the start. I had the privi-
lege of working again with Robi Sen from the first edition and also with experienced
developer and writer Chris King. Along with the help of the talented team at Manning,
we are pleased to present Android in Action, the update to Unlocking Android.
In particular, we’d like to acknowledge and thank those at Manning who helped
bring this book about. First, thanks to Troy Mott, our acquisition and development
editor, who has been involved in every aspect of both the first and second editions.
Troy was there from the beginning, from the “what if” stages, through helping push us
over the goal line—twice! Karen Tegtmeyer did all the big and little things to bring
the project together; Mary Piergies skillfully piloted the team through the harrowing
production process; and Marjan Bace, our publisher, showed an attention to detail at
once challenging, beneficial, and appreciated.
Once the writing was done, the next round of work began and special thanks need
to go to: Benjamin Berg who performed the pre-production editing pass, Joan Celmer
and Liz Welch, our copyeditors, who made our content readable in cases where it
went either “too geek” or where the geek in us tried to be “too literary;” Elizabeth
Martin, our proofreader, who added common sense to the project, as well as a terrific
sense of humor and encouraging attitude; Janet Vail who jumped in at the last minute
to help us bring the final pieces of the project together; and finally Dottie Marsico
who handles the actual layout of the pages. It is sometimes hard to envision the final
ACKNOWLEDGMENTSxxii
product when looking at edits upon edits in MS Word, but Dottie’s magic makes the
product you hold in your hands. Thanks to each of you for your special contribution
to this project. Next, we would like to thank Candace Gillhooley for her efforts in get-
ting the word out about the book.
And special thanks to the other reviewers who read our revised manuscript at dif-
ferent times during its development: Michael Martin, Orhan Alkan, Eric Raymond,
Jason Jung, Frank Wang, Robert O’Connor, Paul Grebenc, Sean Owen, Loïc Simon,
Greg Donald, Nikolaos Kaintantzis, Matthew Johnson, and Patrick Steger; and to
Michael Galpin and Jérôme Bâton for their careful tech review of the final manuscript
during production.
Lastly, we want to thank the thoughtful and encouraging MEAP subscribers who
provided feedback along the way; the book is better thanks to your contributions.
Frank Ableson
I would like to thank Robi Sen, Chris King, and Troy Mott for their contributions, col-
laboration, and endurance on this project! And of course, my wife Nikki and my chil-
dren deserve special recognition for the seemingly endless hours of wondering when I
would emerge from the “lab” and what mood I would be in—either elation when the
robot worked, or near depression when the AppWidgets wouldn’t go away. Thank you
for getting neither too excited nor too concerned! My staff at navitend also deserve a
big thank you for carrying the water while I finished my work on this project. Finally, a
big thank you to Miriam Raffay from Madridiam.com, who provided the much-
needed Spanish translations for chapter 18. Gracias!
Chris King
I am deeply grateful to Troy Mott and Frank Ableson for bringing me into this project
and providing support and inspiration throughout. Troy has been welcoming and
enthusiastic, showing great flexibility as we discussed what projects to undertake.
Frank has a keen eye for quality, and provided great guidance from start to finish on
how to craft the best book possible. I also appreciate all the work done by the review-
ers and editors from Manning, whose contributions have improved the text’s accuracy
and style. Working on this book has been a joy, and I’ve greatly enjoyed the opportuni-
ties to contribute more and more to its progress.
Thanks also to the crew at Gravity Mobile, especially Noah Hurwitz, Chris Lyon,
Young Yoon, and Sam Trychin. You guys keep my life fun and challenging, and have
made mobile development an even better place to work. Finally, my love to my fam-
ily: Charles, Karen, Patrick, Kathryn, and Andrew. You’ve made everything possible
for me.
ACKNOWLEDGMENTS xxiii
Robi Sen
I would like to thank Troy Mott and the team—and everyone at Manning Publica-
tions— for their hard work making this book something worth reading. I would like to
thank my coauthors, Frank and Chris, who were great to work with and very under-
standing when I was the one holding things up. I would also like to thank Jesse Dailey
for his help with OpenGL as well as David Cartier with the Contacts API. Finally, I
would like to thank my family who, more often than I liked, had to do without me
while I worked on my chapters, worked multiple jobs, and finished grad school.
xxiv
about this book
Android in Action, Second Edition is a revision and update of Unlocking Android, pub-
lished in April 2009. This book doesn’t fit nicely into the camp of “introductory text,”
nor is it a highly detailed reference manual. The text has something to offer both the
beginner and the experienced developer who is looking to sell his or her application
in the Android Market. This book covers important beginner topics such as “What is
Android” and installing and using the development environment. We then advance to
practical working examples of core programming topics any developer will be happy
to have at the ready on the reference shelf. The remaining chapters present very
detailed example applications covering advanced topics, including a complete field
service application, localization, and material on Android web applications, Blue-
tooth, sensors, AppWidgets, and integration adapters. We even include two chapters
on writing applications in C—one for the native side of Android and one using the
more generally accepted method of employing the Android Native Development Kit.
Although you can read the book from start to finish, you can also consider it a cou-
ple of books in one. If you’re new to Android, focus first on chapter 1, appendix A,
and then chapter 2. With that foundation, you can then work your way through chap-
ters 3 through 12. Chapter 13 and on are more in-depth in nature and can be read
independently of the others.
The audience
We wrote this book for professional programmers and hobbyists alike. Many of the
concepts can be absorbed without specific Java language knowledge, though the
most value will be found by readers with Java programming skills because Android
ABOUT THIS BOOK xxv
application programming requires them. A reader with C, C++, or C# programming
knowledge will be able to follow the examples.
Prior Eclipse experience is helpful, but not required. A number of good resources
are available on Java and Eclipse to augment the content of this book.
Roadmap
This book is divided into four parts. Part 1 contains introductory material about the
platform and development environment. Part 2 takes a close look at the fundamental
skills required for building Android applications. Part 3 presents a larger scope appli-
cation and a Native C Android application. Part 4 explores features added to the
Android platform, providing examples of leveraging the capable Android platform to
create innovative mobile applicatoins.
PART 1: THE ESSENTIALS
Part 1 introduces the Android platform, including its architecture and setting up the
development environment.
Chapter 1 delves into the background and positioning of the Android platform,
including comparisons to other popular platforms such as BlackBerry, iPhone, and
Windows Mobile. After an introduction to the platform, the balance of the first chap-
ter introduces the high-level architecture of Android applications and the operating
system environment.
Chapter 2 takes you on a step-by-step development exercise, teaching you the
ropes of using the Android development environment, including the key tools and
concepts for building an application. If you’ve never used Eclipse or have never writ-
ten an Android application, this chapter will prepare you for the next part of the
book.
PART 2: THE PROGRAMMING ENVIRONMENT
Part 2 includes an extensive survey of fundamental programming topics in the
Android environment.
Chapter 3 covers the fundamental Android UI components, including View and
Layout. We also review the Activity in more detail. These are the basic building
blocks of screens and applications on the Android platform. Along the way, we also
touch on other basic concepts such as handling external resources, dealing with
events, and the lifecycle of an Android application.
Chapter 4 expands on the concepts you learned in chapter 3. We delve into the
Android Intent to demonstrate interaction between screens, activities, and entire
applications. We also introduce and use the Service, which brings background pro-
cesses into the fold.
Chapter 5 incorporates methods and strategies for storing and retrieving data
locally. The chapter examines use of the filesystem, databases, the SD card, and
Android-specific entities such as the SharedPreferences and ContentProvider
classes. At this point, we begin combining fundamental concepts with more real-world
ABOUT THIS BOOKxxvi
details, such as handling application state, using a database for persistent storage, and
working with SQLite.
Chapter 6 deals with storing and retrieving data over the network. Here we include
a networking primer before delving into using raw networking concepts such as sock-
ets on Android. From there, we progress to using HTTP, and even exploring web ser-
vices (such as REST and SOAP).
Chapter 7 covers telephony on the Android platform. We touch on basics such as
originating and receiving phone calls, as well as more involved topics such as working
with SMS. We also cover telephony properties and helper classes.
Chapter 8 looks at how to work with notifications and alarms. In this chapter, we
look at how to notify users of various events such as receiving a SMS message, as well as
how to manage and set alarms.
Chapter 9 deals with the basics of Android’s Graphics API and more advanced con-
cepts such as working with the OpenGL ES library for creating sophisticated 2D and 3D
graphics. We also touch on animation.
Chapter 10 looks at Android’s support for multimedia; we cover both playing mul-
timedia as well as using the camera and microphone to record your own multimedia
files.
Chapter 11 introduces location-based services as we look at an example that com-
bines many of the concepts from the earlier parts of the book in a mapping applica-
tion. You’ll learn about using the mapping APIs on Android, including different
location providers and properties that are available, how to build and manipulate
map-related screens, and how to work with location-related concepts within the emu-
lator.
PART 3: BRINGING IT ALL TOGETHER
Part 3 contains two chapters, both of which build on knowledge you gained earlier in
the text, with a focus on bringing a larger application to fruition.
Chapter 12 demonstrates an end-to-end field service application. The application
includes server communications, persistent storage, multiple Activity navigation
menus, and signature capture.
Chapter 13 explores the world of native C language applications. The Android SDK
is limited to the Java language, although native applications can be written for
Android. This chapter walks you through examples of building C language applica-
tions for Android, including the use of built-in libraries and TCP socket communica-
tions as a Java application connects to your C application. This chapter is useful for
developers targeting solutions beyond carrier-subsidized, locked down cell phones.
PART 4: THE MATURING PLATFORM
Part 4 contains six new chapters, each of which represents a more advanced develop-
ment topic.
Chapter 14 demonstrates the use of both Bluetooth communication and process-
ing sensor data. The sample application accompanying the chapter, SenseBot, permits
the user to drive a LEGO Mindstorms robot with their Android phone.
ABOUT THIS BOOK xxvii
Chapter 15 explores the Android contact database and demonstrates integrating
with an external data source. In particular, this application brings Android into the
social networking scene by integrating with the popular LinkedIn professional net-
working service.
Chapter 16 explores the world of web development. Android’s browser is based on
the open source WebKit engine and brings desktop-like capability to this mobile
browser. This chapter equips you to bring attractive and capable web applications to
Android.
Chapter 17 brings the “home screen” of your Android application to life by show-
ing you how to build an application that presents its user interface as an AppWidget.
In addition to AppWidgets, this chapter demonstrates BroadcastReceiver, Service,
and Alarms.
Chapter 18 takes a real-world look at localizing an existing application. Chapter
12’s Field Service application is modified to support multiple languages. Chapter 18’s
version of the Field Service application contains support for both English and Spanish.
Chapter 19 reaches into Android’s open source foundation by using a popular
edge detection image processing algorithm. The Sobel Edge Detection algorithm is
written in C and compiled into a native library. The sample application snaps a pic-
ture with the Android camera and then uses this C algorithm to find the edges in the
photo.
THE APPENDICES
The appendices contain additional information that didn’t fit with the flow of the
main text. Appendix A is a step-by-step guide to installing the development environ-
ment. This appendix, along with chapter 2, provides all the information you need to
build an Android application. Appendix B demonstrates how to prepare and submit
an application for the Android Market—an important topic for anyone looking to sell
an application commercially.
Code conventions and downloads
All source code in the book is in a fixed-width font like this, which sets it off from
the surrounding text. For most listings, the code is annotated to point out the key con-
cepts, and numbered bullets are sometimes used in the text to provide additional
information about the code. We have tried to format the code so that it fits within the
available page space in the book by adding line breaks and using indentation carefully.
Sometimes, however, very long lines will include line-continuation markers.
Source code for all the working examples is available from www.manning.com/
AndroidinActionSecondEdition or http://www.manning.com/ableson2. A readme.txt
file is provided in the root folder and also in each chapter folder; the files provide
details on how to install and run the code. Code examples appear throughout this
book. Longer listings will appear under clear listing headers while shorter listings will
appear between lines of text.
ABOUT THIS BOOKxxviii
Software requirements
Developing applications for Android may be done from the Windows XP/Vista/7
environment, a Mac OS X (Intel only) environment or a Linux environment. Appen-
dix A includes a detailed description of setting up the Eclipse environment along with
the Android Developer Tools plug-in for Eclipse.
A note about the graphics
Many of the original graphics from the first edition, Unlocking Android, have been
reused in this version of the book. While the title of the revised edition was changed
to Android in Action, Second Edition during development, we kept the original book title
in our graphics and sample applications.
Author Online
Purchase of Android in Action, Second Edition includes free access to a private web
forum run by Manning Publications where you can make comments about the book,
ask technical questions, and receive help from the authors and from other users. To
access the forum and subscribe to it, point your web browser to www.manning.com/
AndroidinActionSecondEdition or www.manning.com/ableson2. This page provides
information on how to get on the forum once you’re registered, what kind of help is
available, and the rules of conduct on the forum.
Manning’s commitment to our readers is to provide a venue where a meaningful
dialog between individual readers and between readers and the authors can take
place. It’s not a commitment to any specific amount of participation on the part of the
authors, whose contribution to the AO remains voluntary (and unpaid). We suggest
you try asking the authors some challenging questions lest their interest stray!
The Author Online forum and the archives of previous discussions will be accessi-
ble from the publisher’s website as long as the book is in print.
xxix
about the cover illustration
The illustration on the cover of Android in Action, Second Edition is taken from a French
book of dress customs, Encyclopédie des Voyages by J. G. St. Saveur, published in 1796.
Travel for pleasure was a relatively new phenomenon at the time and illustrated
guides such as this one were popular, introducing both the tourist as well as the arm-
chair traveler to the inhabitants of other regions of the world, as well as to the
regional costumes and uniforms of France.
The diversity of the drawings in the Encyclopédie des Voyages speaks vividly of the
uniqueness and individuality of the world’s countries and regions just 200 years ago.
This was a time when the dress codes of two regions separated by a few dozen miles
identified people uniquely as belonging to one or the other, and when members of a
social class or a trade or a tribe could be easily distinguished by what they were wearing.
This was also a time when people were fascinated by foreign lands and faraway
places, even though they could not travel to these exotic destinations themselves.
Dress codes have changed since then and the diversity by region and tribe, so rich at
the time, has faded away. It is now often hard to tell the inhabitant of one continent
from another. Perhaps, trying to view it optimistically, we have traded a world of cul-
tural and visual diversity for a more varied personal life. Or a more varied and interest-
ing intellectual and technical life.
We at Manning celebrate the inventiveness, the initiative, and the fun of the com-
puter business with book covers based on native and tribal costumes from two centu-
ries ago brought back to life by the pictures from this travel guide.
Part 1
What is Android?—
The Big Picture
Android promises to be a market-moving technology platform—not just
because of the functionality available in the platform but because of how the
platform has come to market. Part 1 of this book brings you into the picture as a
developer of the open source Android platform. We begin with a look at the
Android platform and the impact it has on each of the major “stakeholders” in
the mobile marketplace (chapter 1). We then bring you on board to developing
applications for Android with a hands-on tour of the Android development envi-
ronment (chapter 2).
3
Introducing Android
You’ve heard about Android. You’ve read about Android. Now it’s time to begin
unlocking Android.
Android is a software platform that’s revolutionizing the global cell phone mar-
ket. It’s the first open source mobile application platform that’s moved the needle
in major mobile markets around the globe. When you’re examining Android,
there are a number of technical and market-related dimensions to consider. This
first section introduces the platform and provides context to help you better under-
stand Android and where it fits in the global cell phone scene.
Android is primarily a Google effort, in collaboration with the Open Handset
Alliance. Open Handset Alliance is an alliance of nearly 50 organizations commit-
ted to bringing a “better” and more “open” mobile phone to market. Considered a
novelty at first by some, Android has grown to become a market-changing player in
a few short years, earning both respect and derision alike from peers in the industry.
This chapter introduces Android—what it is, and, equally important, what it’s
not. After reading this chapter, you’ll understand how Android is constructed, how
This chapter covers
 Exploring Android, the open source mobile platform
 Android Intents, the way things work
 Sample application
5Understanding the Android market
PLATFORM VS. DEVICE Throughout this book, wherever code must be tested
or exercised on a device, a software-based emulator is typically employed. An
exception is in chapter 14 where Bluetooth and Sensors are exercised. See
chapter 2 for information on how to set up and use the Android emulator.
The term platform refers to Android itself—the software—including all the
binaries, code libraries, and tool chains. This book focuses on the Android
platform; the Android emulators available in the SDK are simply components
of the Android platform.
With all of that as a backdrop, creating a successful mobile platform is clearly a non-
trivial task involving numerous players. Android is an ambitious undertaking, even for
Google, a company of seemingly boundless resources and moxie—and they’re getting
the job done. Within a span of two years, Android has seen four major software
releases and the release of multiple handsets across most major mobile carriers in the
global market.
Now that you’ve got an introduction to what Android is, let’s look at the why and
where of Android to provide some context and set the perspective for Android’s intro-
duction to the marketplace. After that, it’s on to exploring the platform itself!
1.2 Understanding the Android market
Android promises to have something for everyone. It aims to support a variety of hard-
ware devices, not just high-end ones typically associated with expensive smartphones.
Of course, Android users will enjoy improved performance on a more powerful
device, considering that it sports a comprehensive set of computing features. But how
well can Android scale up and down to a variety of markets and gain market and mind
share? How quickly can the smartphone market become the standard? Some folks are
still clinging to phone-only devices, even though smartphones are growing rapidly in
virtually every demographic. Let’s look at Android from the perspective of a few exist-
ing players in the marketplace. When you’re talking about the cellular market, the
place to start is at the top, with the carriers, or as they’re sometimes referred to, the
mobile operators.
1.2.1 Mobile operators
Mobile operators (the cell phone companies such as AT&T and Verizon) are in the
business, first and foremost, of selling subscriptions to their services. Shareholders
want a return on their investment, and it’s hard to imagine an industry where there’s a
larger investment than in a network that spans such broad geographic territory. To
the mobile operator, cell phones are simultaneously a conduit for services, a drug to
entice subscribers, and an annoyance to support and lock down.
Some mobile operators are embracing Android as a platform to drive new data ser-
vices across the excess capacity operators have built into their networks. Data services
represent high-premium services and high-margin revenues for the operator. If
Android can help drive those revenues for the mobile operator, all the better.
6 CHAPTER 1 Introducing Android
Other mobile operators feel threatened by Google and the potential of “free wire-
less,” driven by advertising revenues and an upheaval of the market. Another challenge
for mobile operators is that they want the final say on what services are enabled across
their networks. Historically, handset manufacturers complain that their devices are
handicapped and don’t exercise all the features designed into them because mobile
operators lack the capability or willingness to support those features. An encouraging
sign is that there are mobile operators involved in the Open Handset Alliance.
Let’s move on to a comparison of Android and existing cell phones on the market
today.
1.2.2 Android vs. the feature phones
The majority of cell phones on the market continue to be consumer flip phones and
feature phones—phones that aren’t smartphones.1
These phones are the ones consum-
ers get when they walk into the retailer and ask what can be had for free. These con-
sumers are the “I just want a phone” customers. Their primary interest is a phone for
voice communications, an address book, and increasingly, texting. They might even
want a camera. Many of these phones have additional capabilities such as mobile web
browsing, but because of relatively poor user
experience, these features aren’t employed heav-
ily. The one exception is text messaging, which is
a dominant application no matter the classifica-
tion of device. Another increasingly in-demand
category is location-based services, which typi-
cally use the Global Positioning System (GPS).
Android’s challenge is to scale down to this
market. Some of the bells and whistles in
Android can be left out to fit into lower-end
hardware. One of the big functionality gaps on
these lower-end phones is the web experience
the user gets. Part of the problem is screen size,
but equally challenging is the browser technol-
ogy itself, which often struggles to match the rich
web experience of desktop computers. Android
features the market-leading WebKit browser
engine, which brings desktop-compatible brows-
ing to the mobile arena. Figure 1.2 shows WebKit
in action on Android. If a rich web experience
can be effectively scaled down to feature phone
class hardware, it would go a long way toward
1
Only 12% of phones sold in the fourth quarter of 2008 were smartphones: http://www.gartner.com/it/
page.jsp?id=910112.
Figure 1.2 Android’s built-in browser
technology is based on WebKit’s browser
engine.
7Understanding the Android market
penetrating this end of the market. Chapter 16 takes a close look at using web devel-
opment skills for creating Android applications.
WEBKIT The WebKit (http://www.webkit.org) browser engine is an open
source project that powers the browser found in Macs (Safari) and is the
engine behind Mobile Safari, which is the browser on the iPhone. It’s not a
stretch to say that the browser experience is what makes the iPhone popular,
so its inclusion in Android is a strong plus for Android’s architecture.
Software at the lower end of the market generally falls into one of two camps:
 Qualcomm’s BREW environment—BREW stands for Binary Runtime Environment
for Wireless. For a high-volume example of BREW technology, consider Veri-
zon’s Get It Now-capable devices, which run on this platform. The challenge for
software developers who want to gain access to this market is that the bar to get
an application on this platform is high, because everything is managed by the
mobile operator, with expensive testing and revenue-sharing fee structures. The
upside to this platform is that the mobile operator collects the money and dis-
burses it to the developer after the sale, and often these sales recur monthly.
Just about everything else is a challenge to the software developer. Android’s
open application environment is more accessible than BREW.
 Java ME, or Java Platform, Micro Edition—A popular platform for this class of
device. The barrier to entry is much lower for software developers. Java ME
developers will find a same-but-different environment in Android. Android isn’t
strictly a Java ME-compatible platform, but the Java programming environment
found in Android is a plus for Java ME developers. There are some projects
underway to create a bridge environment, with the aim of enabling Java ME
applications to be compiled and run for Android. Gaming, a better browser,
and anything to do with texting or social applications present fertile territory
for Android at this end of the market.
Although the majority of cell phones sold worldwide are not considered smartphones,
the popularity of Android (and other capable platforms) has increased demand for
higher-function devices. That’s what we’re going to discuss next.
1.2.3 Android vs. the smartphones
Let’s start by naming the major smartphone players: Symbian (big outside North
America), BlackBerry from Research in Motion, iPhone from Apple, Windows
(Mobile, SmartPhone, and now Phone 7), and of course, the increasingly popular
Android platform.
One of the major concerns of the smartphone market is whether a platform can
synchronize data and access Enterprise Information Systems for corporate users.
Device-management tools are also an important factor in the enterprise market. The
browser experience is better than with the lower-end phones, mainly because of larger
8 CHAPTER 1 Introducing Android
displays and more intuitive input methods, such as a touch screen, touch pad, slide-
out keyboard, or a jog dial.
Android’s opportunity in this market is to provide a device and software that peo-
ple want. For all the applications available for the iPhone, working with Apple can be
a challenge; if the core device doesn’t suit your needs, there’s little room to maneuver
because of the limited models available and historical carrier exclusivity. Now that
email, calendaring, and contacts can sync with Microsoft Exchange, the corporate
environment is more accessible, but Android will continue to fight the battle of scal-
ing the Enterprise walls. Later Android releases have added improved support for the
Microsoft Exchange platform, though third-party solutions still out-perform the built-
in offerings. BlackBerry is dominant because of its intuitive email capabilities, and the
Microsoft platforms are compelling because of tight integration to the desktop experi-
ence and overall familiarity for Windows users. iPhone has surprisingly good integra-
tion with Microsoft Exchange—for Android to compete in this arena, it must
maintain parity with iPhone on Enterprise support.
You’ve seen how Android stacks up next to feature phones and smartphones. Next,
we’ll see whether Android, the open source mobile platform, can succeed as an open
source project.
1.2.4 Android vs. itself
Android will likely always be an open source project, but to succeed in the mobile mar-
ket, it must sell millions of units and stay fresh. Even though Google briefly entered the
device fray with its Nexus One phone, it’s not a hardware company. From necessity,
Android is sold by others such as HTC and Motorola, to name the big players. These
manufacturers start with the Android Open Source Platform (AOSP), but extend it to
meet their need to differentiate their offerings. Android isn’t the first open source
phone, but it’s the first from a player with the market-moving weight of Google leading
the charge. This market leadership position has already translated to impressive unit
sales across multiple manufacturers. So, now that there are a respectable number of
devices on the market, can Android keep it together and avoid fragmentation?
Open source is a double-edged sword. On one hand, the power of many talented
people and companies working around the globe and around the clock to deliver
desirable features is a force to be reckoned with, particularly in comparison with a tra-
ditional, commercial approach to software development. This topic has become trite
because the benefits of open source development are well documented. On the other
hand, how far will the competing manufacturers extend and potentially split Android?
Depending on your perspective, the variety of Android offerings is a welcome alterna-
tive to a more monolithic iPhone device platform where consumers have few choices
available.
Another challenge for Android is that the licensing model of open source code
used in commercial offerings can be sticky. Some software licenses are more restrictive
than others, and some of those restrictions pose a challenge to the open source label.
At the same time, Android licensees need to protect their investment, so licensing is
an important topic for the commercialization of Android.
9Understanding the Android market
1.2.5 Licensing Android
Android is released under two different open source licenses. The Linux kernel is
released under the GNU General Public License (GPL) as is required for anyone licensing
the open source OS kernel. The Android platform, excluding the kernel, is licensed
under the Apache Software License (ASL). Although both licensing models are open
source-oriented, the major difference is that the Apache license is considered friend-
lier toward commercial use. Some open source purists might find fault with anything
but complete openness, source-code sharing, and noncommercialization; the ASL
attempts to balance the goals of open source with commercial market forces. So far
there has been only one notable licensing hiccup impacting the Android mod com-
munity, and that had more to do with the gray area of full system images than with a
manufacturer’s use of Android on a mainstream product release. Currently, Android
is facing intellectual property challenges; both Microsoft and Apple are bringing liti-
gation against Motorola and HTC for the manufacturer’s Android-based handsets.
The high-level, market-oriented portion of the book has now concluded! The
remainder of this book is focused on Android application development. Any technical
discussion of a software environment must include a review of the layers that compose
the environment, sometimes referred to as a stack because of the layer-upon-layer con-
struction. Next up is a high-level breakdown of the components of the Android stack.
Selling applications
A mobile platform is ultimately valuable only if there are applications to use and enjoy
on that platform. To that end, the topic of buying and selling applications for Android
is important and gives us an opportunity to highlight a key difference between Android
and the iPhone. The Apple AppStore contains software titles for the iPhone—lots of
them. But Apple’s somewhat draconian grip on the iPhone software market requires
that all applications be sold through its venue. Although Apple’s digital rights man-
agement (DRM) is the envy of the market, this approach can pose a challenging envi-
ronment for software developers who might prefer to make their application available
through multiple distribution channels.
Contrast Apple’s approach to application distribution with the freedom an Android
developer enjoys to ship applications via traditional venues such as freeware and
shareware, and commercially through various marketplaces, including his own web-
site! For software publishers who want the focus of an on-device shopping experi-
ence, Google has launched and continues to mature the Android Market. For software
developers who already have titles for other platforms such as Windows Mobile,
Palm, or BlackBerry, traditional software markets such as Handango (http://
www.Handango.com) also support selling Android applications. Handango and its ilk
are important outlets; consumers new to Android will likely visit sites such as Han-
dango because that might be where they first purchased one of their favorite applica-
tions for their prior device.
11The layers of Android
TIP Without question, Android development requires Java programming
skills. To get the most out of this book, be sure to brush up on your Java pro-
gramming knowledge. There are many Java references on the internet, and no
shortage of Java books on the market. An excellent source of Java titles can be
found at http://www.manning.com/catalog/java.
Now that we’ve shown you the obligatory stack diagram and introduced all the layers,
let’s look more in depth at the runtime technology that underpins Android.
1.3.1 Building on the Linux kernel
Android is built on a Linux kernel and on an advanced, optimized VM for its Java
applications. Both technologies are crucial to Android. The Linux kernel component
of the Android stack promises agility and portability to take advantage of numerous
hardware options for future Android-equipped phones. Android’s Java environment
is key: It makes Android accessible to programmers because of both the number of
Java software developers and the rich environment that Java programming has to
offer.
Why use Linux for a phone? Using a full-featured platform such as the Linux ker-
nel provides tremendous power and capabilities for Android. Using an open source
foundation unleashes the capabilities of talented individuals and companies to move
the platform forward. Such an arrangement is particularly important in the world of
mobile devices, where products change so rapidly. The rate of change in the mobile
market makes the general computer market look slow and plodding. And, of course,
the Linux kernel is a proven core platform. Reliability is more important than perfor-
mance when it comes to a mobile phone, because voice communication is the primary
use of a phone. All mobile phone users, whether buying for personal use or for a busi-
ness, demand voice reliability, but they still want cool data features and will purchase a
device based on those features. Linux can help meet this requirement.
Speaking to the rapid rate of phone turnover and accessories hitting the market,
another advantage of using Linux as the foundation of the Android platform stack is
that it provides a hardware abstraction layer; the upper levels remain unchanged
despite changes in the underlying hardware. Of course, good coding practices
demand that user applications fail gracefully in the event a resource isn’t available,
such as a camera not being present in a particular handset model. As new accessories
appear on the market, drivers can be written at the Linux level to provide support, just
as on other Linux platforms. This architecture is already demonstrating its value;
Android devices are already available on distinct hardware platforms. HTC, Motorola,
and others have released Android-based devices built on their respective hardware
platforms. User applications, as well as core Android applications, are written in Java
and are compiled into byte codes. Byte codes are interpreted at runtime by an inter-
preter known as a virtual machine (VM).
12 CHAPTER 1 Introducing Android
1.3.2 Running in the Dalvik VM
The Dalvik VM is an example of the need for efficiency, the desire for a rich program-
ming environment, and even some intellectual property constraints, colliding, with
innovation as the result. Android’s Java environment provides a rich application plat-
form and is accessible because of the popularity of Java itself. Also, application perfor-
mance, particularly in a low-memory setting such as you find in a mobile phone, is
paramount for the mobile market. But this isn’t the only issue at hand.
Android isn’t a Java ME platform. Without commenting on whether this is ulti-
mately good or bad for Android, there are other forces at play here. There’s the mat-
ter of Java VM licensing from Oracle. From a high level, Android’s code environment
is Java. Applications are written in Java, which is compiled to Java byte codes and sub-
sequently translated to a similar but different representation called dex files. These
files are logically equivalent to Java byte codes, but they permit Android to run its
applications in its own VM that’s both (arguably) free from Oracle’s licensing clutches
and an open platform upon which Google, and potentially the open source commu-
nity, can improve as necessary. Android is facing litigation challenges from Oracle
about the use of Java.
NOTE From the mobile application developer’s perspective, Android is a Java
environment, but the runtime isn’t strictly a Java VM. This accounts for the
incompatibilities between Android and proper Java environments and librar-
ies. If you have a code library that you want to reuse, your best bet is to assume
that your code is nearly source compatible, attempt to compile it into an
Android project, then determine how close you are to having usable code.
The important things to know about the Dalvik VM are that Android applications run
inside it and that it relies on the Linux kernel for services such as process, memory,
and filesystem management.
Now that we’ve discussed the foundational technologies in Android, it’s time to
focus on Android application development. The remainder of this chapter discusses
high-level Android application architecture and introduces a simple Android applica-
tion. If you’re not comfortable or ready to begin coding, you might want to jump to
chapter 2, where we introduce the development environment step-by-step.
1.4 The Intent of Android development
Let’s jump into the fray of Android development, focus on an important component
of the Android platform, and expand to take a broader view of how Android applica-
tions are constructed.
An important and recurring theme of Android development is the Intent. An
Intent in Android describes what you want to do. An Intent might look like “I want
to look up a contact record” or “Please launch this website” or “Show the order confir-
mation screen.” Intents are important because they not only facilitate navigation in
an innovative way, as we’ll discuss next, they also represent the most important aspect
of Android coding. Understand the Intent and you’ll understand Android.
13The Intent of Android development
NOTE Instructions for setting up the Eclipse development environment are
in appendix A. This environment is used for all Java examples in this book.
Chapter 2 goes into more detail on setting up and using the development
tools.
The code examples in this chapter are primarily for illustrative purposes.
We reference and introduce classes without necessarily naming specific Java
packages. Subsequent chapters take a more rigorous approach to introducing
Android-specific packages and classes.
Next, we’ll look at the foundational information about why Intents are important,
then we’ll describe how Intents work. Beyond the introduction of the Intent, the
remainder of this chapter describes the major elements of Android application devel-
opment, leading up to and including the first complete Android application that
you’ll develop.
1.4.1 Empowering intuitive UIs
The power of Android’s application framework lies in the way it brings a web mindset
to mobile applications. This doesn’t mean the platform has only a powerful browser
and is limited to clever JavaScript and server-side resources, but rather it goes to the
core of how the Android platform works and how users interact with the mobile
device. The power of the internet is that everything is just a click away. Those clicks are
known as Uniform Resource Locators (URLs), or alternatively, Uniform Resource Identifiers
(URIs). Using effective URIs permits easy and quick access to the information users
need and want every day. “Send me the link” says it all.
Beyond being an effective way to get access to data, why is this URI topic important,
and what does it have to do with Intents? The answer is nontechnical but crucial: The
way a mobile user navigates on the platform is crucial to its commercial success. Plat-
forms that replicate the desktop experience on a mobile device are acceptable to only
a small percentage of hardcore power users. Deep menus and multiple taps and clicks
are generally not well received in the mobile market. The mobile application, more
than in any other market, demands intuitive ease of use. A consumer might buy a
device based on cool features that were enumerated in the marketing materials, but
that same consumer is unlikely to even touch the instruction manual. A UI’s usability
is highly correlated with its market penetration. UIs are also a reflection of the plat-
form’s data access model, so if the navigation and data models are clean and intuitive,
the UI will follow suit.
Now we’re going to introduce Intents and IntentFilters, Android’s innovative
navigation and triggering mechanisms.
1.4.2 Intents and how they work
Intents and IntentFilters bring the “click on it” paradigm to the core of mobile
application use (and development) for the Android platform:
14 CHAPTER 1 Introducing Android
 An Intent is a declaration of need. It’s made up of a number of pieces of infor-
mation that describe the desired action or service. We’re going to examine the
requested action and, generically, the data that accompanies the requested
action.
 An IntentFilter is a declaration of capability and interest in offering assis-
tance to those in need. It can be generic or specific with respect to which
Intents it offers to service.
The action attribute of an Intent is typically a verb; for example VIEW, PICK, or EDIT. A
number of built-in Intent actions are defined as members of the Intent class, but
application developers can create new actions as well. To view a piece of information,
an application employs the following Intent action:
android.content.Intent.ACTION_VIEW
The data component of an Intent is expressed in the form of a URI and can be virtu-
ally any piece of information, such as a contact record, a website location, or a refer-
ence to a media clip. Table 1.1 lists some Android URI examples.
The IntentFilter defines the relationship between the Intent and the application.
IntentFilters can be specific to the data portion of the Intent, the action portion,
or both. IntentFilters also contain a field known as a category. The category helps
classify the action. For example, the category named CATEGORY_LAUNCHER instructs
Android that the Activity containing this IntentFilter should be visible in the
main application launcher or home screen.
When an Intent is dispatched, the system evaluates the available Activitys,
Services, and registered BroadcastReceivers (more on these in section 1.5) and dis-
patches the Intent to the most appropriate recipient. Figure 1.4 depicts this relation-
ship among Intents, IntentFilters, and BroadcastReceivers.
IntentFilters are often defined in an application’s AndroidManifest.xml file with
the <intent-filter> tag. The AndroidManifest.xml file is essentially an application
descriptor file, which we’ll discuss later in this chapter.
A common task on a mobile device is looking up a specific contact record for the
purpose of initiating a call, sending a text message, or looking up a snail-mail address
when you’re standing in line at the neighborhood pack-and-ship store. Or a user
might want to view a specific piece of information, say a contact record for user 1234.
In these cases, the action is ACTION_VIEW and the data is a specific contact record
Table 1.1 Commonly employed URIs in Android
Type of information URI data
Contact lookup content://contacts/people
Map lookup/search Geo:0,0?q=23+Route+206+Stanhope+NJ
Browser launch to a specific website http://www.google.com/
16 CHAPTER 1 Introducing Android
helpful when you know exactly which Activity you want to handle the Intent and
you don’t want to leave anything to chance in terms of what code is executed. To cre-
ate an explicit Intent, use the overloaded Intent constructor, which takes a class as
an argument:
public void onClick(View v) {
try {
startActivityForResult(new Intent(v.getContext(),RefreshJobs.class),0);
} catch (Exception e) {
. . .
}
}
These examples show how an Android developer creates an Intent and asks for it to be
handled. Similarly, an Android application can be deployed with an IntentFilter,
indicating that it responds to Intents that were already defined on the system, thereby
publishing new functionality for the platform. This facet alone should bring joy to
independent software vendors (ISVs) who’ve made a living by offering better contact
managers and to-do list management software titles for other mobile platforms.
Intent resolution, or dispatching, takes place at runtime, as opposed to when the
application is compiled. You can add specific Intent-handling features to a device,
which might provide an upgraded or more desirable set of functionality than the orig-
inal shipping software. This runtime dispatching is also referred to as late binding.
Thus far, this discussion of Intents has focused on the variety of Intents that cause
UI elements to be displayed. Other Intents are more event-driven than task-oriented,
as our earlier contact record example described. For example, you also use the Intent
class to notify applications that a text message has arrived. Intents are a central ele-
ment to Android; we’ll revisit them on more than one occasion.
Now that we’ve explained Intents as the catalyst for navigation and event flow on
Android, let’s jump to a broader view and discuss the Android application lifecycle
and the key components that make Android tick. The Intent will come into better
focus as we further explore Android throughout this book.
The power and the complexity of Intents
It’s not hard to imagine that an absolutely unique user experience is possible with
Android because of the variety of Activitys with specific IntentFilters that are
installed on any given device. It’s architecturally feasible to upgrade various aspects
of an Android installation to provide sophisticated functionality and customization.
Though this might be a desirable characteristic for the user, it can be troublesome
for someone providing tech support who has to navigate a number of components
and applications to troubleshoot a problem.
Because of the potential for added complexity, this approach of ad hoc system patch-
ing to upgrade specific functionality should be entertained cautiously and with your
eyes wide open to the potential pitfalls associated with this approach.
17Four kinds of Android components
1.5 Four kinds of Android components
Let’s build on your knowledge of the Intent and IntentFilter classes and explore
the four primary components of Android applications, as well as their relation to the
Android process model. We’ll include code snippets to provide a taste of Android
application development. We’re going to leave more in-depth examples and discus-
sion for later chapters.
NOTE A particular Android application might not contain all of these ele-
ments, but will have at least one of these elements, and could have all of
them.
1.5.1 Activity
An application might have a UI, but it doesn’t have to have one. If it has a UI, it’ll have
at least one Activity.
The easiest way to think of an Android Activity is to relate it to a visible screen,
because more often than not there’s a one-to-one relationship between an Activity
and a UI screen. This relationship is similar to that of a controller in the MVC paradigm.
Android applications often contain more than one Activity. Each Activity dis-
plays a UI and responds to system- and user-initiated events. The Activity employs
one or more Views to present the actual UI elements to the user. The Activity class is
extended by user classes, as shown in the following listing.
package com.msi.manning.chapter1;
import android.app.Activity;
import android.os.Bundle;
public class Activity1 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
The Activity class is part of the android.app Java package, found in the Android
runtime. The Android runtime is deployed in the android.jar file. The class
Activity1 extends the class Activity, which we’ll examine in detail in chapter 3.
One of the primary tasks an Activity performs is displaying UI elements, which are
implemented as Views and are typically defined in XML layout files. Chapter 3 goes
into more detail on Views and Resources.
Moving from one Activity to another is accomplished with the startActivity()
method or the startActivityForResult() method when you want a synchronous
call/result paradigm. The argument to these methods is an instance of an Intent.
The Activity represents a visible application component within Android. With
assistance from the View class, which we’ll cover in chapter 3, the Activity is the most
Listing 1.1 A basic Activity in an Android application
18 CHAPTER 1 Introducing Android
commonly employed Android application component. The next topic of interest is
the Service, which runs in the background and doesn’t generally present a direct UI.
1.5.2 Service
If an application is to have a long lifecycle, it’s often best to put it into a Service. For
example, a background data synchronization utility should be implemented as a
Service. A best practice is to launch Services on a periodic or as-needed basis, trig-
gered by a system alarm, and then have the Service terminate when its task is complete.
Like the Activity, a Service is a class in the Android runtime that you should
extend, as shown in the following listing. This example extends a Service, and peri-
odically publishes an informative message to the Android log.
package com.msi.manning.chapter1;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class Service1 extends Service implements Runnable {
public static final String tag = "service1";
private int counter = 0;
@Override
protected void onCreate() {
super.onCreate();
Thread aThread = new Thread (this);
aThread.start();
}
public void run() {
while (true) {
try {
Log.i(tag,"service1 firing : # " + counter++);
Thread.sleep(10000);
} catch(Exception ee) {
Log.e(tag,ee.getMessage());
}
}
}
Listing 1.2 A simple example of an Android Service
You say Intent; I say Intent
The Intent class is used in similar sounding but very different scenarios.
Some Intents are used to assist in navigating from one Activity to the next, such
as the example given earlier of viewing a contact record. Activities are the targets of
these kinds of Intents, which are used with the startActivity or startActivi-
tyForResult methods.
Also, a Service can be started by passing an Intent to the startService method.
BroadcastReceivers receive Intents when responding to system-wide events,
such as a ringing phone or an incoming text message.
Extend
Service
class
B
InitializationC
19Four kinds of Android components
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
This example requires that the package android.app.Service be imported. This
package contains the Service class. This example also demonstrates Android’s log-
ging mechanism android.util.Log, which is useful for debugging purposes. (Many
examples in this book include using the logging facility. We’ll discuss logging in more
depth in chapter 2.) The Service1 class B extends the Service class. This class
implements the Runnable interface to perform its main task on a separate thread. The
onCreate method C of the Service class permits the application to perform initial-
ization-type tasks. We’re going to talk about the onBind() method D in further detail
in chapter 4, when we’ll explore the topic of interprocess communication in general.
Services are started with the startService(Intent) method of the abstract
Context class. Note that, again, the Intent is used to initiate a desired result on the
platform.
Now that the application has a UI in an Activity and a means to have a back-
ground task via an instance of a Service, it’s time to explore the BroadcastReceiver,
another form of Android application that’s dedicated to processing Intents.
1.5.3 BroadcastReceiver
If an application wants to receive and respond to a global event, such as a ringing
phone or an incoming text message, it must register as a BroadcastReceiver. An
application registers to receive Intents in one of the following ways:
 The application can implement a <receiver> element in the Android-
Manfest.xml file, which describes the BroadcastReceiver’s class name and enu-
merates its IntentFilters. Remember, the IntentFilter is a descriptor of the
Intent an application wants to process. If the receiver is registered in the
AndroidManifest.xml file, the application doesn’t need to be running in order
to be triggered. When the event occurs, the application is started automatically
upon notification of the triggering event. Thankfully, all this housekeeping is
managed by the Android OS itself.
 An application can register at runtime via the Context class’s register-
Receiver method.
Like Services, BroadcastReceivers don’t have a UI. Even more importantly, the code
running in the onReceive method of a BroadcastReceiver should make no assump-
tions about persistence or long-running operations. If the BroadcastReceiver
requires more than a trivial amount of code execution, it’s recommended that the
code initiate a request to a Service to complete the requested functionality because
the Service application component is designed for longer-running operations
whereas the BroadcastReceiver is meant for responding to various triggers.
Handle
Binding request
D
20 CHAPTER 1 Introducing Android
NOTE The familiar Intent class is used in triggering BroadcastReceivers.
The parameters will differ, depending on whether you’re starting an Activ-
ity, a Service, or a BroadcastReceiver, but it’s the same Intent class
that’s used throughout the Android platform.
A BroadcastReceiver implements the abstract method onReceive to process incom-
ing Intents. The arguments to the method are a Context and an Intent. The method
returns void, but a handful of methods are useful for passing back results, including
setResult, which passes back to the invoker an integer return code, a String return
value, and a Bundle value, which can contain any number of objects.
The following listing is an example of a BroadcastReceiver triggering upon
receipt of an incoming text message.
package com.msi.manning.unlockingandroid;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import.android.content.BroadcastReceiver
public class MySMSMailBox extends BroadcastReceiver {
public static final String tag = "MySMSMailBox";
@Override
public void onReceive(Context context, Intent intent) {
Log.i(tag,"onReceive");
if (intent.getAction().equals
("android.provider.Telephony.SMS_RECEIVED")) {
Log.i(tag,"Found our Event!");
}
}
We need to discuss a few items in this listing. The class MySMSMailBox extends the
BroadcastReceiver class. This subclass approach is the most straightforward way to
employ a BroadcastReceiver. (Note the class name MySMSMailBox; it’ll be used in the
AndroidManifest.xml file, shown in listing 1.4.) The tag variable B is used in con-
junction with the logging mechanism to assist in labeling messages sent to the console
log on the emulator. Using a tag in the log enables us to filter and organize log mes-
sages in the console. (We discuss the log mechanism in more detail in chapter 2.) The
onReceive method is where all the work takes place in a BroadcastReceiver; you
must implement this method. A given BroadcastReceiver can register multiple
IntentFilters. A BroadcastReceiver can be instantiated for an arbitrary number of
Intents.
It’s important to make sure that the application handles the appropriate Intent by
checking the action of the incoming Intent C. When the application receives the
desired Intent, it should carry out the specific functionality that’s required. A com-
mon task in an SMS-receiving application is to parse the message and display it to the
user via the capabilities found in the NotificationManager. (We’ll discuss notifica-
tions in chapter 8.) In listing 1.3, we simply record the action to the log.
Listing 1.3 A sample BroadcastReceiver
Tag used
in logging
B
Check
Intent’s action
C
21Four kinds of Android components
In order for this BroadcastReceiver to fire and receive this Intent, the Broadcast-
Receiver is listed in the AndroidManifest.xml file, along with an appropriate intent-
filter tag, as shown in the following listing. This listing contains the elements
required for the application to respond to an incoming text message.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.msi.manning.unlockingandroid">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<application android:icon="@drawable/icon">
<activity android:name=".Activity1" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MySMSMailBox" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
Certain tasks within the Android platform require the application to have a designated
privilege. To give an application the required permissions, use the <uses-
permission> tag B. (We’ll discuss this tag in detail in section 1.6.) The <receiver>
tag contains the class name of the class implementing the BroadcastReceiver. In this
example, the class name is MySMSMailBox, from the package com.msi.manning.
unlockingandroid. Be sure to note the dot that precedes the name C. This dot is
required. If your application isn’t behaving as expected, one of the first places to
check is your Android.xml file, and look for the dot before the class name! The
IntentFilter is defined in the <intent-filter> tag. The desired action in this
Listing 1.4 AndroidManifest.xml
BRequired permission
Receiver tag;
note dot prefix
C
Testing SMS
The emulator has a built-in set of tools for manipulating certain telephony behavior
to simulate a variety of conditions, such as in-network and out-of-network coverage
and placing phone calls.
To send an SMS message to the emulator, telnet to port 5554 (the port number
might vary on your system), which will connect to the emulator, and issue the follow-
ing command at the prompt:
sms send <sender's phone number> <body of text message>
To learn more about available commands, type help at the prompt.
We’ll discuss these tools in more detail in chapter 2.
22 CHAPTER 1 Introducing Android
example is android.provider.Telephony.SMS_RECEIVED. The Android SDK contains
the available actions for the standard Intents. Also, remember that user applications
can define their own Intents, as well as listen for them.
Now that we’ve introduced Intents and the Android classes that process or handle
Intents, it’s time to explore the next major Android application topic: the Content-
Provider, Android’s preferred data-publishing mechanism.
1.5.4 ContentProvider
If an application manages data and needs to expose that data to other applications
running in the Android environment, you should consider a ContentProvider. If an
application component (Activity, Service, or BroadcastReceiver) needs to access
data from another application, the component accesses the other application’s
ContentProvider. The ContentProvider implements a standard set of methods to
permit an application to access a data store. The access might be for read or write
operations, or for both. A ContentProvider can provide data to an Activity or
Service in the same containing application, as well as to an Activity or Service con-
tained in other applications.
A ContentProvider can use any form of data storage mechanism available on the
Android platform, including files, SQLite databases, or even a memory-based hash
map if data persistence isn’t required. The ContentProvider is a data layer that pro-
vides data abstraction for its clients and centralizing storage and retrieval routines in a
single place.
Sharing files or databases directly is discouraged on the Android platform, and is
enforced by the underlying Linux security system, which prevents ad hoc file access
from one application space to another without explicitly granted permissions.
Data stored in a ContentProvider can be traditional data types, such as integers
and strings. Content providers can also manage binary data, such as image data. When
binary data is retrieved, the suggested best practice is to return a string representing
the filename that contains the binary data. If a filename is returned as part of a
ContentProvider query, the application shouldn’t access the file directly; you should
use the helper class, ContentResolver’s openInputStream method, to access the
binary data. This approach navigates the Linux process and security hurdles, as well as
keeps all data access normalized through the ContentProvider. Figure 1.5 outlines
the relationship among ContentProviders, data stores, and their clients.
A ContentProvider’s data is accessed by an Android application through a Con-
tent URI. A ContentProvider defines this URI as a public static final String. For
example, an application might have a data store managing material safety data sheets.
The Content URI for this ContentProvider might look like this:
public static final Uri CONTENT_URI =
Uri.parse("content://com.msi.manning.provider.unlockingandroid/datasheets");
From this point, accessing a ContentProvider is similar to using Structured Query
Language (SQL) in other platforms, though a complete SQL statement isn’t
employed. A query is submitted to the ContentProvider, including the columns
24 CHAPTER 1 Introducing Android
1.6 Understanding the AndroidManifest.xml file
In the preceding sections, we introduced the common elements of an Android appli-
cation. A fundamental fact of Android development is that an Android application
contains at least one Activity, Service, BroadcastReceiver, or ContentProvider.
Some of these elements advertise the Intents they’re interested in processing via the
IntentFilter mechanism. All these pieces of information need to be tied together
for an Android application to execute. The glue mechanism for this task of defining
relationships is the AndroidManifest.xml file.
The AndroidManifest.xml file exists in the root of an application directory and
contains all the design-time relationships of a specific application and Intents.
AndroidManfest.xml files act as deployment descriptors for Android applications. The
following listing is an example of a simple AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.msi.manning.unlockingandroid">
<application android:icon="@drawable/icon">
<activity android:name=".Activity1" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Looking at this simple AndroidManifest.xml file, you see that the manifest element
contains the obligatory namespace, as well as the Java package name containing this
application. This application contains a single Activity, with the class name
Activity1. Note also the @string syntax. Any time an @ symbol is used in an
AndroidManifest.xml file, it references information stored in one of the resource
files. In this case, the label attribute is obtained from the string resource identified as
app_name. (We discuss resources in further detail later in chapter 3.) This applica-
tion’s lone Activity contains a single IntentFilter definition. The IntentFilter
used here is the most common IntentFilter seen in Android applications. The
action android.intent.action.MAIN indicates that this is an entry point to the appli-
cation. The category android.intent.category.LAUNCHER places this Activity in
the launcher window, as shown in figure 1.6. It’s possible to have multiple Activity
elements in a manifest file (and thereby an application), with zero or more of them
visible in the launcher window.
In addition to the elements used in the sample manifest file shown in listing 1.5,
other common tags are:
 The <service> tag represents a Service. The attributes of the <service> tag
include its class and label. A Service might also include the <intent-filter>
tag.
Listing 1.5 AndroidManifest.xml file for a basic Android application
25Mapping applications to processes
 The <receiver> tag represents a
BroadcastReceiver, which might have
an explicit <intent-filter> tag.
 The <uses-permission> tag tells
Android that this application requires
certain security privileges. For exam-
ple, if an application requires access to
the contacts on a device, it requires the
following tag in its AndroidMani-
fest.xml file:
<uses-permission android:name=
"android.permission.READ_CONTACTS" />
We’ll revisit the AndroidManifest.xml file a
number of times throughout the book because
we need to add more details about certain ele-
ments and specific coding scenarios.
Now that you have a basic understanding of
the Android application and the AndroidMani-
fest.xml file, which describes its components,
it’s time to discuss how and where an Android
application executes. To do that, we need to
talk about the relationship between an
Android application and its Linux and Dalvik
VM runtime.
1.7 Mapping applications to
processes
Android applications each run in a single
Linux process. Android relies on Linux for pro-
cess management, and the application itself runs in an instance of the Dalvik VM. The
OS might need to unload, or even kill, an application from time to time to accommo-
date resource allocation demands. The system uses a hierarchy or sequence to select
the victim during a resource shortage. In general, the system follows these rules:
 Visible, running activities have top priority.
 Visible, nonrunning activities are important, because they’re recently paused
and are likely to be resumed shortly.
 Running services are next in priority.
 The most likely candidates for termination are processes that are empty
(loaded perhaps for performance-caching purposes) or processes that have
dormant Activitys.
Let’s apply some of what you’ve learned by building your first Android application.
Figure 1.6 Applications are listed in the
launcher based on their IntentFilter. In
this example, the application Where Do You
Live is available in the LAUNCHER category.
26 CHAPTER 1 Introducing Android
1.8 Creating an Android application
Let’s look at a simple Android application consisting of a single Activity, with one
View. The Activity collects data (a street address) and creates an Intent to find this
address. The Intent is ultimately dispatched to Google Maps. Figure 1.7 is a screen
shot of the application running on the emulator. The name of the application is
Where Do You Live.
ps -a
The Linux environment is complete, including process management. You can launch
and kill applications directly from the shell on the Android platform, but this is a
developer’s debugging task, not something the average Android handset user is
likely to carry out. It’s nice to have this option for troubleshooting application issues.
It’s a relatively recent phenomenon to be able to touch the metal of a mobile phone
in this way. For more in-depth exploration of the Linux foundations of Android, see
chapter 13.
Figure 1.7 This Android application demonstrates a simple Activity and Intent.
27Creating an Android application
As we previously stated, the AndroidManifest.xml file contains the descriptors for
the application components of the application. This application contains a single
Activity named AWhereDoYouLive. The application’s AndroidManifest.xml file is
shown in the following listing.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.msi.manning.unlockingandroid">
<application android:icon="@drawable/icon">
<activity android:name=".AWhereDoYouLive"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
The sole Activity is implemented in the file AWhereDoYouLive.java, shown in the
following listing.
package com.msi.manning.unlockingandroid;
// imports omitted for brevity
public class AWhereDoYouLive extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
final EditText addressfield =
(EditText) findViewById(R.id.address);
final Button button = (Button)
findViewById(R.id.launchmap);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
try {
String address = addressfield.getText().toString();
address = address.replace(' ', '+');
Intent geoIntent = new Intent
(android.content.Intent.ACTION_VIEW,
Uri.parse("geo:0,0?q=" + address));
startActivity(geoIntent);
} catch (Exception e) {
}
}
});
}
}
Listing 1.6 AndroidManifest.xml for the Where Do You Live application
Listing 1.7 Implementing the Android Activity in AWhereDoYouLive.java
B Get
address
C Prepare
Intent
28 CHAPTER 1 Introducing Android
In this example application, the setContentView method creates the primary UI,
which is a layout defined in main.xml in the /res/layout directory. The EditText view
collects information, which in this case is an address. The EditText view is a text box
or edit box in generic programming parlance. The findViewById method connects
the resource identified by R.id.address to an instance of the EditText class.
A Button object is connected to the launchmap UI element, again using the find-
ViewById method. When this button is clicked, the application obtains the entered
address by invoking the getText method of the associated EditText B.
When the address has been retrieved from the UI, we need to create an Intent to
find the entered address. The Intent has a VIEW action, and the data portion repre-
sents a geographic search query C.
Finally, the application asks Android to perform the Intent, which ultimately
results in the mapping application displaying the chosen address. The startActivity
method is invoked, passing in the prepared Intent.
Resources are precompiled into a special class known as the R class, as shown in
listing 1.8. The final members of this class represent UI elements. You should never
modify the R.java file manually; it’s automatically built every time the underlying
resources change. (We’ll cover Android resources in greater depth in chapter 3.)
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.msi.manning.unlockingandroid;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class id {
public static final int address=0x7f050000;
public static final int launchmap=0x7f050001;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040000;
}
}
Figure 1.7 shows the sample application in action. Someone looked up the address of
the White House; the result shows the White House pinpointed on the map.
Listing 1.8 R.java contains the R class, which has UI element identifiers
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011
Android in action 2nd edition 2011

Más contenido relacionado

Similar a Android in action 2nd edition 2011

Manning.silverlight.4.in.action.sep.2010
Manning.silverlight.4.in.action.sep.2010Manning.silverlight.4.in.action.sep.2010
Manning.silverlight.4.in.action.sep.2010Longhui Li
 
Arduino Cookbook.pdf
Arduino Cookbook.pdfArduino Cookbook.pdf
Arduino Cookbook.pdfTracy Hill
 
Google Nexus S mobile english_android users guide_2.3-103
Google Nexus S mobile english_android users guide_2.3-103Google Nexus S mobile english_android users guide_2.3-103
Google Nexus S mobile english_android users guide_2.3-103StevDev64
 
Twelve ways to make your apps suck less
Twelve ways to make your apps suck lessTwelve ways to make your apps suck less
Twelve ways to make your apps suck lessFons Sonnemans
 
Chat Application | RSD
Chat Application | RSDChat Application | RSD
Chat Application | RSDRajon
 
CDMA1X Pilot Panorama introduction
CDMA1X Pilot Panorama introductionCDMA1X Pilot Panorama introduction
CDMA1X Pilot Panorama introductionTempus Telcosys
 
ptg18221866ptg18221866The Practice of System and.docx
ptg18221866ptg18221866The Practice of System and.docxptg18221866ptg18221866The Practice of System and.docx
ptg18221866ptg18221866The Practice of System and.docxpotmanandrea
 
2002 Great Global Grid Book
2002 Great Global Grid Book 2002 Great Global Grid Book
2002 Great Global Grid Book Bob Marcus
 
Apple iPhone App Programming Guide
Apple iPhone App Programming GuideApple iPhone App Programming Guide
Apple iPhone App Programming GuideYusuf Karoma
 
Art of Java Web Development.pdf
Art of Java Web Development.pdfArt of Java Web Development.pdf
Art of Java Web Development.pdfNancy Rinehart
 
Docker-in-Action 1st edition.pdf
Docker-in-Action 1st edition.pdfDocker-in-Action 1st edition.pdf
Docker-in-Action 1st edition.pdfaNDREUETgARCIA
 
Android icecream sandwich
Android icecream sandwichAndroid icecream sandwich
Android icecream sandwichMayur Dharukiya
 
OReilly-Web-Application-Security-NGINX.pdf
OReilly-Web-Application-Security-NGINX.pdfOReilly-Web-Application-Security-NGINX.pdf
OReilly-Web-Application-Security-NGINX.pdfRazaMehmood7
 
Symbol MC32N0 | SAP Business One for Hana
Symbol MC32N0 | SAP Business One for HanaSymbol MC32N0 | SAP Business One for Hana
Symbol MC32N0 | SAP Business One for HanaTienda en línea
 

Similar a Android in action 2nd edition 2011 (20)

Manning.silverlight.4.in.action.sep.2010
Manning.silverlight.4.in.action.sep.2010Manning.silverlight.4.in.action.sep.2010
Manning.silverlight.4.in.action.sep.2010
 
Arduino Cookbook.pdf
Arduino Cookbook.pdfArduino Cookbook.pdf
Arduino Cookbook.pdf
 
Android
AndroidAndroid
Android
 
Google Nexus S mobile english_android users guide_2.3-103
Google Nexus S mobile english_android users guide_2.3-103Google Nexus S mobile english_android users guide_2.3-103
Google Nexus S mobile english_android users guide_2.3-103
 
Twelve ways to make your apps suck less
Twelve ways to make your apps suck lessTwelve ways to make your apps suck less
Twelve ways to make your apps suck less
 
Chat Application | RSD
Chat Application | RSDChat Application | RSD
Chat Application | RSD
 
CDMA1X Pilot Panorama introduction
CDMA1X Pilot Panorama introductionCDMA1X Pilot Panorama introduction
CDMA1X Pilot Panorama introduction
 
ptg18221866ptg18221866The Practice of System and.docx
ptg18221866ptg18221866The Practice of System and.docxptg18221866ptg18221866The Practice of System and.docx
ptg18221866ptg18221866The Practice of System and.docx
 
Android
Android Android
Android
 
Android online Training
Android online TrainingAndroid online Training
Android online Training
 
Presentation1
Presentation1Presentation1
Presentation1
 
2002 Great Global Grid Book
2002 Great Global Grid Book 2002 Great Global Grid Book
2002 Great Global Grid Book
 
Apple iPhone App Programming Guide
Apple iPhone App Programming GuideApple iPhone App Programming Guide
Apple iPhone App Programming Guide
 
Art of Java Web Development.pdf
Art of Java Web Development.pdfArt of Java Web Development.pdf
Art of Java Web Development.pdf
 
Docker-in-Action 1st edition.pdf
Docker-in-Action 1st edition.pdfDocker-in-Action 1st edition.pdf
Docker-in-Action 1st edition.pdf
 
Android icecream sandwich
Android icecream sandwichAndroid icecream sandwich
Android icecream sandwich
 
OReilly-Web-Application-Security-NGINX.pdf
OReilly-Web-Application-Security-NGINX.pdfOReilly-Web-Application-Security-NGINX.pdf
OReilly-Web-Application-Security-NGINX.pdf
 
ANDROID NEW EDITION
ANDROID NEW EDITIONANDROID NEW EDITION
ANDROID NEW EDITION
 
Discover Meteor
Discover MeteorDiscover Meteor
Discover Meteor
 
Symbol MC32N0 | SAP Business One for Hana
Symbol MC32N0 | SAP Business One for HanaSymbol MC32N0 | SAP Business One for Hana
Symbol MC32N0 | SAP Business One for Hana
 

Más de Simba Samuel

Manual do curso de cftv
Manual do curso de cftvManual do curso de cftv
Manual do curso de cftvSimba Samuel
 
012 computacao forense
012   computacao forense012   computacao forense
012 computacao forenseSimba Samuel
 
Ubuntu guia do_iniciante-2-0
Ubuntu guia do_iniciante-2-0Ubuntu guia do_iniciante-2-0
Ubuntu guia do_iniciante-2-0Simba Samuel
 
Capítulo 3 funcionalidades e protocolos da camada de aplicação
Capítulo 3   funcionalidades e protocolos da camada de aplicaçãoCapítulo 3   funcionalidades e protocolos da camada de aplicação
Capítulo 3 funcionalidades e protocolos da camada de aplicaçãoSimba Samuel
 
Linguagem de-programacao-html 2
Linguagem de-programacao-html 2Linguagem de-programacao-html 2
Linguagem de-programacao-html 2Simba Samuel
 
Segurança de informação1
Segurança de informação1Segurança de informação1
Segurança de informação1Simba Samuel
 
Projecto de Programação de Aluno(Samuel)
Projecto de Programação de Aluno(Samuel)Projecto de Programação de Aluno(Samuel)
Projecto de Programação de Aluno(Samuel)Simba Samuel
 
Mgp sisp --plano_de_gerenciamento_do_projeto
Mgp sisp --plano_de_gerenciamento_do_projetoMgp sisp --plano_de_gerenciamento_do_projeto
Mgp sisp --plano_de_gerenciamento_do_projetoSimba Samuel
 

Más de Simba Samuel (15)

Manual cctv v3.1
Manual cctv v3.1 Manual cctv v3.1
Manual cctv v3.1
 
Manual do curso de cftv
Manual do curso de cftvManual do curso de cftv
Manual do curso de cftv
 
012 computacao forense
012   computacao forense012   computacao forense
012 computacao forense
 
Ubuntu guia do_iniciante-2-0
Ubuntu guia do_iniciante-2-0Ubuntu guia do_iniciante-2-0
Ubuntu guia do_iniciante-2-0
 
Curriculum vitae
Curriculum vitaeCurriculum vitae
Curriculum vitae
 
Angola2
Angola2Angola2
Angola2
 
Motivação
MotivaçãoMotivação
Motivação
 
Html
HtmlHtml
Html
 
Capítulo 3 funcionalidades e protocolos da camada de aplicação
Capítulo 3   funcionalidades e protocolos da camada de aplicaçãoCapítulo 3   funcionalidades e protocolos da camada de aplicação
Capítulo 3 funcionalidades e protocolos da camada de aplicação
 
Linguagem de-programacao-html 2
Linguagem de-programacao-html 2Linguagem de-programacao-html 2
Linguagem de-programacao-html 2
 
Segurança de informação1
Segurança de informação1Segurança de informação1
Segurança de informação1
 
Projecto de Programação de Aluno(Samuel)
Projecto de Programação de Aluno(Samuel)Projecto de Programação de Aluno(Samuel)
Projecto de Programação de Aluno(Samuel)
 
Poster08
Poster08Poster08
Poster08
 
Mgp sisp --plano_de_gerenciamento_do_projeto
Mgp sisp --plano_de_gerenciamento_do_projetoMgp sisp --plano_de_gerenciamento_do_projeto
Mgp sisp --plano_de_gerenciamento_do_projeto
 
Exercicios
ExerciciosExercicios
Exercicios
 

Android in action 2nd edition 2011

  • 1.
  • 2. Android in Action SECOND EDITION W. FRANK ABLESON ROBI SEN CHRIS KING Revised Edition of Unlocking Android M A N N I N G Greenwich (74° w. long.)
  • 3. For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 180 Broad St. Suite 1323 Stamford, CT 06901 Email: orders@manning.com ©2011 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine Manning Publications Co. Development editor: Troy Mott 180 Broad St. Copyeditors: Joan Celmer, Liz Welch Suite 1323 Typesetter: Dottie Marsico Stamford, CT 06901 Cover designer: Marija Tudor ISBN 978-1-935182-72-6 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – MAL – 16 15 14 13 12 11
  • 4. v brief contents PART 1 WHAT IS ANDROID?—THE BIG PICTURE ........................1 1 ■ Introducing Android 3 2 ■ Android’s development environment 31 PART 2 EXERCISING THE ANDROID SDK ..................................61 3 ■ User interfaces 63 4 ■ Intents and Services 101 5 ■ Storing and retrieving data 129 6 ■ Networking and web services 159 7 ■ Telephony 187 8 ■ Notifications and alarms 205 9 ■ Graphics and animation 222 10 ■ Multimedia 246 11 ■ Location, location, location 267 PART 3 ANDROID APPLICATIONS............................................291 12 ■ Putting Android to work in a field service application 293 13 ■ Building Android applications in C 338
  • 5. BRIEF CONTENTSvi PART 4 THE MATURING PLATFORM ........................................365 14 ■ Bluetooth and sensors 367 15 ■ Integration 387 16 ■ Android web development 421 17 ■ AppWidgets 454 18 ■ Localization 491 19 ■ Android Native Development Kit 506
  • 6. vii contents preface xvii preface to the first edition xix acknowledgments xxi about this book xxiv about the cover illustration xxix PART 1 WHAT IS ANDROID?—THE BIG PICTURE ...............1 1 Introducing Android 3 1.1 The Android platform 4 1.2 Understanding the Android market 5 Mobile operators 5 ■ Android vs. the feature phones 6 Android vs. the smartphones 7 ■ Android vs. itself 8 Licensing Android 9 1.3 The layers of Android 10 Building on the Linux kernel 11 ■ Running in the Dalvik VM 12 1.4 The Intent of Android development 12 Empowering intuitive UIs 13 ■ Intents and how they work 13
  • 7. CONTENTSviii 1.5 Four kinds of Android components 17 Activity 17 ■ Service 18 ■ BroadcastReceiver 19 ContentProvider 22 1.6 Understanding the AndroidManifest.xml file 24 1.7 Mapping applications to processes 25 1.8 Creating an Android application 26 1.9 Summary 30 2 Android’s development environment 31 2.1 Introducing the Android SDK 32 Core Android packages 33 ■ Optional packages 34 2.2 Exploring the development environment 34 The Java perspective 35 ■ The DDMS perspective 37 Command-line tools 40 2.3 Building an Android application in Eclipse 43 The Android Project Wizard 43 ■ Android sample application code 44 ■ Packaging the application 50 2.4 Using the Android emulator 51 Setting up the emulated environment 52 Testing your application in the emulator 56 2.5 Debugging your application 57 2.6 Summary 58 PART 2 EXERCISING THE ANDROID SDK .........................61 3 User interfaces 63 3.1 Creating the Activity 65 Creating an Activity class 66 ■ Exploring the Activity lifecycle 71 3.2 Working with views 74 Exploring common views 75 ■ Using a ListView 77 Multitasking with Handler and Message 81 Creating custom views 82 ■ Understanding layout 84 Handling focus 86 ■ Grasping events 87 3.3 Using resources 89 Supported resource types 89 ■ Referencing resources in Java 89 Defining views and layouts through XML resources 92 Externalizing values 94 ■ Providing animations 97
  • 8. CONTENTS ix 3.4 Exploring the AndroidManifest file 98 3.5 Summary 99 4 Intents and Services 101 4.1 Serving up RestaurantFinder with Intent 102 Defining Intents 102 ■ Implicit and explicit invocation 103 Adding external links to RestaurantFinder 104 ■ Finding your way with Intent 106 ■ Taking advantage of Android-provided activities 108 4.2 Checking the weather with a custom URI 109 Offering a custom URI 109 ■ Inspecting a custom Uri 111 4.3 Checking the weather with broadcast receivers 113 Broadcasting Intent 113 ■ Creating a receiver 115 4.4 Building a background weather service 115 4.5 Communicating with the WeatherAlertService from other apps 119 Android Interface Definition Language 119 ■ Binder and Parcelable 121 ■ Exposing a remote interface 122 Binding to a Service 123 ■ Starting versus binding 126 Service lifecycle 127 4.6 Summary 128 5 Storing and retrieving data 129 5.1 Using preferences 130 Working with SharedPreferences 130 ■ Preference access permissions 133 5.2 Using the filesystem 136 Creating files 136 ■ Accessing files 137 ■ Files as raw resources 138 ■ XML file resources 139 ■ External storage via an SD card 141 5.3 Persisting data to a database 144 Building and accessing a database 144 ■ Using the sqlite3 tool 149 5.4 Working with ContentProvider classes 149 Using an existing ContentProvider 150 ■ Creating a ContentProvider 151 5.5 Summary 158
  • 9. CONTENTSx 6 Networking and web services 159 6.1 An overview of networking 161 Networking basics 161 ■ Clients and servers 163 6.2 Checking the network status 164 6.3 Communicating with a server socket 165 6.4 Working with HTTP 168 Simple HTTP and java.net 169 ■ Robust HTTP with HttpClient 170 ■ Creating an HTTP and HTTPS helper 172 6.5 Web services 178 POX—Putting it together with HTTP and XML 179 REST 181 ■ To SOAP or not to SOAP, that is the question 184 6.6 Summary 185 7 Telephony 187 7.1 Exploring telephony background and terms 188 Understanding GSM 189 ■ Understanding CDMA 189 7.2 Accessing telephony information 190 Retrieving telephony properties 191 ■ Obtaining phone state information 193 7.3 Interacting with the phone 195 Using intents to make calls 195 ■ Using phone number-related utilities 196 ■ Intercepting outbound calls 198 7.4 Working with messaging: SMS 199 Sending SMS messages 199 ■ Receiving SMS messages 202 7.5 Summary 203 8 Notifications and alarms 205 8.1 Introducing Toast 206 Creating an SMS example with a Toast 206 ■ Receiving an SMS message 207 8.2 Introducing notifications 210 The Notification class 210 ■ Notifying a user of an SMS 211 8.3 Introducing Alarms 215 Creating a simple alarm example 215 ■ Using notifications with Alarms 218 8.4 Summary 220
  • 10. CONTENTS xi 9 Graphics and animation 222 9.1 Drawing graphics in Android 223 Drawing with XML 224 ■ Exploring XML drawable shapes 225 9.2 Creating animations with Android’s Graphics API 227 Android’s frame-by-frame animation 227 ■ Programmatically creating an animation 230 9.3 Introducing OpenGL for Embedded Systems 233 Creating an OpenGL context 234 ■ Drawing a rectangle with OpenGL ES 238 ■ Three-dimensional shapes and surfaces with OpenGL ES 241 9.4 Summary 245 10 Multimedia 246 10.1 Introduction to multimedia and OpenCORE 247 10.2 Playing audio 248 10.3 Playing video 250 10.4 Capturing media 251 Understanding the camera 252 ■ Capturing audio 257 10.5 Recording video 259 10.6 Summary 265 11 Location, location, location 267 11.1 Simulating your location within the emulator 269 Sending in your coordinates with the DDMS tool 269 The GPS Exchange Format 271 ■ The Google Earth Keyhole Markup Language 272 11.2 Using LocationManager and LocationProvider 275 Accessing location data with LocationManager 275 Using a LocationProvider 277 ■ Receiving location updates with LocationListener 279 11.3 Working with maps 281 Extending MapActivity 282 ■ Using a MapView 282 Placing data on a map with an Overlay 285 11.4 Converting places and addresses with Geocoder 288 11.5 Summary 290
  • 11. CONTENTSxii PART 3 ANDROID APPLICATIONS ...................................291 12 Putting Android to work in a field service application 293 12.1 Designing a real-world Android application 294 Core requirements of the application 295 ■ Managing the data 296 ■ Application architecture and integration 297 12.2 Mapping out the application flow 298 Mapping out the field service application 298 ■ List of source files 300 ■ Field service application’s AndroidManifest.xml 302 12.3 Application source code 302 Splash Activity 302 ■ Preferences used by the FieldService Activity 304 ■ Implementing the FieldService Activity 306 Settings 307 ■ Managing job data 309 12.4 Source code for managing jobs 316 RefreshJobs 317 ■ Managing jobs: The ManageJobs Activity 320 ■ Working with a job with the ShowJob Activity 323 Capturing a signature with the CloseJob Activity 327 12.5 Server code 333 Dispatcher user interface 334 ■ Database 334 ■ PHP dispatcher code 335 ■ PHP mobile integration code 336 12.6 Summary 337 13 Building Android applications in C 338 13.1 Building Android apps without the SDK 339 The C compiler and linker tools 339 ■ Building a Hello World application 340 ■ Installing and running the application 342 C application build script 344 13.2 Solving the problem with dynamic linking 344 Android system libraries 345 ■ Building a dynamically linked application 346 ■ exit() versus return() 349 ■ Startup code 350 13.3 What time is it? The DayTime Server 352 DayTime Server application 352 ■ daytime.c 353 The SQLite database 355 ■ Building and running the DayTime Server 358 13.4 Daytime Client 360 Activity 360 ■ Socket Client 361 ■ Testing the Daytime Client 362 13.5 Summary 362
  • 12. CONTENTS xiii PART 4 THE MATURING PLATFORM ...............................365 14 Bluetooth and sensors 367 14.1 Exploring Android’s Bluetooth capabilities 368 Replacing cables 369 ■ Primary and secondary roles and sockets 369 ■ Trusting a device 370 ■ Connecting to a remote device 372 ■ Capturing Bluetooth events 374 ■ Bluetooth permissions 375 14.2 Interacting with the SensorManager 375 Types of sensors 376 ■ Reading sensor values 377 Enabling and disabling sensors 378 14.3 Building the SenseBot application 379 User interface 380 ■ Interpreting sensor values 382 Driving the robot 383 ■ Communication with the robot 384 14.4 Summary 385 15 Integration 387 15.1 Understanding the Android contact model 388 Choosing open-ended records 388 ■ Dealing with multiple accounts 390 ■ Unifying a local view from diverse remote stores 392 ■ Sharing the playground 393 15.2 Getting started with LinkedIn 393 15.3 Managing contacts 395 Leveraging the built-in contacts app 395 ■ Requesting operations from your app 398 ■ Directly reading and modifying the contacts database 399 ■ Adding contacts 400 15.4 Keeping it together 403 The dream of sync 403 ■ Defining accounts 404 Telling secrets: The AccountManager service 405 15.5 Creating a LinkedIn account 406 Not friendly to mobile 406 ■ Authenticating to LinkedIn 407 15.6 Synchronizing to the backend with SyncAdapter 414 The synchronizing lifecycle 414 ■ Synchronizing LinkedIn data 414 15.7 Wrapping up: LinkedIn in action 417 Finalizing the LinkedIn project 417 ■ Troubleshooting tips 418 Moving on 419 15.8 Summary 419
  • 13. CONTENTSxiv 16 Android web development 421 16.1 What’s Android web development? 422 Introducing WebKit 422 ■ Examining the architectural options 423 16.2 Optimizing web applications for Android 424 Designing with mobile in mind 424 ■ Adding the viewport tag 426 ■ Selectively loading content 428 ■ Interrogating the user agent 428 ■ The media query 429 ■ Considering a made- for-mobile application 430 16.3 Storing data directly in the browser 431 Setting things up 432 ■ Examining the code 433 ■ The user interface 433 ■ Opening the database 435 ■ Unpacking the transaction function 436 ■ Inserting and deleting rows 438 Testing the application with WebKit tools 439 16.4 Building a hybrid application 440 Examining the browser control 440 ■ Wiring up the control 441 Implementing the JavaScript handler 443 ■ Accessing the code from JavaScript 445 ■ Digging into the JavaScript 445 Security matters 447 ■ Implementing a WebViewClient 448 Augmenting the browser 448 ■ Detecting navigation events 449 Implementing the WebChromeClient 452 16.5 Summary 453 17 AppWidgets 454 17.1 Introducing the AppWidget 455 What’s an AppWidget? 455 ■ AppWidget deployment strategies 457 17.2 Introducing SiteMonitor 458 Benefits of SiteMonitor 458 ■ The user experience 459 17.3 SiteMonitor application architecture 462 Bird’s-eye view of the application 462 ■ File by file 464 17.4 AppWidget data handling 465 17.5 Implementing the AppWidgetProvider 469 AppWidgetProvider method inventory 469 ■ Implementing SiteMonitorWidgetImpl 470 ■ Handling zombie widgets 472 17.6 Displaying an AppWidget with RemoteViews 473 Working with RemoteViews 473 ■ UpdateOneWidget explained 474
  • 14. CONTENTS xv 17.7 Configuring an instance of the AppWidget 476 AppWidget metadata 477 ■ Working with Intent data 478 Confirming widget creation 479 17.8 Updating the AppWidget 480 Comparing services to alarms 481 ■ Triggering the update 482 Updating the widgets, finally! 484 17.9 Tying it all together with AndroidManifest.xml 488 17.10 Summary 489 18 Localization 491 18.1 The need for localization 492 18.2 Exploring locales 493 18.3 Strategies for localizing an application 494 Identifying target locales and data 494 ■ Identifying and managing strings 495 ■ Drawables and layouts 497 Dates, times, numbers, and currencies 498 ■ Working with the translation team 499 18.4 Leveraging Android resource capabilities 500 More than locale 500 ■ Assigning strings in resources 500 18.5 Localizing in Java code 502 18.6 Formatting localized strings 503 18.7 Obstacles to localization 504 18.8 Summary 505 19 Android Native Development Kit 506 19.1 Introducing the NDK 507 Uses for the NDK 507 ■ Looking at the NDK 508 19.2 Building an application with the NDK 509 Demonstrating the completed application 510 Examining the project structure 511 19.3 Building the JNI library 512 Understanding JNI 512 ■ Implementing the library 513 Compiling the JNI library 518 19.4 Building the user interface 519 User interface layout 519 ■ Taking a photo 521 Finding the edges 523
  • 15. CONTENTSxvi 19.5 Integrating the NDK into Eclipse 524 19.6 Summary 526 appendix A Installing the Android SDK 527 appendix B Publishing applications 538 index 551
  • 16. xvii preface When we set out to write the first version of this book, many friends and family won- dered just what this Android thing was all about. Now, two years after the publication of the first edition, Android is nearly a household term. The first edition of the book, Unlocking Android, enjoyed enough success that we were privileged to have the opportunity to write this second edition, renamed as Android in Action. The first thirteen chapters of the book have been refreshed and/or rewritten to bring the content up to date with Android 2.2+. Six chapters were added, bringing in more topics of interest that stray from the simplistic but are still within the realm of instructional and informational. The new content extends beyond the basics of Android development, including some topics that I’ve envisioned for a long time but lacked the proper platform to bring them to fruition. We could have written many more chapters, but we had to draw the line somewhere! The second edition of this book was written by Frank Ableson, Robi Sen, and Chris King. Chris updated chapters 4, 5, 7, and 11. Some excellent content originally writ- ten by Charlie Collins remains in this second edition. Early on in the project Chris and I were discussing the need to bring social networking into the book. Chris exam- ined the available social networks and came back with a clever mechanism to integrate the Android contacts database with the popular business networking service LinkedIn. His work is shown in chapter 15, “Integration.” The application from chap- ter 15 is available as a free download in the Android Market. Robi updated his chapters on notifications, graphics, and media, while I focused on some new content areas of interest, including Bluetooth communications, sen- sors, localization, AppWidgets, native development in C, and web development for Android.
  • 17. PREFACExviii In addition to the LinkedIn application from chapter 15, two more applications from this book are available in the Market as free downloads. The first is SenseBot— an application that allows you to drive a LEGO Mindstorms-powered robot by tilting your phone. The application demonstrates both the sensor subsystem of Android, as well as communicating with Bluetooth. The other application available in the Market is called FindEdges. FindEdges demonstrates the Android Native Development Kit as it exercises an image processing algorithm written in the C language. All in all, writing a book for Android is both exciting and challenging. Android continues to mature and promises to be a major player for years to come. Many thanks are owed to readers of the first edition, for without you, there wouldn’t be a second edition! FRANK ABLESON
  • 18. xix preface to the first edition The first mobile applications I had the opportunity to work with were inventory con- trol programs used in retail and manufacturing settings. The “terminals,” as we called them at the time, were heavy and expensive. They had big antennas, lots of clunky keys, grayscale LCD displays, and they looked like they came straight from the set of a science fiction movie. From that austere beginning, my mobile horizons expanded when the Palm Pilot became the craze in the mid to late 1990s. My first significant PalmOS project was to develop an IrDA communications library for an application that printed calendars, contacts, and task-lists. Back then, the hip printers had an IrDA port and it was cool to beam your business card to someone. Ironically, I always enjoyed designing and writ- ing the software more than using the devices themselves. Fast forward ten years, and I have had the privilege of working on some very chal- lenging and engaging mobile software projects for numerous clients along the way. Much of my career to date can be traced back to relationships stemming from my early mobile development experiences—and what a blessing it has been for me. I just love the question, “would it be possible to…?” And more often than not, the answer has been “Yes!” What I particularly enjoy is helping change the way a business operates or the way problems are solved through the application of mobile software. Mobile technology can and will continue to change the way we live, work, and play…and this brings me to Android and this book. In the fall of 2007, I was speaking with my friend Troy Mott, who happens to be an editor for Manning, the publisher of this book. Troy and I were discussing the mobile marketplace, something we’ve been doing for years. We started kicking around the
  • 19. PREFACE TO THE FIRST EDITIONxx idea of writing a book on Android. The challenge was that Android didn’t really exist. Yet. We knew from some of the preliminary information that the platform promised to be open, capable, and popular. We felt that those ingredients could make for an inter- esting and valuable topic, so we began thinking about what that book might look like, taking it on faith that the platform would actually come to fruition. Before long, we convinced ourselves (and Manning) that this was a good idea and the work began in early 2008. Beyond the usual challenges of putting a book together, we had the additional obstacle that our subject matter has been in a steady, though unpredictable, state of change over the past year. In essence, we’ve written this book twice because the SDK has been changed multiple times and Android-equipped phones have become available, accelerating the interest and demand for the plat- form. Every time a significant change occurred, we went back and revisited portions of the book, sometimes rewriting entire chapters to accommodate the latest develop- ments in the Android platform. I say “we” because in the process of writing this book, Troy and I decided to share the fun and brought in two experienced authors to contribute their expertise and enthusiasm for this platform. It has been a pleasure getting to know and working with both Charlie Collins and Robi Sen. While I focused on the first and third parts of the book in the first edition, Charlie and Robi wrote part 2, which covers the important fundamentals of writing Android applications. Thanks to their contributions, I enjoyed the freedom to express my vision of what Android means to the mobile space in the first part of the book, and then to work on a couple of more advanced applica- tions at the end of the book. We hope that you enjoy reading this book and that it proves to be a valuable resource for years to come as together we contribute to the future of the Android platform. FRANK ABLESON
  • 20. xxi acknowledgments Perhaps the only thing more challenging than writing a technical book is writing the second edition. There is a lot of excitement when writing the proposed table of con- tents for the updated edition but at some point the work must commence. The size and scope of this project meant working together as a team from the start. I had the privi- lege of working again with Robi Sen from the first edition and also with experienced developer and writer Chris King. Along with the help of the talented team at Manning, we are pleased to present Android in Action, the update to Unlocking Android. In particular, we’d like to acknowledge and thank those at Manning who helped bring this book about. First, thanks to Troy Mott, our acquisition and development editor, who has been involved in every aspect of both the first and second editions. Troy was there from the beginning, from the “what if” stages, through helping push us over the goal line—twice! Karen Tegtmeyer did all the big and little things to bring the project together; Mary Piergies skillfully piloted the team through the harrowing production process; and Marjan Bace, our publisher, showed an attention to detail at once challenging, beneficial, and appreciated. Once the writing was done, the next round of work began and special thanks need to go to: Benjamin Berg who performed the pre-production editing pass, Joan Celmer and Liz Welch, our copyeditors, who made our content readable in cases where it went either “too geek” or where the geek in us tried to be “too literary;” Elizabeth Martin, our proofreader, who added common sense to the project, as well as a terrific sense of humor and encouraging attitude; Janet Vail who jumped in at the last minute to help us bring the final pieces of the project together; and finally Dottie Marsico who handles the actual layout of the pages. It is sometimes hard to envision the final
  • 21. ACKNOWLEDGMENTSxxii product when looking at edits upon edits in MS Word, but Dottie’s magic makes the product you hold in your hands. Thanks to each of you for your special contribution to this project. Next, we would like to thank Candace Gillhooley for her efforts in get- ting the word out about the book. And special thanks to the other reviewers who read our revised manuscript at dif- ferent times during its development: Michael Martin, Orhan Alkan, Eric Raymond, Jason Jung, Frank Wang, Robert O’Connor, Paul Grebenc, Sean Owen, Loïc Simon, Greg Donald, Nikolaos Kaintantzis, Matthew Johnson, and Patrick Steger; and to Michael Galpin and Jérôme Bâton for their careful tech review of the final manuscript during production. Lastly, we want to thank the thoughtful and encouraging MEAP subscribers who provided feedback along the way; the book is better thanks to your contributions. Frank Ableson I would like to thank Robi Sen, Chris King, and Troy Mott for their contributions, col- laboration, and endurance on this project! And of course, my wife Nikki and my chil- dren deserve special recognition for the seemingly endless hours of wondering when I would emerge from the “lab” and what mood I would be in—either elation when the robot worked, or near depression when the AppWidgets wouldn’t go away. Thank you for getting neither too excited nor too concerned! My staff at navitend also deserve a big thank you for carrying the water while I finished my work on this project. Finally, a big thank you to Miriam Raffay from Madridiam.com, who provided the much- needed Spanish translations for chapter 18. Gracias! Chris King I am deeply grateful to Troy Mott and Frank Ableson for bringing me into this project and providing support and inspiration throughout. Troy has been welcoming and enthusiastic, showing great flexibility as we discussed what projects to undertake. Frank has a keen eye for quality, and provided great guidance from start to finish on how to craft the best book possible. I also appreciate all the work done by the review- ers and editors from Manning, whose contributions have improved the text’s accuracy and style. Working on this book has been a joy, and I’ve greatly enjoyed the opportuni- ties to contribute more and more to its progress. Thanks also to the crew at Gravity Mobile, especially Noah Hurwitz, Chris Lyon, Young Yoon, and Sam Trychin. You guys keep my life fun and challenging, and have made mobile development an even better place to work. Finally, my love to my fam- ily: Charles, Karen, Patrick, Kathryn, and Andrew. You’ve made everything possible for me.
  • 22. ACKNOWLEDGMENTS xxiii Robi Sen I would like to thank Troy Mott and the team—and everyone at Manning Publica- tions— for their hard work making this book something worth reading. I would like to thank my coauthors, Frank and Chris, who were great to work with and very under- standing when I was the one holding things up. I would also like to thank Jesse Dailey for his help with OpenGL as well as David Cartier with the Contacts API. Finally, I would like to thank my family who, more often than I liked, had to do without me while I worked on my chapters, worked multiple jobs, and finished grad school.
  • 23. xxiv about this book Android in Action, Second Edition is a revision and update of Unlocking Android, pub- lished in April 2009. This book doesn’t fit nicely into the camp of “introductory text,” nor is it a highly detailed reference manual. The text has something to offer both the beginner and the experienced developer who is looking to sell his or her application in the Android Market. This book covers important beginner topics such as “What is Android” and installing and using the development environment. We then advance to practical working examples of core programming topics any developer will be happy to have at the ready on the reference shelf. The remaining chapters present very detailed example applications covering advanced topics, including a complete field service application, localization, and material on Android web applications, Blue- tooth, sensors, AppWidgets, and integration adapters. We even include two chapters on writing applications in C—one for the native side of Android and one using the more generally accepted method of employing the Android Native Development Kit. Although you can read the book from start to finish, you can also consider it a cou- ple of books in one. If you’re new to Android, focus first on chapter 1, appendix A, and then chapter 2. With that foundation, you can then work your way through chap- ters 3 through 12. Chapter 13 and on are more in-depth in nature and can be read independently of the others. The audience We wrote this book for professional programmers and hobbyists alike. Many of the concepts can be absorbed without specific Java language knowledge, though the most value will be found by readers with Java programming skills because Android
  • 24. ABOUT THIS BOOK xxv application programming requires them. A reader with C, C++, or C# programming knowledge will be able to follow the examples. Prior Eclipse experience is helpful, but not required. A number of good resources are available on Java and Eclipse to augment the content of this book. Roadmap This book is divided into four parts. Part 1 contains introductory material about the platform and development environment. Part 2 takes a close look at the fundamental skills required for building Android applications. Part 3 presents a larger scope appli- cation and a Native C Android application. Part 4 explores features added to the Android platform, providing examples of leveraging the capable Android platform to create innovative mobile applicatoins. PART 1: THE ESSENTIALS Part 1 introduces the Android platform, including its architecture and setting up the development environment. Chapter 1 delves into the background and positioning of the Android platform, including comparisons to other popular platforms such as BlackBerry, iPhone, and Windows Mobile. After an introduction to the platform, the balance of the first chap- ter introduces the high-level architecture of Android applications and the operating system environment. Chapter 2 takes you on a step-by-step development exercise, teaching you the ropes of using the Android development environment, including the key tools and concepts for building an application. If you’ve never used Eclipse or have never writ- ten an Android application, this chapter will prepare you for the next part of the book. PART 2: THE PROGRAMMING ENVIRONMENT Part 2 includes an extensive survey of fundamental programming topics in the Android environment. Chapter 3 covers the fundamental Android UI components, including View and Layout. We also review the Activity in more detail. These are the basic building blocks of screens and applications on the Android platform. Along the way, we also touch on other basic concepts such as handling external resources, dealing with events, and the lifecycle of an Android application. Chapter 4 expands on the concepts you learned in chapter 3. We delve into the Android Intent to demonstrate interaction between screens, activities, and entire applications. We also introduce and use the Service, which brings background pro- cesses into the fold. Chapter 5 incorporates methods and strategies for storing and retrieving data locally. The chapter examines use of the filesystem, databases, the SD card, and Android-specific entities such as the SharedPreferences and ContentProvider classes. At this point, we begin combining fundamental concepts with more real-world
  • 25. ABOUT THIS BOOKxxvi details, such as handling application state, using a database for persistent storage, and working with SQLite. Chapter 6 deals with storing and retrieving data over the network. Here we include a networking primer before delving into using raw networking concepts such as sock- ets on Android. From there, we progress to using HTTP, and even exploring web ser- vices (such as REST and SOAP). Chapter 7 covers telephony on the Android platform. We touch on basics such as originating and receiving phone calls, as well as more involved topics such as working with SMS. We also cover telephony properties and helper classes. Chapter 8 looks at how to work with notifications and alarms. In this chapter, we look at how to notify users of various events such as receiving a SMS message, as well as how to manage and set alarms. Chapter 9 deals with the basics of Android’s Graphics API and more advanced con- cepts such as working with the OpenGL ES library for creating sophisticated 2D and 3D graphics. We also touch on animation. Chapter 10 looks at Android’s support for multimedia; we cover both playing mul- timedia as well as using the camera and microphone to record your own multimedia files. Chapter 11 introduces location-based services as we look at an example that com- bines many of the concepts from the earlier parts of the book in a mapping applica- tion. You’ll learn about using the mapping APIs on Android, including different location providers and properties that are available, how to build and manipulate map-related screens, and how to work with location-related concepts within the emu- lator. PART 3: BRINGING IT ALL TOGETHER Part 3 contains two chapters, both of which build on knowledge you gained earlier in the text, with a focus on bringing a larger application to fruition. Chapter 12 demonstrates an end-to-end field service application. The application includes server communications, persistent storage, multiple Activity navigation menus, and signature capture. Chapter 13 explores the world of native C language applications. The Android SDK is limited to the Java language, although native applications can be written for Android. This chapter walks you through examples of building C language applica- tions for Android, including the use of built-in libraries and TCP socket communica- tions as a Java application connects to your C application. This chapter is useful for developers targeting solutions beyond carrier-subsidized, locked down cell phones. PART 4: THE MATURING PLATFORM Part 4 contains six new chapters, each of which represents a more advanced develop- ment topic. Chapter 14 demonstrates the use of both Bluetooth communication and process- ing sensor data. The sample application accompanying the chapter, SenseBot, permits the user to drive a LEGO Mindstorms robot with their Android phone.
  • 26. ABOUT THIS BOOK xxvii Chapter 15 explores the Android contact database and demonstrates integrating with an external data source. In particular, this application brings Android into the social networking scene by integrating with the popular LinkedIn professional net- working service. Chapter 16 explores the world of web development. Android’s browser is based on the open source WebKit engine and brings desktop-like capability to this mobile browser. This chapter equips you to bring attractive and capable web applications to Android. Chapter 17 brings the “home screen” of your Android application to life by show- ing you how to build an application that presents its user interface as an AppWidget. In addition to AppWidgets, this chapter demonstrates BroadcastReceiver, Service, and Alarms. Chapter 18 takes a real-world look at localizing an existing application. Chapter 12’s Field Service application is modified to support multiple languages. Chapter 18’s version of the Field Service application contains support for both English and Spanish. Chapter 19 reaches into Android’s open source foundation by using a popular edge detection image processing algorithm. The Sobel Edge Detection algorithm is written in C and compiled into a native library. The sample application snaps a pic- ture with the Android camera and then uses this C algorithm to find the edges in the photo. THE APPENDICES The appendices contain additional information that didn’t fit with the flow of the main text. Appendix A is a step-by-step guide to installing the development environ- ment. This appendix, along with chapter 2, provides all the information you need to build an Android application. Appendix B demonstrates how to prepare and submit an application for the Android Market—an important topic for anyone looking to sell an application commercially. Code conventions and downloads All source code in the book is in a fixed-width font like this, which sets it off from the surrounding text. For most listings, the code is annotated to point out the key con- cepts, and numbered bullets are sometimes used in the text to provide additional information about the code. We have tried to format the code so that it fits within the available page space in the book by adding line breaks and using indentation carefully. Sometimes, however, very long lines will include line-continuation markers. Source code for all the working examples is available from www.manning.com/ AndroidinActionSecondEdition or http://www.manning.com/ableson2. A readme.txt file is provided in the root folder and also in each chapter folder; the files provide details on how to install and run the code. Code examples appear throughout this book. Longer listings will appear under clear listing headers while shorter listings will appear between lines of text.
  • 27. ABOUT THIS BOOKxxviii Software requirements Developing applications for Android may be done from the Windows XP/Vista/7 environment, a Mac OS X (Intel only) environment or a Linux environment. Appen- dix A includes a detailed description of setting up the Eclipse environment along with the Android Developer Tools plug-in for Eclipse. A note about the graphics Many of the original graphics from the first edition, Unlocking Android, have been reused in this version of the book. While the title of the revised edition was changed to Android in Action, Second Edition during development, we kept the original book title in our graphics and sample applications. Author Online Purchase of Android in Action, Second Edition includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical questions, and receive help from the authors and from other users. To access the forum and subscribe to it, point your web browser to www.manning.com/ AndroidinActionSecondEdition or www.manning.com/ableson2. This page provides information on how to get on the forum once you’re registered, what kind of help is available, and the rules of conduct on the forum. Manning’s commitment to our readers is to provide a venue where a meaningful dialog between individual readers and between readers and the authors can take place. It’s not a commitment to any specific amount of participation on the part of the authors, whose contribution to the AO remains voluntary (and unpaid). We suggest you try asking the authors some challenging questions lest their interest stray! The Author Online forum and the archives of previous discussions will be accessi- ble from the publisher’s website as long as the book is in print.
  • 28. xxix about the cover illustration The illustration on the cover of Android in Action, Second Edition is taken from a French book of dress customs, Encyclopédie des Voyages by J. G. St. Saveur, published in 1796. Travel for pleasure was a relatively new phenomenon at the time and illustrated guides such as this one were popular, introducing both the tourist as well as the arm- chair traveler to the inhabitants of other regions of the world, as well as to the regional costumes and uniforms of France. The diversity of the drawings in the Encyclopédie des Voyages speaks vividly of the uniqueness and individuality of the world’s countries and regions just 200 years ago. This was a time when the dress codes of two regions separated by a few dozen miles identified people uniquely as belonging to one or the other, and when members of a social class or a trade or a tribe could be easily distinguished by what they were wearing. This was also a time when people were fascinated by foreign lands and faraway places, even though they could not travel to these exotic destinations themselves. Dress codes have changed since then and the diversity by region and tribe, so rich at the time, has faded away. It is now often hard to tell the inhabitant of one continent from another. Perhaps, trying to view it optimistically, we have traded a world of cul- tural and visual diversity for a more varied personal life. Or a more varied and interest- ing intellectual and technical life. We at Manning celebrate the inventiveness, the initiative, and the fun of the com- puter business with book covers based on native and tribal costumes from two centu- ries ago brought back to life by the pictures from this travel guide.
  • 29. Part 1 What is Android?— The Big Picture Android promises to be a market-moving technology platform—not just because of the functionality available in the platform but because of how the platform has come to market. Part 1 of this book brings you into the picture as a developer of the open source Android platform. We begin with a look at the Android platform and the impact it has on each of the major “stakeholders” in the mobile marketplace (chapter 1). We then bring you on board to developing applications for Android with a hands-on tour of the Android development envi- ronment (chapter 2).
  • 30. 3 Introducing Android You’ve heard about Android. You’ve read about Android. Now it’s time to begin unlocking Android. Android is a software platform that’s revolutionizing the global cell phone mar- ket. It’s the first open source mobile application platform that’s moved the needle in major mobile markets around the globe. When you’re examining Android, there are a number of technical and market-related dimensions to consider. This first section introduces the platform and provides context to help you better under- stand Android and where it fits in the global cell phone scene. Android is primarily a Google effort, in collaboration with the Open Handset Alliance. Open Handset Alliance is an alliance of nearly 50 organizations commit- ted to bringing a “better” and more “open” mobile phone to market. Considered a novelty at first by some, Android has grown to become a market-changing player in a few short years, earning both respect and derision alike from peers in the industry. This chapter introduces Android—what it is, and, equally important, what it’s not. After reading this chapter, you’ll understand how Android is constructed, how This chapter covers  Exploring Android, the open source mobile platform  Android Intents, the way things work  Sample application
  • 31.
  • 32. 5Understanding the Android market PLATFORM VS. DEVICE Throughout this book, wherever code must be tested or exercised on a device, a software-based emulator is typically employed. An exception is in chapter 14 where Bluetooth and Sensors are exercised. See chapter 2 for information on how to set up and use the Android emulator. The term platform refers to Android itself—the software—including all the binaries, code libraries, and tool chains. This book focuses on the Android platform; the Android emulators available in the SDK are simply components of the Android platform. With all of that as a backdrop, creating a successful mobile platform is clearly a non- trivial task involving numerous players. Android is an ambitious undertaking, even for Google, a company of seemingly boundless resources and moxie—and they’re getting the job done. Within a span of two years, Android has seen four major software releases and the release of multiple handsets across most major mobile carriers in the global market. Now that you’ve got an introduction to what Android is, let’s look at the why and where of Android to provide some context and set the perspective for Android’s intro- duction to the marketplace. After that, it’s on to exploring the platform itself! 1.2 Understanding the Android market Android promises to have something for everyone. It aims to support a variety of hard- ware devices, not just high-end ones typically associated with expensive smartphones. Of course, Android users will enjoy improved performance on a more powerful device, considering that it sports a comprehensive set of computing features. But how well can Android scale up and down to a variety of markets and gain market and mind share? How quickly can the smartphone market become the standard? Some folks are still clinging to phone-only devices, even though smartphones are growing rapidly in virtually every demographic. Let’s look at Android from the perspective of a few exist- ing players in the marketplace. When you’re talking about the cellular market, the place to start is at the top, with the carriers, or as they’re sometimes referred to, the mobile operators. 1.2.1 Mobile operators Mobile operators (the cell phone companies such as AT&T and Verizon) are in the business, first and foremost, of selling subscriptions to their services. Shareholders want a return on their investment, and it’s hard to imagine an industry where there’s a larger investment than in a network that spans such broad geographic territory. To the mobile operator, cell phones are simultaneously a conduit for services, a drug to entice subscribers, and an annoyance to support and lock down. Some mobile operators are embracing Android as a platform to drive new data ser- vices across the excess capacity operators have built into their networks. Data services represent high-premium services and high-margin revenues for the operator. If Android can help drive those revenues for the mobile operator, all the better.
  • 33. 6 CHAPTER 1 Introducing Android Other mobile operators feel threatened by Google and the potential of “free wire- less,” driven by advertising revenues and an upheaval of the market. Another challenge for mobile operators is that they want the final say on what services are enabled across their networks. Historically, handset manufacturers complain that their devices are handicapped and don’t exercise all the features designed into them because mobile operators lack the capability or willingness to support those features. An encouraging sign is that there are mobile operators involved in the Open Handset Alliance. Let’s move on to a comparison of Android and existing cell phones on the market today. 1.2.2 Android vs. the feature phones The majority of cell phones on the market continue to be consumer flip phones and feature phones—phones that aren’t smartphones.1 These phones are the ones consum- ers get when they walk into the retailer and ask what can be had for free. These con- sumers are the “I just want a phone” customers. Their primary interest is a phone for voice communications, an address book, and increasingly, texting. They might even want a camera. Many of these phones have additional capabilities such as mobile web browsing, but because of relatively poor user experience, these features aren’t employed heav- ily. The one exception is text messaging, which is a dominant application no matter the classifica- tion of device. Another increasingly in-demand category is location-based services, which typi- cally use the Global Positioning System (GPS). Android’s challenge is to scale down to this market. Some of the bells and whistles in Android can be left out to fit into lower-end hardware. One of the big functionality gaps on these lower-end phones is the web experience the user gets. Part of the problem is screen size, but equally challenging is the browser technol- ogy itself, which often struggles to match the rich web experience of desktop computers. Android features the market-leading WebKit browser engine, which brings desktop-compatible brows- ing to the mobile arena. Figure 1.2 shows WebKit in action on Android. If a rich web experience can be effectively scaled down to feature phone class hardware, it would go a long way toward 1 Only 12% of phones sold in the fourth quarter of 2008 were smartphones: http://www.gartner.com/it/ page.jsp?id=910112. Figure 1.2 Android’s built-in browser technology is based on WebKit’s browser engine.
  • 34. 7Understanding the Android market penetrating this end of the market. Chapter 16 takes a close look at using web devel- opment skills for creating Android applications. WEBKIT The WebKit (http://www.webkit.org) browser engine is an open source project that powers the browser found in Macs (Safari) and is the engine behind Mobile Safari, which is the browser on the iPhone. It’s not a stretch to say that the browser experience is what makes the iPhone popular, so its inclusion in Android is a strong plus for Android’s architecture. Software at the lower end of the market generally falls into one of two camps:  Qualcomm’s BREW environment—BREW stands for Binary Runtime Environment for Wireless. For a high-volume example of BREW technology, consider Veri- zon’s Get It Now-capable devices, which run on this platform. The challenge for software developers who want to gain access to this market is that the bar to get an application on this platform is high, because everything is managed by the mobile operator, with expensive testing and revenue-sharing fee structures. The upside to this platform is that the mobile operator collects the money and dis- burses it to the developer after the sale, and often these sales recur monthly. Just about everything else is a challenge to the software developer. Android’s open application environment is more accessible than BREW.  Java ME, or Java Platform, Micro Edition—A popular platform for this class of device. The barrier to entry is much lower for software developers. Java ME developers will find a same-but-different environment in Android. Android isn’t strictly a Java ME-compatible platform, but the Java programming environment found in Android is a plus for Java ME developers. There are some projects underway to create a bridge environment, with the aim of enabling Java ME applications to be compiled and run for Android. Gaming, a better browser, and anything to do with texting or social applications present fertile territory for Android at this end of the market. Although the majority of cell phones sold worldwide are not considered smartphones, the popularity of Android (and other capable platforms) has increased demand for higher-function devices. That’s what we’re going to discuss next. 1.2.3 Android vs. the smartphones Let’s start by naming the major smartphone players: Symbian (big outside North America), BlackBerry from Research in Motion, iPhone from Apple, Windows (Mobile, SmartPhone, and now Phone 7), and of course, the increasingly popular Android platform. One of the major concerns of the smartphone market is whether a platform can synchronize data and access Enterprise Information Systems for corporate users. Device-management tools are also an important factor in the enterprise market. The browser experience is better than with the lower-end phones, mainly because of larger
  • 35. 8 CHAPTER 1 Introducing Android displays and more intuitive input methods, such as a touch screen, touch pad, slide- out keyboard, or a jog dial. Android’s opportunity in this market is to provide a device and software that peo- ple want. For all the applications available for the iPhone, working with Apple can be a challenge; if the core device doesn’t suit your needs, there’s little room to maneuver because of the limited models available and historical carrier exclusivity. Now that email, calendaring, and contacts can sync with Microsoft Exchange, the corporate environment is more accessible, but Android will continue to fight the battle of scal- ing the Enterprise walls. Later Android releases have added improved support for the Microsoft Exchange platform, though third-party solutions still out-perform the built- in offerings. BlackBerry is dominant because of its intuitive email capabilities, and the Microsoft platforms are compelling because of tight integration to the desktop experi- ence and overall familiarity for Windows users. iPhone has surprisingly good integra- tion with Microsoft Exchange—for Android to compete in this arena, it must maintain parity with iPhone on Enterprise support. You’ve seen how Android stacks up next to feature phones and smartphones. Next, we’ll see whether Android, the open source mobile platform, can succeed as an open source project. 1.2.4 Android vs. itself Android will likely always be an open source project, but to succeed in the mobile mar- ket, it must sell millions of units and stay fresh. Even though Google briefly entered the device fray with its Nexus One phone, it’s not a hardware company. From necessity, Android is sold by others such as HTC and Motorola, to name the big players. These manufacturers start with the Android Open Source Platform (AOSP), but extend it to meet their need to differentiate their offerings. Android isn’t the first open source phone, but it’s the first from a player with the market-moving weight of Google leading the charge. This market leadership position has already translated to impressive unit sales across multiple manufacturers. So, now that there are a respectable number of devices on the market, can Android keep it together and avoid fragmentation? Open source is a double-edged sword. On one hand, the power of many talented people and companies working around the globe and around the clock to deliver desirable features is a force to be reckoned with, particularly in comparison with a tra- ditional, commercial approach to software development. This topic has become trite because the benefits of open source development are well documented. On the other hand, how far will the competing manufacturers extend and potentially split Android? Depending on your perspective, the variety of Android offerings is a welcome alterna- tive to a more monolithic iPhone device platform where consumers have few choices available. Another challenge for Android is that the licensing model of open source code used in commercial offerings can be sticky. Some software licenses are more restrictive than others, and some of those restrictions pose a challenge to the open source label. At the same time, Android licensees need to protect their investment, so licensing is an important topic for the commercialization of Android.
  • 36. 9Understanding the Android market 1.2.5 Licensing Android Android is released under two different open source licenses. The Linux kernel is released under the GNU General Public License (GPL) as is required for anyone licensing the open source OS kernel. The Android platform, excluding the kernel, is licensed under the Apache Software License (ASL). Although both licensing models are open source-oriented, the major difference is that the Apache license is considered friend- lier toward commercial use. Some open source purists might find fault with anything but complete openness, source-code sharing, and noncommercialization; the ASL attempts to balance the goals of open source with commercial market forces. So far there has been only one notable licensing hiccup impacting the Android mod com- munity, and that had more to do with the gray area of full system images than with a manufacturer’s use of Android on a mainstream product release. Currently, Android is facing intellectual property challenges; both Microsoft and Apple are bringing liti- gation against Motorola and HTC for the manufacturer’s Android-based handsets. The high-level, market-oriented portion of the book has now concluded! The remainder of this book is focused on Android application development. Any technical discussion of a software environment must include a review of the layers that compose the environment, sometimes referred to as a stack because of the layer-upon-layer con- struction. Next up is a high-level breakdown of the components of the Android stack. Selling applications A mobile platform is ultimately valuable only if there are applications to use and enjoy on that platform. To that end, the topic of buying and selling applications for Android is important and gives us an opportunity to highlight a key difference between Android and the iPhone. The Apple AppStore contains software titles for the iPhone—lots of them. But Apple’s somewhat draconian grip on the iPhone software market requires that all applications be sold through its venue. Although Apple’s digital rights man- agement (DRM) is the envy of the market, this approach can pose a challenging envi- ronment for software developers who might prefer to make their application available through multiple distribution channels. Contrast Apple’s approach to application distribution with the freedom an Android developer enjoys to ship applications via traditional venues such as freeware and shareware, and commercially through various marketplaces, including his own web- site! For software publishers who want the focus of an on-device shopping experi- ence, Google has launched and continues to mature the Android Market. For software developers who already have titles for other platforms such as Windows Mobile, Palm, or BlackBerry, traditional software markets such as Handango (http:// www.Handango.com) also support selling Android applications. Handango and its ilk are important outlets; consumers new to Android will likely visit sites such as Han- dango because that might be where they first purchased one of their favorite applica- tions for their prior device.
  • 37.
  • 38. 11The layers of Android TIP Without question, Android development requires Java programming skills. To get the most out of this book, be sure to brush up on your Java pro- gramming knowledge. There are many Java references on the internet, and no shortage of Java books on the market. An excellent source of Java titles can be found at http://www.manning.com/catalog/java. Now that we’ve shown you the obligatory stack diagram and introduced all the layers, let’s look more in depth at the runtime technology that underpins Android. 1.3.1 Building on the Linux kernel Android is built on a Linux kernel and on an advanced, optimized VM for its Java applications. Both technologies are crucial to Android. The Linux kernel component of the Android stack promises agility and portability to take advantage of numerous hardware options for future Android-equipped phones. Android’s Java environment is key: It makes Android accessible to programmers because of both the number of Java software developers and the rich environment that Java programming has to offer. Why use Linux for a phone? Using a full-featured platform such as the Linux ker- nel provides tremendous power and capabilities for Android. Using an open source foundation unleashes the capabilities of talented individuals and companies to move the platform forward. Such an arrangement is particularly important in the world of mobile devices, where products change so rapidly. The rate of change in the mobile market makes the general computer market look slow and plodding. And, of course, the Linux kernel is a proven core platform. Reliability is more important than perfor- mance when it comes to a mobile phone, because voice communication is the primary use of a phone. All mobile phone users, whether buying for personal use or for a busi- ness, demand voice reliability, but they still want cool data features and will purchase a device based on those features. Linux can help meet this requirement. Speaking to the rapid rate of phone turnover and accessories hitting the market, another advantage of using Linux as the foundation of the Android platform stack is that it provides a hardware abstraction layer; the upper levels remain unchanged despite changes in the underlying hardware. Of course, good coding practices demand that user applications fail gracefully in the event a resource isn’t available, such as a camera not being present in a particular handset model. As new accessories appear on the market, drivers can be written at the Linux level to provide support, just as on other Linux platforms. This architecture is already demonstrating its value; Android devices are already available on distinct hardware platforms. HTC, Motorola, and others have released Android-based devices built on their respective hardware platforms. User applications, as well as core Android applications, are written in Java and are compiled into byte codes. Byte codes are interpreted at runtime by an inter- preter known as a virtual machine (VM).
  • 39. 12 CHAPTER 1 Introducing Android 1.3.2 Running in the Dalvik VM The Dalvik VM is an example of the need for efficiency, the desire for a rich program- ming environment, and even some intellectual property constraints, colliding, with innovation as the result. Android’s Java environment provides a rich application plat- form and is accessible because of the popularity of Java itself. Also, application perfor- mance, particularly in a low-memory setting such as you find in a mobile phone, is paramount for the mobile market. But this isn’t the only issue at hand. Android isn’t a Java ME platform. Without commenting on whether this is ulti- mately good or bad for Android, there are other forces at play here. There’s the mat- ter of Java VM licensing from Oracle. From a high level, Android’s code environment is Java. Applications are written in Java, which is compiled to Java byte codes and sub- sequently translated to a similar but different representation called dex files. These files are logically equivalent to Java byte codes, but they permit Android to run its applications in its own VM that’s both (arguably) free from Oracle’s licensing clutches and an open platform upon which Google, and potentially the open source commu- nity, can improve as necessary. Android is facing litigation challenges from Oracle about the use of Java. NOTE From the mobile application developer’s perspective, Android is a Java environment, but the runtime isn’t strictly a Java VM. This accounts for the incompatibilities between Android and proper Java environments and librar- ies. If you have a code library that you want to reuse, your best bet is to assume that your code is nearly source compatible, attempt to compile it into an Android project, then determine how close you are to having usable code. The important things to know about the Dalvik VM are that Android applications run inside it and that it relies on the Linux kernel for services such as process, memory, and filesystem management. Now that we’ve discussed the foundational technologies in Android, it’s time to focus on Android application development. The remainder of this chapter discusses high-level Android application architecture and introduces a simple Android applica- tion. If you’re not comfortable or ready to begin coding, you might want to jump to chapter 2, where we introduce the development environment step-by-step. 1.4 The Intent of Android development Let’s jump into the fray of Android development, focus on an important component of the Android platform, and expand to take a broader view of how Android applica- tions are constructed. An important and recurring theme of Android development is the Intent. An Intent in Android describes what you want to do. An Intent might look like “I want to look up a contact record” or “Please launch this website” or “Show the order confir- mation screen.” Intents are important because they not only facilitate navigation in an innovative way, as we’ll discuss next, they also represent the most important aspect of Android coding. Understand the Intent and you’ll understand Android.
  • 40. 13The Intent of Android development NOTE Instructions for setting up the Eclipse development environment are in appendix A. This environment is used for all Java examples in this book. Chapter 2 goes into more detail on setting up and using the development tools. The code examples in this chapter are primarily for illustrative purposes. We reference and introduce classes without necessarily naming specific Java packages. Subsequent chapters take a more rigorous approach to introducing Android-specific packages and classes. Next, we’ll look at the foundational information about why Intents are important, then we’ll describe how Intents work. Beyond the introduction of the Intent, the remainder of this chapter describes the major elements of Android application devel- opment, leading up to and including the first complete Android application that you’ll develop. 1.4.1 Empowering intuitive UIs The power of Android’s application framework lies in the way it brings a web mindset to mobile applications. This doesn’t mean the platform has only a powerful browser and is limited to clever JavaScript and server-side resources, but rather it goes to the core of how the Android platform works and how users interact with the mobile device. The power of the internet is that everything is just a click away. Those clicks are known as Uniform Resource Locators (URLs), or alternatively, Uniform Resource Identifiers (URIs). Using effective URIs permits easy and quick access to the information users need and want every day. “Send me the link” says it all. Beyond being an effective way to get access to data, why is this URI topic important, and what does it have to do with Intents? The answer is nontechnical but crucial: The way a mobile user navigates on the platform is crucial to its commercial success. Plat- forms that replicate the desktop experience on a mobile device are acceptable to only a small percentage of hardcore power users. Deep menus and multiple taps and clicks are generally not well received in the mobile market. The mobile application, more than in any other market, demands intuitive ease of use. A consumer might buy a device based on cool features that were enumerated in the marketing materials, but that same consumer is unlikely to even touch the instruction manual. A UI’s usability is highly correlated with its market penetration. UIs are also a reflection of the plat- form’s data access model, so if the navigation and data models are clean and intuitive, the UI will follow suit. Now we’re going to introduce Intents and IntentFilters, Android’s innovative navigation and triggering mechanisms. 1.4.2 Intents and how they work Intents and IntentFilters bring the “click on it” paradigm to the core of mobile application use (and development) for the Android platform:
  • 41. 14 CHAPTER 1 Introducing Android  An Intent is a declaration of need. It’s made up of a number of pieces of infor- mation that describe the desired action or service. We’re going to examine the requested action and, generically, the data that accompanies the requested action.  An IntentFilter is a declaration of capability and interest in offering assis- tance to those in need. It can be generic or specific with respect to which Intents it offers to service. The action attribute of an Intent is typically a verb; for example VIEW, PICK, or EDIT. A number of built-in Intent actions are defined as members of the Intent class, but application developers can create new actions as well. To view a piece of information, an application employs the following Intent action: android.content.Intent.ACTION_VIEW The data component of an Intent is expressed in the form of a URI and can be virtu- ally any piece of information, such as a contact record, a website location, or a refer- ence to a media clip. Table 1.1 lists some Android URI examples. The IntentFilter defines the relationship between the Intent and the application. IntentFilters can be specific to the data portion of the Intent, the action portion, or both. IntentFilters also contain a field known as a category. The category helps classify the action. For example, the category named CATEGORY_LAUNCHER instructs Android that the Activity containing this IntentFilter should be visible in the main application launcher or home screen. When an Intent is dispatched, the system evaluates the available Activitys, Services, and registered BroadcastReceivers (more on these in section 1.5) and dis- patches the Intent to the most appropriate recipient. Figure 1.4 depicts this relation- ship among Intents, IntentFilters, and BroadcastReceivers. IntentFilters are often defined in an application’s AndroidManifest.xml file with the <intent-filter> tag. The AndroidManifest.xml file is essentially an application descriptor file, which we’ll discuss later in this chapter. A common task on a mobile device is looking up a specific contact record for the purpose of initiating a call, sending a text message, or looking up a snail-mail address when you’re standing in line at the neighborhood pack-and-ship store. Or a user might want to view a specific piece of information, say a contact record for user 1234. In these cases, the action is ACTION_VIEW and the data is a specific contact record Table 1.1 Commonly employed URIs in Android Type of information URI data Contact lookup content://contacts/people Map lookup/search Geo:0,0?q=23+Route+206+Stanhope+NJ Browser launch to a specific website http://www.google.com/
  • 42.
  • 43. 16 CHAPTER 1 Introducing Android helpful when you know exactly which Activity you want to handle the Intent and you don’t want to leave anything to chance in terms of what code is executed. To cre- ate an explicit Intent, use the overloaded Intent constructor, which takes a class as an argument: public void onClick(View v) { try { startActivityForResult(new Intent(v.getContext(),RefreshJobs.class),0); } catch (Exception e) { . . . } } These examples show how an Android developer creates an Intent and asks for it to be handled. Similarly, an Android application can be deployed with an IntentFilter, indicating that it responds to Intents that were already defined on the system, thereby publishing new functionality for the platform. This facet alone should bring joy to independent software vendors (ISVs) who’ve made a living by offering better contact managers and to-do list management software titles for other mobile platforms. Intent resolution, or dispatching, takes place at runtime, as opposed to when the application is compiled. You can add specific Intent-handling features to a device, which might provide an upgraded or more desirable set of functionality than the orig- inal shipping software. This runtime dispatching is also referred to as late binding. Thus far, this discussion of Intents has focused on the variety of Intents that cause UI elements to be displayed. Other Intents are more event-driven than task-oriented, as our earlier contact record example described. For example, you also use the Intent class to notify applications that a text message has arrived. Intents are a central ele- ment to Android; we’ll revisit them on more than one occasion. Now that we’ve explained Intents as the catalyst for navigation and event flow on Android, let’s jump to a broader view and discuss the Android application lifecycle and the key components that make Android tick. The Intent will come into better focus as we further explore Android throughout this book. The power and the complexity of Intents It’s not hard to imagine that an absolutely unique user experience is possible with Android because of the variety of Activitys with specific IntentFilters that are installed on any given device. It’s architecturally feasible to upgrade various aspects of an Android installation to provide sophisticated functionality and customization. Though this might be a desirable characteristic for the user, it can be troublesome for someone providing tech support who has to navigate a number of components and applications to troubleshoot a problem. Because of the potential for added complexity, this approach of ad hoc system patch- ing to upgrade specific functionality should be entertained cautiously and with your eyes wide open to the potential pitfalls associated with this approach.
  • 44. 17Four kinds of Android components 1.5 Four kinds of Android components Let’s build on your knowledge of the Intent and IntentFilter classes and explore the four primary components of Android applications, as well as their relation to the Android process model. We’ll include code snippets to provide a taste of Android application development. We’re going to leave more in-depth examples and discus- sion for later chapters. NOTE A particular Android application might not contain all of these ele- ments, but will have at least one of these elements, and could have all of them. 1.5.1 Activity An application might have a UI, but it doesn’t have to have one. If it has a UI, it’ll have at least one Activity. The easiest way to think of an Android Activity is to relate it to a visible screen, because more often than not there’s a one-to-one relationship between an Activity and a UI screen. This relationship is similar to that of a controller in the MVC paradigm. Android applications often contain more than one Activity. Each Activity dis- plays a UI and responds to system- and user-initiated events. The Activity employs one or more Views to present the actual UI elements to the user. The Activity class is extended by user classes, as shown in the following listing. package com.msi.manning.chapter1; import android.app.Activity; import android.os.Bundle; public class Activity1 extends Activity { @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); } } The Activity class is part of the android.app Java package, found in the Android runtime. The Android runtime is deployed in the android.jar file. The class Activity1 extends the class Activity, which we’ll examine in detail in chapter 3. One of the primary tasks an Activity performs is displaying UI elements, which are implemented as Views and are typically defined in XML layout files. Chapter 3 goes into more detail on Views and Resources. Moving from one Activity to another is accomplished with the startActivity() method or the startActivityForResult() method when you want a synchronous call/result paradigm. The argument to these methods is an instance of an Intent. The Activity represents a visible application component within Android. With assistance from the View class, which we’ll cover in chapter 3, the Activity is the most Listing 1.1 A basic Activity in an Android application
  • 45. 18 CHAPTER 1 Introducing Android commonly employed Android application component. The next topic of interest is the Service, which runs in the background and doesn’t generally present a direct UI. 1.5.2 Service If an application is to have a long lifecycle, it’s often best to put it into a Service. For example, a background data synchronization utility should be implemented as a Service. A best practice is to launch Services on a periodic or as-needed basis, trig- gered by a system alarm, and then have the Service terminate when its task is complete. Like the Activity, a Service is a class in the Android runtime that you should extend, as shown in the following listing. This example extends a Service, and peri- odically publishes an informative message to the Android log. package com.msi.manning.chapter1; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class Service1 extends Service implements Runnable { public static final String tag = "service1"; private int counter = 0; @Override protected void onCreate() { super.onCreate(); Thread aThread = new Thread (this); aThread.start(); } public void run() { while (true) { try { Log.i(tag,"service1 firing : # " + counter++); Thread.sleep(10000); } catch(Exception ee) { Log.e(tag,ee.getMessage()); } } } Listing 1.2 A simple example of an Android Service You say Intent; I say Intent The Intent class is used in similar sounding but very different scenarios. Some Intents are used to assist in navigating from one Activity to the next, such as the example given earlier of viewing a contact record. Activities are the targets of these kinds of Intents, which are used with the startActivity or startActivi- tyForResult methods. Also, a Service can be started by passing an Intent to the startService method. BroadcastReceivers receive Intents when responding to system-wide events, such as a ringing phone or an incoming text message. Extend Service class B InitializationC
  • 46. 19Four kinds of Android components @Override public IBinder onBind(Intent intent) { return null; } } This example requires that the package android.app.Service be imported. This package contains the Service class. This example also demonstrates Android’s log- ging mechanism android.util.Log, which is useful for debugging purposes. (Many examples in this book include using the logging facility. We’ll discuss logging in more depth in chapter 2.) The Service1 class B extends the Service class. This class implements the Runnable interface to perform its main task on a separate thread. The onCreate method C of the Service class permits the application to perform initial- ization-type tasks. We’re going to talk about the onBind() method D in further detail in chapter 4, when we’ll explore the topic of interprocess communication in general. Services are started with the startService(Intent) method of the abstract Context class. Note that, again, the Intent is used to initiate a desired result on the platform. Now that the application has a UI in an Activity and a means to have a back- ground task via an instance of a Service, it’s time to explore the BroadcastReceiver, another form of Android application that’s dedicated to processing Intents. 1.5.3 BroadcastReceiver If an application wants to receive and respond to a global event, such as a ringing phone or an incoming text message, it must register as a BroadcastReceiver. An application registers to receive Intents in one of the following ways:  The application can implement a <receiver> element in the Android- Manfest.xml file, which describes the BroadcastReceiver’s class name and enu- merates its IntentFilters. Remember, the IntentFilter is a descriptor of the Intent an application wants to process. If the receiver is registered in the AndroidManifest.xml file, the application doesn’t need to be running in order to be triggered. When the event occurs, the application is started automatically upon notification of the triggering event. Thankfully, all this housekeeping is managed by the Android OS itself.  An application can register at runtime via the Context class’s register- Receiver method. Like Services, BroadcastReceivers don’t have a UI. Even more importantly, the code running in the onReceive method of a BroadcastReceiver should make no assump- tions about persistence or long-running operations. If the BroadcastReceiver requires more than a trivial amount of code execution, it’s recommended that the code initiate a request to a Service to complete the requested functionality because the Service application component is designed for longer-running operations whereas the BroadcastReceiver is meant for responding to various triggers. Handle Binding request D
  • 47. 20 CHAPTER 1 Introducing Android NOTE The familiar Intent class is used in triggering BroadcastReceivers. The parameters will differ, depending on whether you’re starting an Activ- ity, a Service, or a BroadcastReceiver, but it’s the same Intent class that’s used throughout the Android platform. A BroadcastReceiver implements the abstract method onReceive to process incom- ing Intents. The arguments to the method are a Context and an Intent. The method returns void, but a handful of methods are useful for passing back results, including setResult, which passes back to the invoker an integer return code, a String return value, and a Bundle value, which can contain any number of objects. The following listing is an example of a BroadcastReceiver triggering upon receipt of an incoming text message. package com.msi.manning.unlockingandroid; import android.content.Context; import android.content.Intent; import android.util.Log; import.android.content.BroadcastReceiver public class MySMSMailBox extends BroadcastReceiver { public static final String tag = "MySMSMailBox"; @Override public void onReceive(Context context, Intent intent) { Log.i(tag,"onReceive"); if (intent.getAction().equals ("android.provider.Telephony.SMS_RECEIVED")) { Log.i(tag,"Found our Event!"); } } We need to discuss a few items in this listing. The class MySMSMailBox extends the BroadcastReceiver class. This subclass approach is the most straightforward way to employ a BroadcastReceiver. (Note the class name MySMSMailBox; it’ll be used in the AndroidManifest.xml file, shown in listing 1.4.) The tag variable B is used in con- junction with the logging mechanism to assist in labeling messages sent to the console log on the emulator. Using a tag in the log enables us to filter and organize log mes- sages in the console. (We discuss the log mechanism in more detail in chapter 2.) The onReceive method is where all the work takes place in a BroadcastReceiver; you must implement this method. A given BroadcastReceiver can register multiple IntentFilters. A BroadcastReceiver can be instantiated for an arbitrary number of Intents. It’s important to make sure that the application handles the appropriate Intent by checking the action of the incoming Intent C. When the application receives the desired Intent, it should carry out the specific functionality that’s required. A com- mon task in an SMS-receiving application is to parse the message and display it to the user via the capabilities found in the NotificationManager. (We’ll discuss notifica- tions in chapter 8.) In listing 1.3, we simply record the action to the log. Listing 1.3 A sample BroadcastReceiver Tag used in logging B Check Intent’s action C
  • 48. 21Four kinds of Android components In order for this BroadcastReceiver to fire and receive this Intent, the Broadcast- Receiver is listed in the AndroidManifest.xml file, along with an appropriate intent- filter tag, as shown in the following listing. This listing contains the elements required for the application to respond to an incoming text message. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.msi.manning.unlockingandroid"> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <application android:icon="@drawable/icon"> <activity android:name=".Activity1" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".MySMSMailBox" > <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver> </application> </manifest> Certain tasks within the Android platform require the application to have a designated privilege. To give an application the required permissions, use the <uses- permission> tag B. (We’ll discuss this tag in detail in section 1.6.) The <receiver> tag contains the class name of the class implementing the BroadcastReceiver. In this example, the class name is MySMSMailBox, from the package com.msi.manning. unlockingandroid. Be sure to note the dot that precedes the name C. This dot is required. If your application isn’t behaving as expected, one of the first places to check is your Android.xml file, and look for the dot before the class name! The IntentFilter is defined in the <intent-filter> tag. The desired action in this Listing 1.4 AndroidManifest.xml BRequired permission Receiver tag; note dot prefix C Testing SMS The emulator has a built-in set of tools for manipulating certain telephony behavior to simulate a variety of conditions, such as in-network and out-of-network coverage and placing phone calls. To send an SMS message to the emulator, telnet to port 5554 (the port number might vary on your system), which will connect to the emulator, and issue the follow- ing command at the prompt: sms send <sender's phone number> <body of text message> To learn more about available commands, type help at the prompt. We’ll discuss these tools in more detail in chapter 2.
  • 49. 22 CHAPTER 1 Introducing Android example is android.provider.Telephony.SMS_RECEIVED. The Android SDK contains the available actions for the standard Intents. Also, remember that user applications can define their own Intents, as well as listen for them. Now that we’ve introduced Intents and the Android classes that process or handle Intents, it’s time to explore the next major Android application topic: the Content- Provider, Android’s preferred data-publishing mechanism. 1.5.4 ContentProvider If an application manages data and needs to expose that data to other applications running in the Android environment, you should consider a ContentProvider. If an application component (Activity, Service, or BroadcastReceiver) needs to access data from another application, the component accesses the other application’s ContentProvider. The ContentProvider implements a standard set of methods to permit an application to access a data store. The access might be for read or write operations, or for both. A ContentProvider can provide data to an Activity or Service in the same containing application, as well as to an Activity or Service con- tained in other applications. A ContentProvider can use any form of data storage mechanism available on the Android platform, including files, SQLite databases, or even a memory-based hash map if data persistence isn’t required. The ContentProvider is a data layer that pro- vides data abstraction for its clients and centralizing storage and retrieval routines in a single place. Sharing files or databases directly is discouraged on the Android platform, and is enforced by the underlying Linux security system, which prevents ad hoc file access from one application space to another without explicitly granted permissions. Data stored in a ContentProvider can be traditional data types, such as integers and strings. Content providers can also manage binary data, such as image data. When binary data is retrieved, the suggested best practice is to return a string representing the filename that contains the binary data. If a filename is returned as part of a ContentProvider query, the application shouldn’t access the file directly; you should use the helper class, ContentResolver’s openInputStream method, to access the binary data. This approach navigates the Linux process and security hurdles, as well as keeps all data access normalized through the ContentProvider. Figure 1.5 outlines the relationship among ContentProviders, data stores, and their clients. A ContentProvider’s data is accessed by an Android application through a Con- tent URI. A ContentProvider defines this URI as a public static final String. For example, an application might have a data store managing material safety data sheets. The Content URI for this ContentProvider might look like this: public static final Uri CONTENT_URI = Uri.parse("content://com.msi.manning.provider.unlockingandroid/datasheets"); From this point, accessing a ContentProvider is similar to using Structured Query Language (SQL) in other platforms, though a complete SQL statement isn’t employed. A query is submitted to the ContentProvider, including the columns
  • 50.
  • 51. 24 CHAPTER 1 Introducing Android 1.6 Understanding the AndroidManifest.xml file In the preceding sections, we introduced the common elements of an Android appli- cation. A fundamental fact of Android development is that an Android application contains at least one Activity, Service, BroadcastReceiver, or ContentProvider. Some of these elements advertise the Intents they’re interested in processing via the IntentFilter mechanism. All these pieces of information need to be tied together for an Android application to execute. The glue mechanism for this task of defining relationships is the AndroidManifest.xml file. The AndroidManifest.xml file exists in the root of an application directory and contains all the design-time relationships of a specific application and Intents. AndroidManfest.xml files act as deployment descriptors for Android applications. The following listing is an example of a simple AndroidManifest.xml file. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.msi.manning.unlockingandroid"> <application android:icon="@drawable/icon"> <activity android:name=".Activity1" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Looking at this simple AndroidManifest.xml file, you see that the manifest element contains the obligatory namespace, as well as the Java package name containing this application. This application contains a single Activity, with the class name Activity1. Note also the @string syntax. Any time an @ symbol is used in an AndroidManifest.xml file, it references information stored in one of the resource files. In this case, the label attribute is obtained from the string resource identified as app_name. (We discuss resources in further detail later in chapter 3.) This applica- tion’s lone Activity contains a single IntentFilter definition. The IntentFilter used here is the most common IntentFilter seen in Android applications. The action android.intent.action.MAIN indicates that this is an entry point to the appli- cation. The category android.intent.category.LAUNCHER places this Activity in the launcher window, as shown in figure 1.6. It’s possible to have multiple Activity elements in a manifest file (and thereby an application), with zero or more of them visible in the launcher window. In addition to the elements used in the sample manifest file shown in listing 1.5, other common tags are:  The <service> tag represents a Service. The attributes of the <service> tag include its class and label. A Service might also include the <intent-filter> tag. Listing 1.5 AndroidManifest.xml file for a basic Android application
  • 52. 25Mapping applications to processes  The <receiver> tag represents a BroadcastReceiver, which might have an explicit <intent-filter> tag.  The <uses-permission> tag tells Android that this application requires certain security privileges. For exam- ple, if an application requires access to the contacts on a device, it requires the following tag in its AndroidMani- fest.xml file: <uses-permission android:name= "android.permission.READ_CONTACTS" /> We’ll revisit the AndroidManifest.xml file a number of times throughout the book because we need to add more details about certain ele- ments and specific coding scenarios. Now that you have a basic understanding of the Android application and the AndroidMani- fest.xml file, which describes its components, it’s time to discuss how and where an Android application executes. To do that, we need to talk about the relationship between an Android application and its Linux and Dalvik VM runtime. 1.7 Mapping applications to processes Android applications each run in a single Linux process. Android relies on Linux for pro- cess management, and the application itself runs in an instance of the Dalvik VM. The OS might need to unload, or even kill, an application from time to time to accommo- date resource allocation demands. The system uses a hierarchy or sequence to select the victim during a resource shortage. In general, the system follows these rules:  Visible, running activities have top priority.  Visible, nonrunning activities are important, because they’re recently paused and are likely to be resumed shortly.  Running services are next in priority.  The most likely candidates for termination are processes that are empty (loaded perhaps for performance-caching purposes) or processes that have dormant Activitys. Let’s apply some of what you’ve learned by building your first Android application. Figure 1.6 Applications are listed in the launcher based on their IntentFilter. In this example, the application Where Do You Live is available in the LAUNCHER category.
  • 53. 26 CHAPTER 1 Introducing Android 1.8 Creating an Android application Let’s look at a simple Android application consisting of a single Activity, with one View. The Activity collects data (a street address) and creates an Intent to find this address. The Intent is ultimately dispatched to Google Maps. Figure 1.7 is a screen shot of the application running on the emulator. The name of the application is Where Do You Live. ps -a The Linux environment is complete, including process management. You can launch and kill applications directly from the shell on the Android platform, but this is a developer’s debugging task, not something the average Android handset user is likely to carry out. It’s nice to have this option for troubleshooting application issues. It’s a relatively recent phenomenon to be able to touch the metal of a mobile phone in this way. For more in-depth exploration of the Linux foundations of Android, see chapter 13. Figure 1.7 This Android application demonstrates a simple Activity and Intent.
  • 54. 27Creating an Android application As we previously stated, the AndroidManifest.xml file contains the descriptors for the application components of the application. This application contains a single Activity named AWhereDoYouLive. The application’s AndroidManifest.xml file is shown in the following listing. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.msi.manning.unlockingandroid"> <application android:icon="@drawable/icon"> <activity android:name=".AWhereDoYouLive" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.INTERNET" /> </manifest> The sole Activity is implemented in the file AWhereDoYouLive.java, shown in the following listing. package com.msi.manning.unlockingandroid; // imports omitted for brevity public class AWhereDoYouLive extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); final EditText addressfield = (EditText) findViewById(R.id.address); final Button button = (Button) findViewById(R.id.launchmap); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View view) { try { String address = addressfield.getText().toString(); address = address.replace(' ', '+'); Intent geoIntent = new Intent (android.content.Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + address)); startActivity(geoIntent); } catch (Exception e) { } } }); } } Listing 1.6 AndroidManifest.xml for the Where Do You Live application Listing 1.7 Implementing the Android Activity in AWhereDoYouLive.java B Get address C Prepare Intent
  • 55. 28 CHAPTER 1 Introducing Android In this example application, the setContentView method creates the primary UI, which is a layout defined in main.xml in the /res/layout directory. The EditText view collects information, which in this case is an address. The EditText view is a text box or edit box in generic programming parlance. The findViewById method connects the resource identified by R.id.address to an instance of the EditText class. A Button object is connected to the launchmap UI element, again using the find- ViewById method. When this button is clicked, the application obtains the entered address by invoking the getText method of the associated EditText B. When the address has been retrieved from the UI, we need to create an Intent to find the entered address. The Intent has a VIEW action, and the data portion repre- sents a geographic search query C. Finally, the application asks Android to perform the Intent, which ultimately results in the mapping application displaying the chosen address. The startActivity method is invoked, passing in the prepared Intent. Resources are precompiled into a special class known as the R class, as shown in listing 1.8. The final members of this class represent UI elements. You should never modify the R.java file manually; it’s automatically built every time the underlying resources change. (We’ll cover Android resources in greater depth in chapter 3.) /* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.msi.manning.unlockingandroid; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; } public static final class id { public static final int address=0x7f050000; public static final int launchmap=0x7f050001; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040000; } } Figure 1.7 shows the sample application in action. Someone looked up the address of the White House; the result shows the White House pinpointed on the map. Listing 1.8 R.java contains the R class, which has UI element identifiers