SlideShare a Scribd company logo
Android Application Development Programming With
The Google Sdk 1st Edition Rick Rogers download
https://ebookbell.com/product/android-application-development-
programming-with-the-google-sdk-1st-edition-rick-rogers-2483424
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Android Programming Android Application Development Rk Raji
https://ebookbell.com/product/android-programming-android-application-
development-rk-raji-5903262
Android Programming Android Application Development Raji Rk
https://ebookbell.com/product/android-programming-android-application-
development-raji-rk-6766916
Android Wearable Programming Expand On Your Android Development
Capabilities By Building Applications For Android Wear 1st Edition
Steven F Daniel
https://ebookbell.com/product/android-wearable-programming-expand-on-
your-android-development-capabilities-by-building-applications-for-
android-wear-1st-edition-steven-f-daniel-23129878
Android Application Development Cookbook Second Edition 2016 Second
Edition Rick Boyer
https://ebookbell.com/product/android-application-development-
cookbook-second-edition-2016-second-edition-rick-boyer-57645008
Android Application Development For Dummies 2nd Edition Michael Burton
Donn Felker
https://ebookbell.com/product/android-application-development-for-
dummies-2nd-edition-michael-burton-donn-felker-57723130
Android Application Development For Dummies Donn Felker
https://ebookbell.com/product/android-application-development-for-
dummies-donn-felker-25565548
Android Application Development Course Code And401 Version 7 4th
Edition Coll
https://ebookbell.com/product/android-application-development-course-
code-and401-version-7-4th-edition-coll-36894592
Android Application Development Cookbook 93 Recipes For Building
Winning Apps 1st Edition Weimeng Lee
https://ebookbell.com/product/android-application-development-
cookbook-93-recipes-for-building-winning-apps-1st-edition-weimeng-
lee-4072054
Android Application Development For Java Programmers James Sheusi
https://ebookbell.com/product/android-application-development-for-
java-programmers-james-sheusi-4144872
Android Application Development Programming With The Google Sdk 1st Edition Rick Rogers
Android Application Development Programming With The Google Sdk 1st Edition Rick Rogers
Android Application Development Programming With The Google Sdk 1st Edition Rick Rogers
Android Application Development
Rick Rogers, John Lombardo, Zigurd Mednieks, and Blake
Meike
Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo
Android Application Development
by Rick Rogers, John Lombardo, Zigurd Mednieks, and Blake Meike
Copyright © 2009 Rick Rogers, John Lombardo, Zigurd Mednieks, and Blake Meike. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions
are also available for most titles (http://mysafaribooksonline.com). For more information, contact our
corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com.
Editor: Andy Oram
Production Editor: Sumita Mukherji
Copyeditor: Genevieve d’Entremont
Proofreader: Sada Preisch
Indexer: Joe Wizda
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Robert Romano
Printing History:
May 2009: First Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc. Android Application Development, the image of an Eastern quoll and related trade
dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a
trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume
no responsibility for errors or omissions, or for damages resulting from the use of the information con-
tained herein.
TM
This book uses RepKover™, a durable and flexible lay-flat binding.
ISBN: 978-0-596-52147-9
[M]
1241533714
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
Part I. Development Kit Walk-Through
1. Getting to Know Android . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Why Android? 3
The Open Handset Alliance 4
The Android Execution Environment 5
Components of an Android Application 6
Android Activity Lifecycle 8
Android Service Lifecycle 10
How This Book Fits Together 10
2. Setting Up Your Android Development Environment . . . . . . . . . . . . . . . . . . . . . . . . . 13
Setting Up Your Development Environment 13
Creating an Android Development Environment 14
Hello, Android 18
Where We’re Going 18
Starting a New Android Application: HelloWorld 18
Writing HelloWorld 22
Running HelloWorld 24
3. Using the Android Development Environment for Real Applications . . . . . . . . . . . . 27
MicroJobs: This Book’s Main Sample Application 27
Android and Social Networking 27
Downloading the MJAndroid Code 30
A Brief Tour of the MJAndroid Code 30
The Project Root Folder (MJAndroid) 30
The Source Folder (src) 31
The Resource Folder (res) 32
First Steps: Building and Running the MicroJobs Application 33
iii
A Very Short Tour of the Android SDK/Eclipse IDE 33
Loading and Starting the Application 35
Digging a Little Deeper: What Can Go Wrong? 36
Running an Application on the T-Mobile Phone 39
Summary 41
4. Under the Covers: Startup Code and Resources in the MJAndroid Application . . . . 43
Initialization Parameters in AndroidManifest.xml 44
Initialization in MicroJobs.java 46
More Initialization of MicroJobs.java 52
Summary 56
5. Debugging Android Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
The Tools 57
Eclipse Java Editor 58
Java Errors 58
The Debugger 64
Logcat 67
Android Debug Bridge (adb) 71
DDMS: Dalvik Debug Monitor Service 74
Traceview 75
Summary 80
6. The ApiDemos Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Application Setup in the Manifest File 81
Finding the Source to an Interesting Example 83
Custom Title Demo 83
Linkify Demo 84
Adding Your Own Examples to ApiDemos 84
7. Signing and Publishing Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Test Your Application 88
Attach an End User License Agreement If Desired 89
Create and Attach an Icon and Label 89
Clean Up for Release 90
Version Your Application 90
Obtaining a Signing Certificate and API Key 90
Getting a Signing Certificate for an Application You Are Going to Ship 91
Getting a Signing Certificate While Debugging 93
Signing Your Application 95
Retesting Your Application 96
Publishing on Android Market 96
Signing Up As an Android Developer 96
iv | Table of Contents
Uploading Your Application 96
Part II. Programming Topics
8. Persistent Data Storage: SQLite Databases and Content Providers . . . . . . . . . . . . . 101
Databases 101
Basic Structure of the MicroJobsDatabase Class 102
Reading Data from the Database 107
Modifying the Database 110
Content Providers 114
Introducing NotePad 116
Content Providers 118
Consuming a Content Provider 129
9. Location and Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Location-Based Services 137
Mapping 139
The Google Maps Activity 139
The MapView and MapActivity 140
Working with MapViews 140
MapView and MyLocationOverlay Initialization 141
Pausing and Resuming a MapActivity 144
Controlling the Map with Menu Buttons 145
Controlling the Map with the KeyPad 147
Location Without Maps 148
The Manifest and Layout Files 148
Connecting to a Location Provider and Getting Location Updates 149
Updating the Emulated Location 152
10. Building a View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Android GUI Architecture 157
The Model 157
The View 158
The Controller 159
Putting It Together 159
Assembling a Graphical Interface 161
Wiring Up the Controller 166
Listening to the Model 168
Listening for Touch Events 173
Listening for Key Events 176
Alternative Ways to Handle Events 177
Advanced Wiring: Focus and Threading 179
Table of Contents | v
The Menu 183
11. A Widget Bestiary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Android Views 188
TextView and EditText 188
Button and ImageButton 191
Adapters and AdapterViews 192
CheckBoxes, RadioButtons, and Spinners 193
ViewGroups 198
Gallery and GridView 198
ListView and ListActivity 202
ScrollView 204
TabHost 205
Layouts 208
Frame Layout 209
LinearLayout 209
TableLayout 213
AbsoluteLayout 215
RelativeLayout 216
12. Drawing 2D and 3D Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Rolling Your Own Widgets 221
Layout 222
Canvas Drawing 226
Drawables 237
Bitmaps 242
Bling 243
Shadows, Gradients, and Filters 246
Animation 247
OpenGL Graphics 252
13. Inter-Process Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Intents: Simple, Low-Overhead IPC 258
Intent Objects Used in Inter-Process Communication 258
Activity Objects and Navigating the User Interface Hierarchy 259
Example: An Intent to Pick How We Say “Hello World” 259
Getting a Result via Inter-Process Communication 262
Remote Methods and AIDL 265
Android Interface Definition Language 266
Classes Underlying AIDL-Generated Interfaces 270
Publishing an Interface 273
Android IPC Compared with Java Native Interface (JNI) 274
What Binder Doesn’t Do 275
vi | Table of Contents
Binder and Linux 275
14. Simple Phone Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Quick and Easy Phone Calls 277
Creating an Example Application to Run the call Method 278
Embedding the Code Snippet in a Simple Application 279
Exploring the Phone Code Through the Debugger 280
Creating an Instance of an Intent 282
Adding Data to an Instance of an Intent 283
Initiating a Phone Call 284
Exception Handling 284
Android Application-Level Modularity and Telephony 285
15. Telephony State Information and Android Telephony Classes . . . . . . . . . . . . . . . . 287
Operations Offered by the android.telephony Package 287
Package Summary 288
Limitations on What Applications Can Do with the Phone 288
Example: Determining the State of a Call 289
Android Telephony Internals 291
Inter-Process Communication and AIDL in the
android.internal.telephony Package 291
The android.internal.telephony Package 292
The android.internal.telephony.gsm Package 295
Exploring Android Telephony Internals 299
Android and VoIP 302
Appendix: Wireless Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Table of Contents | vii
Android Application Development Programming With The Google Sdk 1st Edition Rick Rogers
Preface
When Google announced the development of Android, the field of mobile platforms
was already well established. Even in the narrower category of open source platforms,
a number of viable alternatives were being pushed by proponents. Yet Android has
stimulated not only widespread technical interest but rampant speculation about its
potential to completely transform the world of the personal device. Instead of a con-
venient prop to support a set of familiar functions, such as phone calls, email, and
restaurant lookups, the electronic device could become an open-ended window into
the whole world—could become, in short, anything that the user and the developer
could think to make it.
How much of the cogent analysis and fervid hype will come to pass can be discussed
elsewhere; this book is for those who want to get to know the programming environ-
ment for Android and learn what they themselves can do to make a difference. We have
spent many grueling months investigating the source code over multiple releases and
trying out the functions of the library and development kit. We have been working hard
to uncover the true Android, going beyond any documentation we could find online
or in print.
This book, read carefully, can enable any Java programmer to develop useful and robust
applications for Android. It also takes you into the internals in some places, so you
know how Android supports what you’re doing—and so you can play around with its
open source code if you like.
Audience
This book is intended for experienced software developers who want to develop ap-
plications in the Android mobile environment. It assumes you have some experience
with the Java programming language, with using Java to implement user interfaces,
and that you are at least familiar with the technologies Android uses, such as XML,
SQL, GTalk(XMPP), OpenGL-ES, and HTTP.
ix
How This Book Is Organized
This book is organized around the core example program introduced in Chapter 2.
Later chapters illustrate development techniques by adding to the example through
implementing modular extensions, where this is feasible. Some chapters (and the Ap-
pendix) cover more advanced topics that are not required for many applications.
Part I, Development Kit Walk-Through, gets you started with the basics you’ll need to
write applications.
Chapter 1, Getting to Know Android, explains Android’s place in the market and its
basic architecture.
Chapter 2, Setting Up Your Android Development Environment, tells you how to down-
load the software you need, including Eclipse and the Android plug-in, and how to get
started programming.
Chapter 3, Using the Android Development Environment for Real Applications, describes
the files that make up a typical Android program.
Chapter 4, Under the Covers: Startup Code and Resources in the MJAndroid Applica-
tion, looks at the fundamental Java code and XML resources that every application
needs.
Chapter 5, Debugging Android Applications, introduces a number of tools for debugging
and performance, including Eclipse, logs, the Android Debug Bridge (adb), DDMS, and
Traceview.
Chapter 6, The ApiDemos Application, offers a high-level tour of the sample Android
code included in the toolkit, with tips for exploring it yourself.
Chapter 7, Signing and Publishing Your Application, shows you how to make your ap-
plication ready for public use.
Part II, Programming Topics, explores in depth the major libraries you’ll need, and
shows you how to use them effectively.
Chapter 8, Persistent Data Storage: SQLite Databases and Content Providers, shows
how to use the two most powerful means in Android for storing and serving data.
Chapter 9, Location and Mapping, shows how to determine and display the user’s lo-
cation, and how to use Google Maps.
Chapter 10, Building a View, introduces graphical programming on Android by ex-
plaining how to create and manipulate windows and views.
Chapter 11, A Widget Bestiary, covers the most popular and useful graphical interface
elements provided by Android.
Chapter 12, Drawing 2D and 3D Graphics, shows how to lay out graphics, and delves
into drawing, transforming, and animating your own graphics.
x | Preface
Chapter 13, Inter-Process Communication, covers Intents and Remote Methods, which
allow you to access the functionality of other applications.
Chapter 14, Simple Phone Calls, shows how to dial a number from an application, and
explains how Android carries out the request.
Chapter 15, Telephony State Information and Android Telephony Classes, shows how
to get information about telephony service and phone calls, and offers a tour of tel-
ephony internals.
Appendix, Wireless Protocols, offers some background and history on wireless services.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program elements
such as variable or function names, databases, data types, environment variables,
statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter-
mined by context.
This icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.
Using Code Examples
This book is here to help you get your job done. In general, you may use the code in
this book in your programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the code. For example,
writing a program that uses several chunks of code from this book does not require
permission. Selling or distributing a CD-ROM of examples from O’Reilly books does
Preface | xi
require permission. Answering a question by citing this book and quoting example
code does not require permission. Incorporating a significant amount of example code
from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title,
author, publisher, and ISBN. For example: “Android Application Development by Rick
Rogers, John Lombardo, Zigurd Mednieks, and Blake Meike. Copyright 2009 Rick
Rogers, John Lombardo, Zigurd Mednieks, and Blake Meike, 978-0-596-52147-9.”
If you feel your use of code examples falls outside fair use or the permission given here,
feel free to contact us at permissions@oreilly.com.
Safari® Books Online
When you see a Safari® Books Online icon on the cover of your favorite
technology book, that means the book is available online through the
O’Reilly Network Safari Bookshelf.
Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily
search thousands of top tech books, cut and paste code samples, download chapters,
and find quick answers when you need the most accurate, current information. Try it
for free at http://my.safaribooksonline.com.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at:
http://www.oreilly.com/catalog/9780596521479
To comment or ask technical questions about this book, send email to:
bookquestions@oreilly.com
For more information about our books, conferences, Resource Centers, and the
O’Reilly Network, see our website at:
http://www.oreilly.com
xii | Preface
Acknowledgments
We’d like to thank Bill Dimmick, Brad O’Hearne, and Hycel Taylor for their thoughtful
and careful reviews of this book under a high-pressure timeline.
Rick Rogers
Like anything worth doing, I suppose, this book ended up taking more time and effort
than any of us planned in the beginning. I’d like to thank my coauthors and the great
folks at O’Reilly for sticking with it and bringing the work to fruition, through all the
twists and turns. I’d also like to thank my family and friends, who encouraged me all
through the process, and lent an ear when I just needed to talk. Most especially, though,
I want to dedicate the book to my wife, Susie, whose patience knows no bounds, and
whose amazing attitude toward life is an enduring inspiration for me no matter what
I’m doing.
John Lombardo
I would like to thank my wonderful wife, Dena, who kept life from interfering when I
closed the office door to work on the book. I want to dedicate this book to my mother,
Marguerite Megaris, who died suddenly in 2007. I gave her a copy of my first book,
Embedded Linux (New Riders), back in 2001. She cracked it open to a page with some
assembly code, looked at it for about 10 seconds, closed it, and said, “That’s nice, dear.”
We had a good laugh over that. I’d also like to thank all the wonderful people at O’Reilly
for all their hard work. I’d especially like to thank Andy Oram, who coddled and
prodded us in just the right doses to keep the book humming along at a good clip.
Zigurd Mednieks
Thanks to Terry, Maija, and Charles for putting up with my schedule while I was writ-
ing, and to Andy Oram and my coauthors for letting me participate, and hopefully,
contribute.
Blake Meike
I am very grateful to have been invited to work with such an amazing group of people.
Thanks to Zigurd for suggesting it; Andy Oram for practically holding my pen; and
Rick, John, and Isabel Kunkle for making those Thursday morning calls a pleasure.
Thanks to Mike Morton for actually reading both the text and the code. Though it may
seem obvious, thanks to the Google Android developers. Not bad guys. Not bad at all.
Finally, love and thanks to my wife, Catherine, who never let me see any disappoint-
ment when I said, yet again, “Can’t. Gotta work on the book this weekend.” Yes, babe,
let’s do the bookcase now.
Preface | xiii
Android Application Development Programming With The Google Sdk 1st Edition Rick Rogers
PART I
Development Kit Walk-Through
This book gets you started with Android. We’ll explain what’s special about Android’s
features and how its architecture achieves its goals, and show you how to get started
programming. You’ll learn the tools that let you write programs using Eclipse; run them
on the Android emulator; and carry out debugging, tracing, and profiling. The last
chapter in Part 1 shows you how to sign your program for public distribution.
Android Application Development Programming With The Google Sdk 1st Edition Rick Rogers
CHAPTER 1
Getting to Know Android
Why Android?
Google’s Android mobile phone software platform may be the next big opportunity for
application software developers.
Google announced the Open Handset Alliance and the Android platform in November
of 2007, releasing the first beta version of the Android Software Development Kit (SDK)
at the same time. Within a matter of a few months, over 1 million people had down-
loaded versions of the SDK from Google’s website. In the United States, T-Mobile
announced the G1 Android mobile phone in October of 2008, and estimates are that
several hundred thousand G1s were sold before the end of that year. There are already
several competing mobile phone software stacks in the market, so why is there such
interest in Android?
Android has the potential for removing the barriers to success in the development and
sale of a new generation of mobile phone application software. Just as the the stand-
ardized PC and Macintosh platforms created markets for desktop and server software,
Android, by providing a standard mobile phone application environment, will create
a market for mobile applications—and the opportunity for applications developers to
profit from those applications.
Why hasn’t it been profitable to develop mobile applications for smartphones until
now? And what are the problems that Android alleviates?
Fragmentation
About 70 million smartphones were sold in 2007, so there are a lot of phones
available to run applications, but each brand has a different application environ-
ment. This is particularly true of Linux-based phones, where each handset vendor
has had to assemble scores of pieces of third-party software to create a viable mobile
phone platform. There is no chance that they would all choose the same compo-
nents to build a mobile smartphone.
3
Java was supposed to help this situation, with J2ME and the wireless Java recom-
mendations (CDC, CLDC, MIDP, JTWI, MSA, etc.) providing a common
applications environment across handsets. Unfortunately, almost every handset
that supports J2ME also support vendor-proprietary extensions that limit the port-
ability of applications.
Proprietary software stacks
Most existing smartphones use proprietary, relatively closed software stacks, such
as Nokia’s Series 60 with the Symbian operating system, or Microsoft’s Windows
Mobile. Modifications to these stacks (adding a driver, for example) have to be
done either by the stack owner or by the handset manufacturer. The stacks are not
open source, so changing anything in the stack is difficult at best. Most Linux-
based phones to date have an open source kernel (as required by the GPL license),
but keep other details of the software stack (application framework, multimedia
framework, applications) proprietary.
Closed networks
Series 60 and Windows Mobile do allow the addition of third-party applications,
but mobile operators often lock the handsets so applications cannot be added. The
operators claim this is needed to preserve the integrity of their mobile networks,
making sure that viruses and spam are not inadvertently installed by end users. It
also suits the operator’s business model, because their mobile phone customers
are confined to the operators’ “walled garden” of applications, both on the phone
and in the network. Android includes an open catalog of applications, Android
Market, that users can download over the air to their Android phones. It also allows
direct loading of applications via USB connection.
Android gives developers a way to develop unique, creative applications and get those
applications in the hands of customers. Hundreds of thousands of Android mobile
phone users are already there, looking for the next clever or useful application, and that
application could be yours.
The Open Handset Alliance
Google and 33 other companies announced the formation of the Open Handset Alli-
ance on November 5, 2007. According to the joint press release from that day:
This alliance shares a common goal of fostering innovation on mobile devices and giving
consumers a far better user experience than much of what is available on today’s mobile
platforms. By providing developers a new level of openness that enables them to work
more collaboratively, Android will accelerate the pace at which new and compelling
mobile services are made available to consumers.
For us as mobile application developers, that means we are free to develop whatever
creative mobile applications we can think of, free to market them (or give them, at our
option) to Android mobile phone owners, and free to profit from that effort any way
4 | Chapter 1: Getting to Know Android
we can. Each member of the Open Handset Alliance has its own reasons for partici-
pating and contributing its intellectual property, and we are free to benefit.
The Open Handset Alliance integrates contributed software and other intellectual
property from its member companies and makes it available to developers through the
open source community. Software is licensed through the Apache V2 license, which
you can see at http://www.apache.org/licenses/LICENSE-2.0.txt. Use of the Apache li-
cense is critical, because it allows handset manufacturers to take Android code, modify
it as necessary, and then either keep it proprietary or release it back to the open source
community, at their option. The original Alliance members include handset manufac-
turers (HTC, LG, Motorola, Samsung), mobile operators (China Mobile Communica-
tions, KDDI, DoCoMo, Sprint/Nextel, T-Mobile, Telecom Italia, Telefonica),
semiconductor companies (Audience, Broadcom, Intel, Marvell, NVidia Qualcomm,
SiRF, Synaptics), software companies (Ascender, eBay, esmertec, Google, LivingImage,
LiveWire, Nuance, Packet Video, SkyPop, SONiVOX), and commercialization com-
panies (Aplix, Noser, TAT, Wind River). The Alliance includes the major partners
needed to deliver a platform for mobile phone applications in all of the major
geographies.
The Alliance releases software through Google’s developer website (http://developer
.android.com). The Android SDK for use by application software developers can be
downloaded directly from that website. (The Android Platform Porting Kit for use by
handset manufacturers who want to port the Android platform to a handset design is
not covered in this book.)
The Android Execution Environment
Applications in Android are a bit different from what you may be used to in the desktop
and server environments. The differences are driven by a few key concepts unique to
the mobile phone environment and unique to Google’s intentions for Android. As you
write applications for an Android handset, you will use these concepts to guide the
design and implementation of the application:
Limited resources
Mobile phones today are very powerful handheld computers, but they are still
limited. The fundamental limitation of a mobile device is battery capacity. Every
clock tick of the processor, every refresh of memory, every backlit pixel on the
user’s screen takes energy from the battery. Battery size is limited, and users don’t
like frequent battery charging. As a result, the computing resources are limited—
clock rates are in the hundreds of MHz, memory is at best a few gigabytes, data
storage is at best a few tens of gigabytes. Throughout this book we will talk about
the mechanisms included in Android to optimize for these limited resources.
The Android Execution Environment | 5
Mobile mashups
InthedesktopInternetworld,mashupsmakeitveryeasytocreatenewapplications
by reusing the data and user interface elements provided by existing applications.
Google Maps is a great example: you can easily create a web-based application that
incorporates maps, satellite imagery, and traffic updates using just a few lines of
JavaScript on your own web page. Android extends that concept to the mobile
phone. In other mobile environments, applications are separate, and with the ex-
ception of browser-based applications, you are expected to code your applications
separately from the other applications that are running on the handset. In Android
you can easily create new applications that incorporate existing applications.
Chapter 13 focuses on these mobile mashups.
Interchangeable applications
In other mobile software environments, applications are coded to access data from
specific data providers. If you need to send an email from a Windows Mobile ap-
plication, for example, you code explicit references to Pocket Outlook’s email in-
terface, and send the email that way. But what if the user wants to use another
email client?
Android incorporates a fundamental mechanism (Intents) that is independent of
specific application implementations. In an Android application, you don’t say you
want to send email through a specific application; instead, you say you want to
send an email through whatever application is available. The operating system
takes care of figuring out what application can send emails, starts that application
if needed, and connects your request so the email can be sent. The user can sub-
stitute different browsers, different MP3 players, or different email clients at will,
and Android adapts automatically.
Components of an Android Application
Your Android applications will be built from four basic component types that are de-
fined by the Android architecture:
Activities
These are comparable to standalone utilities on desktop systems, such as office
applications. Activities are pieces of executable code that come and go in time,
instantiated by either the user or the operating system and running as long as they
are needed. They can interact with the user and request data or services from other
activities or services via queries or Intents (discussed in a moment).
Most of the executable code you write for Android will execute in the context of
an Activity. Activities usually correspond to display screens: each Activity shows
one screen to the user. When it is not actively running, an Activity can be killed by
the operating system to conserve memory.
6 | Chapter 1: Getting to Know Android
Services
These are analogous to services or daemons in desktop and server operating sys-
tems. They are executable pieces of code that usually run in the background from
the time of their instantiation until the mobile handset is shut down. They generally
don’t expose a user interface.
The classic example of a Service is an MP3 player that needs to keep playing queued
files, even while the user has gone on to use other applications. Your application
may need to implement Services to perform background tasks that persist without
a user interface.
Broadcast and Intent Receivers
These respond to requests for service from another application. A Broadcast
Receiver responds to a system-wide announcement of an event. These announce-
ments can come from Android itself (e.g., battery low) or from any program run-
ning on the system. An Activity or Service provides other applications with access
to its functionality by executing an Intent Receiver, a small piece of executable code
that responds to requests for data or services from other activities. The requesting
(client) activity issues an Intent, leaving it up to the Android framework to figure
out which application should receive and act on it.
Intents are one of the key architectural elements in Android that facilitate the cre-
ation of new applications from existing applications (mobile mashups). You will
use Intents in your application to interact with other applications and services that
provide information needed by your application. Intents and Intent Receivers are
covered in more detail in Chapter 13.
Content providers
These are created to share data with other activities or services. A content provider
uses a standard interface in the form of a URI to fulfill requests for data from other
applications that may not even know which content provider they are using. For
example, when an application issues a query for Contact data, it addresses the
query to a URI of the form:
content://contacts/people
The operating system looks to see which applications have registered themselves
as content providers for the given URI, and sends the request to the appropriate
application (starting the application if it is not already running). If there is more
than one content provider registered for the requested URI, the operating system
asks the user which one he wants to use.
An application doesn’t have to use all of the Android components, but a well-written
application will make use of the mechanisms provided, rather than reinventing func-
tionality or hardcoding references to other applications. URIs and Intents together al-
low Android to provide a very flexible user environment. Applications can be easily
added, deleted, and substituted, and the loose coupling of intents and URIs keeps
everything working together.
Components of an Android Application | 7
Android Activity Lifecycle
Android is designed around the unique requirements of mobile applications. In par-
ticular, Android recognizes that resources (memory and battery, for example) are limi-
ted on most mobile devices, and provides mechanisms to conserve those resources. The
mechanisms are evident in the Android Activity Lifecycle, which defines the states or
events that an activity goes through from the time it is created until it finishes running.
The lifecycle is shown diagrammatically in Figure 1-1.
Your activity monitors and reacts to these events by instantiating methods that override
the Activity class methods for each event:
onCreate
Called when your activity is first created. This is the place you normally create your
views, open any persistent datafiles your activity needs to use, and in general ini-
tialize your activity. When calling onCreate, the Android framework is passed a
Bundle object that contains any activity state saved from when the activity ran
before.
Start activity
Usernavigates
backtoactivity
Processiskilled
Activitycomes
toforeground
Activitynolongervisible
NO
YES
Activityinteracts
withuser
Activitybecomes
visible
Activity exits
onCreate()
onStart()
In foreground?
onResume()
onPause()
onStop()
onDestroy()
onRestart()
Figure 1-1. Android Activity lifecycle
8 | Chapter 1: Getting to Know Android
onStart
Called just before your activity becomes visible on the screen. Once onStart com-
pletes, if your activity can become the foreground activity on the screen, control
will transfer to onResume. If the activity cannot become the foreground activity for
some reason, control transfers to the onStop method.
onResume
Called right after onStart if your activity is the foreground activity on the screen.
Atthispointyouractivityisrunningandinteractingwiththeuser.Youarereceiving
keyboard and touch inputs, and the screen is displaying your user interface.
onResume is also called if your activity loses the foreground to another activity, and
that activity eventually exits, popping your activity back to the foreground. This is
where your activity would start (or resume) doing things that are needed to update
the user interface (receiving location updates or running an animation, for
example).
onPause
Called when Android is just about to resume a different activity, giving that activity
the foreground. At this point your activity will no longer have access to the screen,
so you should stop doing things that consume battery and CPU cycles unnecessa-
rily. If you are running an animation, no one is going to be able to see it, so you
might as well suspend it until you get the screen back. Your activity needs to take
advantage of this method to store any state that you will need in case your activity
gains the foreground again—and it is not guaranteed that your activity will resume.
If the mobile device you are running on runs out of memory, there is no virtual
memory on disk to use for expansion, so your activity may have to make way for
a system process that needs memory. Once you exit this method, Android may kill
your activity at any time without returning control to you.
onStop
Called when your activity is no longer visible, either because another activity has
taken the foreground or because your activity is being destroyed.
onDestroy
The last chance for your activity to do any processing before it is destroyed. Nor-
mally you’d get to this point because the activity is done and the framework called
its finish method. But as mentioned earlier, the method might be called because
Android has decided it needs the resources your activity is consuming.
It is important to take advantage of these methods to provide the best user experience
possible. This is the first place in this book we’ve discussed how programming for
mobile devices is different from programming for desktop devices, and there will be
many more such places as you go through later chapters. Your users will appreciate it
if you write your activities with the activity lifecycle in mind, and you will ultimately
benefit.
Android Activity Lifecycle | 9
Android Service Lifecycle
Thelifecycleforaserviceissimilartothatforanactivity,butdifferentinafewimportant
details:
onCreate and onStart differences
Services can be started when a client calls the Context.startService(Intent)
method. If the service isn’t already running, Android starts it and calls its
onCreate method followed by the onStart method. If the service is already running,
its onStart method is invoked again with the new intent. So it’s quite possible and
normal for a service’s onStart method to be called repeatedly in a single run of the
service.
onResume, onPause, and onStop are not needed
Recall that a service generally has no user interface, so there isn’t any need for the
onPause, onResume, or onStop methods. Whenever a service is running, it is always
in the background.
onBind
If a client needs a persistent connection to a service, it can call the Context.bind
Service method. This creates the service if it is not running, and calls onCreate but
not onStart. Instead, the onBind method is called with the client’s intent, and it
returns an IBind object that the client can use to make further calls to the service.
It’s quite normal for a service to have clients starting it and clients bound to it at
the same time.
onDestroy
As with an activity, the onDestroy method is called when the service is about to be
terminated.Androidwillterminateaservicewhentherearenomoreclientsstarting
or bound to it. As with activities, Android may also terminate a service when
memory is getting low. If that happens, Android will attempt to restart the service
when the memory pressure passes, so if your service needs to store persistent in-
formation for that restart, it’s best to do so in the onStart method.
How This Book Fits Together
Android is a sophisticated platform whose parts all work together: drawing and layout,
inter-process communication and data storage, search and location. Introducing it in
pieces is a challenge, but we’ve entertained the conceit of introducing the complexities
of the platform in a linear order.
The platform is also so rich that we can’t hope to show you how to use everything you
want, or even a large subset of its capabilities. We expect you to consult the official
documentation while reading this book and trying the examples. You should also use
other online resources—but be careful about web pages or forum postings that have
10 | Chapter 1: Getting to Know Android
been around a while, because interfaces change. There is also a substantial amount of
misinformation out on the Web; we discovered scads of it while writing the book.
This book is written for experienced developers who want to quickly learn what they
need to know to build Android applications. The book is written with references to an
example application (MJAndroid, discussed in much more detail in the next chapter)
that you can freely download and reuse. The major topics covered in the book include:
New Android concepts
Android builds upon a lot of legacy technology (Java, Linux, and the Internet, just
to name a few), but it also introduces some new concepts needed to enable the
application environment.
Android development environment
We’ll show how to install the free, open source Android development environment
on your own system, and how to use that environment to develop, test, and debug
your own applications. You’ll not only learn the mechanics of using the system,
but also what’s going on behind the scenes, so you’ll have a better understanding
of how the whole system fits together.
Android user interface
The Android user interface elements are similar to things you’ve seen before, but
also different. We’ll show you what the principal elements are, how they’re used,
and what they look like on the screen. We’ll also show you the basic layout types
available for the Android screen.
Intents
Android makes it easy to leverage existing applications through the use of Intents.
For example, if you want to dial a phone number, you don’t have to do all the work
in your application, or even know what applications are available that know how
to dial. You can just ask Android to find you an installed application that knows
how to dial out, and pass it the string of numbers.
Location-based services and mapping
As you’d expect from a Google-sponsored environment, mapping and location are
major features of Android. You’ll see how easy it is to create sophisticated mapping
and location-based applications.
Persistent data
Android includes the SQLite database libraries and tools, which your application
can use to store persistent data. Content providers, which we’ve already intro-
duced, provide data to other applications. Using the libraries can be a little tricky,
but in Chapter 8 we’ll guide you through the creation of a database, and reading,
writing, and deleting data records.
Graphics
Your application has access to 2D and 3D graphics capabilities in Android. Ani-
mation and various advanced effects are also provided. This book will show you
How This Book Fits Together | 11
how to use those libraries so you can build a compelling user interface for your
application.
Communications
Android, even more than most smartphone operating systems, places great em-
phasis on communication—by voice, by text messaging, by instant messaging, and
byInternet.You’llseehowyourapplicationcantakeadvantageofthesecapabilities
so your users can become part of a larger community of data and users.
The next three chapters, Chapters 2 through 4, set you up with a working application,
and will give you a sense of how the files and basic classes fit together. Chapter 5
empowers you to better understand what you’re doing and helps you debug your first
efforts.
The Android toolkit naturally comes with an enormous number of working code ex-
amples in its ApiDemos application. Unfortunately, its very size and sophistication
make it a formidable castle for novices to enter. Chapter 6 guides you through it.
A bit of experience with ApiDemos will convince you that you need some more back-
ground and tutorial help. In Chapter 7, we’ll show you how to sign and publish your
application, which you need to do in order to test it with Google Maps, even before
you’re ready to go public.
Chapter 8 presents tutorials on two data storage systems.
Chapter 9 presents location and mapping, which are key features that draw people to
mobile devices and which you’ll surely want to incorporate into your application.
We then turn to a critical part of any end-user application, graphics, in three
information-packed chapters, Chapters 10 through 12.
Chapter 13 takes another step into the complexity and unique power of Android, by
discussing how applications can offer functionality to other applications. This allows
for powerful mashups, which involve one program standing on the shoulders of other
programs.
Let’s not forget that Android runs on telephones. Chapters 14 and 15 wrap up the book
by showing you how to place and track phone calls.
There’s even more to Android than these features, of course, but programmers of all
stripes will find in this book what they need to create useful and efficient programs for
the Android platform.
12 | Chapter 1: Getting to Know Android
CHAPTER 2
Setting Up Your Android
Development Environment
Setting Up Your Development Environment
Android applications, like most mobile phone applications, are developed in a host-
target development environment. In other words, you develop your application on a
host computer (where resources are abundant) and download it to a target mobile
phone for testing and ultimate use. Applications can be tested and debugged either on
a real Android device or on an emulator. For most developers, using an emulator is
easier for initial development and debugging, followed by final testing on real devices.
To write your own Android mobile phone applications, you’ll first need to collect the
required tools and set up an appropriate development environment on your PC or Mac.
In this chapter we’ll collect the tools you need, download them and install them on
your computer, and write a sample application that will let you get the feel of writing
and running Android applications on an emulator. Linux, Windows, and OS X are all
supported development environments, and we’ll show you how to install the latest set
of tools on each. Then, we’ll show you any configuration you need to do after installing
the tools (setting PATH environment variables and the like), again for each of the three
operating systems. Finally, we’ll write a short little “Hello, Android” application that
demonstrates what needs to be done in order to get a generic application running.
The Android SDK supports several different integrated development environments
(IDEs). For this book we will focus on Eclipse because it is the IDE that is best integrated
with the SDK, and, hey, it’s free. No matter which operating system you are using, you
will need essentially the same set of tools:
• The Eclipse IDE
• Sun’s Java Development Kit (JDK)
• The Android Software Developer’s Kit (SDK)
• The Android Developer Tool (ADT), a special Eclipse plug-in
13
Since you’re probably going to develop on only one of the host operating systems, skip
to the appropriate section that pertains to your selected operating system.
Creating an Android Development Environment
The Android Software Development Kit supports Windows (XP and Vista), Linux
(tested on Ubuntu Dapper Drake, but any recent Linux distro should work), and Mac
OS X (10.4.8 or later, Intel platform only) as host development environments. Instal-
lation of the SDK is substantially the same for any of the operating systems, and most
of this description applies equally to all of them. Where the procedure differs, we will
clearly tell you what to do for each environment:
1. Install JDK: The Android SDK requires JDK version 5 or version 6. If you already
have one of those installed, skip to the next step. In particular, Mac OS X comes
with the JDK version 5 already installed, and many Linux distributions include a
JDK. If the JDK is not installed, go to http://java.sun.com/javase/downloads and
you’ll see a list of Java products to download. You want JDK 6 Update n for your
operating system, where n is 6 at the time of this writing.
Windows (XP and Vista)
• Select the distribution for “Windows Offline Installation, Multi-language.”
• Read, review, and accept Sun’s license for the JDK. (The license has become
very permissive, but if you have a problem with it, alternative free JDKs
exist.)
• Once the download is complete, a dialog box will ask you whether you want
to run the downloaded executable. When you select “Run,” the Windows
Installer will start up and lead you through a dialog to install the JDK on
your PC.
Linux
• Select the distribution for “Linux self-extracting file.”
• Read, review, and accept Sun’s license for the JDK. (The license has become
very permissive, but if you have a problem with it, alternative free JDKs
exist.)
• You will need to download the self-extracting binary to the location in
which you want to install the JDK on your filesystem. If that is a system-
wide directory (such as /usr/local), you will need root access. After the
file is downloaded, make it executable (chmod +x jdk-6version-linux-
i586.bin), and execute it. It will self-extract to create a tree of directories.
Mac OS X
Mac OS X comes with JDK version 5 already loaded.
14 | Chapter 2: Setting Up Your Android Development Environment
2. Install Eclipse: The Android SDK requires Eclipse version 3.3 or later. If you do
not have that version of Eclipse installed yet, you will need to go to http://www
.eclipse.org/downloads to get it, and you might as well get version 3.4 (also known
as Ganymede), since that package includes the required plug-ins mentioned in the
next step. You want the version of the Eclipse IDE labeled “Eclipse IDE for Java
Developers,”andobviouslyyouwanttheversionforyouroperatingsystem.Eclipse
will ask you to select a mirror site, and will then start the download.
Windows (XP or Vista)
The Eclipse download comes as a big ZIP file that you install by extracting the
files to your favorite directory. For this book, we’ll assume that you extracted
to C:/eclipse. Eclipse is now installed, but it will not show up in your Start menu
of applications. You may want to create a Windows shortcut for C:/eclipse/
eclipse.exe and place it on your desktop, in your Start menu, or someplace else
where you can easily find it.
Linux and Mac OS X
Note that, as of this writing, the version of Eclipse installed if you request it
on Ubuntu Hardy Heron is 3.2.2, which does not contain all the plug-ins
needed for Android. The Eclipse download comes as a big tarball (.gz file) that
you install by extracting the files to your favorite directory. For this book, we’ll
assume that you extracted to /usr/lib/eclipse. The executable itself is located in
that directory and is named eclipse.
3. Check for required plug-ins: You can skip this step if you just downloaded a
current version of Eclipse as we recommended. If you are using a preinstalled ver-
sion of Eclipse, you need to make sure you have the Java Development Tool (JDT)
and Web Standard Tools (WST) plug-ins. You can easily check to see whether they
are installed by starting Eclipse and selecting menu options “Windows →
Preferences...”. The list of preferences should include one for “Java” and one for
either “XML” or “Web and XML.” If they aren’t on the list, the easiest thing to do
is reinstall Eclipse, as described in the previous step. Installing “Eclipse IDE for
Java Developers” will automatically get the needed plug-ins.
4. Install Android SDK: This is where you should start if you already have the right
versions of Eclipse and the JDK loaded. The Android SDK is distributed through
Google’s Android site, http://developer.android.com/sdk/1.1_r1/index.html. You
will need to read, review, and accept the terms of the license to proceed. When you
get to the list of downloads, you will see a table of distributions. Select the one for
your operating system (XP and Vista use the same distribution). The package (file)
names include the release number. For example, as this is written, the latest
version of the SDK is 1.1_r1, so the filename for Windows is android-sdk-
windows-1.1_r1.zip.
Setting Up Your Development Environment | 15
For versions 3.3 and later of Eclipse, the Android download site provides directions
about how to install the plug-in through Eclipse’s software updates utility. If you’re
using Eclipse 3.2 or the software update technique doesn’t work for you, download
the SDK from the Android site and install it using instructions in the next
paragraph.
The file you download is another archive file, as with Eclipse: a ZIP file on Win-
dows, a tar-zipped file for Linux and MacOS X. Do the same thing as for Eclipse:
extract the archive file to a directory where you want to install Android, and make
a note of the directory name (you’ll need it in step 6). The extraction will create a
directory tree containing a bunch of subdirectories, including one called tools.
5. Update the environment variables: To make it easier to launch the Android
tools, add the tools directory to your path.
• On Windows XP, click on Start, then right-click on My Computer. In the pop-
up menu, click on Properties. In the resulting System Properties dialog box,
select the Advanced tab. Near the bottom of the Advanced tab is a button, “En-
vironment Variables,” that takes you to an Environment Variables dialog. User
environment variables are listed in the top half of the box, and System environ-
ment variables in the bottom half. Scroll down the list of System environment
variables until you find “Path”; select it, and click the “Edit” button. Now you
will be in an Edit System Variable dialog that allows you to change the envi-
ronment variable “Path.” Add the full path of the tools directory to the end of
the existing Path variable and click “OK.” You should now see the new version
of the variable in the displayed list. Click “OK” and then “OK” again to exit the
dialog boxes.
• On Windows Vista, click on the Microsoft “flag” in the lower left of the desktop,
then right-click on Computer. At the top of the resulting display, just below the
menu bar, click on “System Properties.” In the column on the left of the resulting
box, click on “Advanced system settings.” Vista will warn you with a dialog box
that says “Windows needs your permission to continue”; click “Continue.”
Near the bottom of the System Properties box is a button labeled “Environment
Variables” that takes you to an Environment Variables dialog. User environment
variables are listed in the top half of the box, and System environment variables
in the bottom half. Scroll down the list of System environment variables until
you find “Path”; select it, and click the “Edit” button. Now you will be in an
Edit System Variable dialog that allows you to change the environment variable
“Path.” Add the full path of the tools directory to the end of the existing Path
variable, and click “OK.” You should now see the new version of the variable
in the displayed list. Click “OK” and then “OK” again to exit the dialog boxes.
• On Linux, the PATH environment variable can be defined in your ~/.bashrc
~/.bash_profile file. If you have either of those files, use a text editor such as
gedit, vi, or Emacs to open the file and look for a line that exports the PATH
16 | Chapter 2: Setting Up Your Android Development Environment
variable. If you find such a line, edit it to add the full path of the tools directory
to the path. If there is no such line, you can add a line like this:
export PATH=${PATH}:your_sdk_dir/tools
where you put the full path in place of your_sdk_dir.
• On Mac OS X, look for a file named .bash_profile in your home directory (note
the initial dot in the filename). If there is one, use an editor to open the file and
look for a line that exports the PATH variable. If you find such a line, edit it to
add the full path of the tools directory to the path. If there is no such line, you
can add a line like this:
export PATH=${PATH}:your_sdk_dir/tools
where you put the full path in place of your_sdk_dir.
6. Install the Android plug-in (ADT): Throughout this book, we will make use of
the Android Development Tool plug-in that Google supplies for use in building
Android applications. The plug-in is installed in much the same way as any other
Eclipse plug-in:
a. Start Eclipse, if it’s not already running.
b. From the menu bar, select “Help → Software Updates → Find and Install...”.
c. In the Install/Update dialog, select “Search for new features to install” and
click on “Next.”
d. In the Install dialog, click on “New Remote Site.” A “New Update Site” dialog
pops up. Enter a name for the plug-in (“Android Plugin” will do), and the URL
for updates: https://dl-ssl.google.com/android/eclipse. Click “OK.”
e. The new site should now appear in the list of sites on the Install dialog. Click
“Finish.”
f. In the Search Results dialog, select the checkbox for “Android Plugin →
Developer Tools” and click “Next.”
g. The license agreement for the plug-in appears. Read it, and if you agree, select
“Accept terms of the license agreement” and click “Next.” Click “Finish.”
h. You will get a warning that the plug-in is not signed. Choose to install it anyway
by clicking “Install All.”
i. Restart Eclipse.
j. After Eclipse restarts, you need to tell it where the SDK is located. From the
menu bar, select “Window → Preferences.” In the Preferences dialog, select
“Android” in the left column.
k. Use the “Browse” button to navigate to the place you installed the Android
SDK, and click on “Apply,” then on “OK.”
Setting Up Your Development Environment | 17
Congratulations—you have installed a complete Android development environment
without spending a penny. As you’ll see in this and subsequent chapters, the environ-
ment includes a very sophisticated set of tools to make Android programming easier,
including:
• An Integrated Development Environment based on Eclipse, arguably the premier
IDE for Java development. Eclipse itself brings many valuable development fea-
tures. Google and OHA have taken advantage of Eclipse’s extensibility to provide
features customized for Android, including debugging capabilities that are tuned
to the needs of mobile application developers like you.
• A Java development environment and Dalvik virtual machine that build on Sun’s
JDK foundation to provide a very sophisticated programming environment for
your applications.
• A complete mobile phone emulator that allows you to test your applications with-
out having to download them to a target mobile phone. The emulator includes
features for testing your application under different mobile phone communication
conditions (fading, dropped connections, etc.).
• Test tools, such as Traceview, which allow you to tune your application to take
best advantage of the limited resources available on a mobile phone.
Hello, Android
So enough downloading; let’s write a program. A “Hello World!” program is tradi-
tional, and we will start with something similar to demonstrate what you need to do
to create, build, and test an Android application. We won’t explore much of the An-
droid API for this program—that’s left for the following chapters—but here we’ll get
a taste for the development environment and the steps you go through to create an
application for Android.
Where We’re Going
There isn’t much functionality in this program. We just want to display some text on
the Android emulator window that says “Hello Android!” (see Figure 2-1).
Starting a New Android Application: HelloWorld
Several components are needed to build an Android application. Fortunately, the
Eclipse IDE with the Android plug-in automates a lot of the work needed to create and
maintain these components. We will start by using the IDE to create a project for our
application. Start up Eclipse and select “File → New → Project...” from the menu bar
(be sure to select “Project...”, not “Java Project”). You’ll see a list of project types,
similar to the menu in Figure 2-2.
18 | Chapter 2: Setting Up Your Android Development Environment
Select “Android Project” and click “Next” to get the “New Android Project” dialog box
(Figure 2-3).
We’ll use “HelloWorld” as the name for both the Project and the Application. You
don’t need to change the button or checkbox selections, and we’ll use the package name
com.oreilly.helloworld as shown.
Every Android application has to have at least one Activity (an executable that usually
has a user interface), so let’s say we’re going to include an Activity called Hello
WorldActivity, as shown in the dialog box. Click “Finish,” and the Android Software
Development Kit does a number of things for you, to make your life easier as a
Figure 2-1. “Hello Android” screenshot
Figure 2-2. Eclipse New Project menu
Hello, Android | 19
developer. In Figure 2-4, I’ve expanded the tree in the Package Explorer window to
show some of the files and directories that the Android SDK created.
The Android SDK created a HelloWorld directory in the default Eclipse workspace for
your project. It also created subdirectories for your source files (.src), references to the
Android Library, assets, resources (.res), and a manifest file (AndroidManifest.xml). In
each of the subdirectories it created another level of subdirectories as appropriate. Let’s
take a quick look at them:
Sources (under src)
• Contains a directory structure that corresponds to the package name you gave
for your application: in this case, com.android.helloworld.
• Contains a Java template for the Activity you indicated was in the application
(HelloWorldActivity) and may contain a directory of resource references
(R.java). R.java is actually generated by the Android SDK the first time you
Figure 2-3. Eclipse New Android Project dialog
20 | Chapter 2: Setting Up Your Android Development Environment
compile your application; it contains the Java version of all the resources you
define in the res directory (covered later). We’ll come back to R.java later.
Figure 2-4. Eclipse project listing after creation of the HelloWorld project
Hello, Android | 21
Android Library
This is just what it says. If you like, you can expand the android.jar tree and see
the names of the modules included in the library. This is where your application
will go for Android library references.
assets
Files you want to bundle with your application. We won’t have any for
HelloWorld.
Resources (under res)
• Drawable resources are any images, bitmaps, etc., that you need for your ap-
plication. For HelloWorld, the Android SDK has supplied us with the default
Android icon, and that’s all we’ll need.
• Layout resources tell Android how to arrange items on the screen when the
application runs. These resources are XML files that give you quite a bit of
freedom in laying out the screen for different purposes. For HelloWorld, we’ll
just use the defaults generated by the Android SDK.
• Values are constants, strings, etc., available for use by your application. Keeping
them outside the sources makes it easier to customize the application, such as
adapting it for different languages.
Manifest (AndroidManifest.xml)
This is another XML file that tells the Android build system what it needs to know
to build and package your application so it can be installed on an Android phone
or the emulator. This file has its own specialized editor, which we’ll describe when
we get to more complicated applications.
Writing HelloWorld
In the Eclipse Package Explorer window, double-click on HelloWorldActivity.java.
This opens the source file of that name in the center window, ready for editing:
package com.oreilly.helloworld;
import android.app.Activity;
import android.os.Bundle;
public class HelloWorldActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
22 | Chapter 2: Setting Up Your Android Development Environment
Looking quickly at the template code that the Android SDK has provided for us, we
can note several things:
• The Android SDK has included the package reference we asked for, which is con-
sistent with the directory structure it created.
• It has also created a (collapsed) set of imports for the library references it knows
we need.
• It created a class definition for the Activity we said we wanted (Hello
WorldActivity), including a method called OnCreate.
For the moment, don’t worry about the parameter passed into OnCreate. The
savedInstanceState Bundle is a way of passing data between activities and storing
data between instantiations of the same Activity. We won’t need to use this for
HelloWorld.
• One special line of code has been included in OnCreate:
setContentView (R.layout.main);
Remember that Android uses layouts to define screen layouts on the target, and
that main.xml was the name of the default layout file that the Android SDK created
for us under .res/layout. The R.java file is generated automatically and contains
Java references for each of the resources under .res. You will never need to edit the
R.java file by hand; the Android SDK takes care of it as you add, change, or delete
resources.
Again in the Eclipse Package Explorer window, double-click on main.xml and you will
see the default layout screen in the center window. There are two tabs at the bottom
of the panel that say “Layout” and “main.xml”. Click on the one that says “main.xml”
to bring up the code version:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
Again, let’s look at the key features of this template code:
• Like any other XML file, this one starts with a reference to the XML version and
encoding used.
• LinearLayout is one of the screen layout formats provided by the Android SDK.
There are several others, which can be combined hierarchically to create very
Hello, Android | 23
complex screen layouts. For our purposes, a simple linear layout is fine. More
Layout types are covered later in the book in Chapter 11.
—The LinearLayout definition:
xmlns:android="http://schemas.android.com/apk/res/android"
identifies the XML schema being used.
—This code:
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
defines an orientation, width, and height for the entire scope of the layout.
• TextView describes an area where text can be displayed and edited. It resembles
the text boxes you may have encountered when programming in other graphical
environments.
—Within the TextView definition:
android:layout_width="fill_parent"
android:layout_height="wrap_content"
define a width and height for the TextView box.
—This code:
android:text="@string/hello"
provides some text to display in the TextView. The actual string is defined in a
separate file, res/values/strings.xml. If we open that file (again by clicking on it
in the Package Explorer), we see a specialized string editor added by ADT. If
you select “hello (String)” by clicking on it, you’ll see the current value for that
string. By a stroke of luck, the Android SDK has already included text that is
close to what we wanted to display anyway. Just to show them who’s boss,
change the value of the String hello to say “Hello Android!”, or something else
equally clever.
Save the Project either from the Eclipse File menu (File → Save) or by clicking on the
disk icon in the menu bar.
Believe it or not, we’re done. We don’t have to write a single line of Java to create this
application.
Running HelloWorld
From the Eclipse menu bar, select Run → Run. A “Run As” dialog box will pop up.
Select “Android Application” from the list, which displays the dialog shown in Fig-
ure 2-5.
24 | Chapter 2: Setting Up Your Android Development Environment
A command window will pop up, followed quickly by an emulator window that looks
just like a mobile phone. The emulated phone will then go through its boot sequence,
which takes a few minutes (relax; if anything goes wrong, it will tell you). After a few
minutes you should see the screen shown in Figure 2-6.
Figure 2-6. First try at HelloAndroid
Notice anything different between that screen image and the one we showed in Fig-
ure 2-1? The application prints out “Hello Android!”, or whatever you wrote into the
android:text line earlier, but it also displays the title of the application as “Hello
World”. Let’s change the title to match our creative change to the application text.
In the Package Explorer in the left panel of the Eclipse workbench, reopen the
strings.xml file (the one where we found the String hello before). This will open the file
in the editing window. The intent of this file is to give you a place to define strings that
will be used by your application, without actually embedding them in the Java source
code. The other string that’s defined here is app_name. To make things consistent,
change the definition of app_name to HelloAndroid, as shown in Figure 2-7.
Figure 2-5. Eclipse Application Type selection
Hello, Android | 25
Now when we run the application, we get a screen that looks just like what we set out
to do, as shown previously in Figure 2-1.
Congratulations! You’ve just created your first Android program by doing nothing
more than changing the text in one line of code. There are much greater challenges
ahead.
Figure 2-7. HelloWorld String editing
26 | Chapter 2: Setting Up Your Android Development Environment
CHAPTER 3
Using the Android Development
Environment for Real Applications
MicroJobs: This Book’s Main Sample Application
We want to take a look at applications that are more complex than “Hello, Android,”
and that’s what we’ll do in this chapter. Based on the theory that it’s often easiest to
explain things through an example, we’ll take an in-depth look at a more complex
application, called MicroJobs. Some of the application’s code modules are named
MJAndroid, so we’ll also use that name for the code associated with MicroJobs.
We’ll first take a look at what we want the MicroJobs application to do, then we’ll
quickly get into the code itself. After looking at the structure of the application, we’ll
describe in detail how to build the application and how to get it running on the emu-
lator. Finally, we’ll take a look at some helpful debug hints in case you’re developing
a similar application and it doesn’t start up. The reasons are not always obvious in the
Android environment.
Android and Social Networking
One of the great promises of Android mobile phones is their ability to run applications
that enhance opportunities for social networking between users. This promise echoes
the reality of the Internet. The first generation of Internet applications were about user
access to information, and many of those applications have been very popular. The
second wave of Internet applications has been about connecting users to each other.
Applications such as Facebook, YouTube, and many others enhance our ability to
connect with people of similar interests, and allow the application’s users to provide
some or all of the content that makes the application what it is. Android has the po-
tential to take that concept and add a new dimension: mobility. It’s expected that a
whole new generation of applications will be built for users of mobile devices: social
networkingapplicationsthatareeasytousewhilewalkingdownthestreet;applications
27
that are aware of the user’s location; applications that allow the easy sharing of content-
rich information, such as pictures and videos.
As mentioned in the previous chapter, we are going to study just such an application
as an example of Android application development. The code is available for you to
download from the book’s website (http://www.oreilly.com/catalog/9780596521479),
and is based on an actual entry in the first round of the Android Developer Challenge,
sponsored by Google. The application is an example of a class of applications known
as “friend finders” because that’s the central idea.
In the case of the MicroJobs application, instead of finding friends, the user is trying
to locate a temporary job in the vicinity, so she can work for a few hours and make
some money. The premise is that employers looking for temporary help have entered
available jobs, descriptions, hours, and offered wages in a web-based database that is
accessible from Android mobile phones. Anyone looking for a few hours’ work can use
the MicroJobs application to access that database, look for jobs in the immediate area,
communicate with friends about potential employers and potential jobs, and call the
employer directly if she is interested in the position. For our purposes here, we won’t
create an online service; we’ll just have some canned data on the phone. The application
has a number of features that extend that central idea in ways that are unique to mobile
handsets:
Mapping
The Android mobile phone environment provides very rich support for dynamic,
interactive maps, and we’re going to take full advantage of its capabilities. You’ll
see that with very little code, we’ll be able to show dynamic maps of our local
neighborhood, getting location updates from the internal GPS to automatically
scroll the map as we move. We’ll be able to scroll the map in two directions, zoom
in and out, and even switch to satellite views.
Finding friends and events
A graphic overlay on the map will show us where jobs are placed in the area, and
will allow us to get more information about a job by just touching its symbol on
the map. We will access Android’s Contact Manager application to get address
informationforourfriends(telephonenumbers,instantmessagingaddresses,etc.),
and access the MicroJobs database to get more information about posted jobs.
Instant messaging
When we find friends we want to chat with, we will be able to contact them via
instant messages (IMs), by trading SMS messages with our friends’ mobile phones.
Talking with friends or employers
If IMing is too slow or cumbersome, we’ll be able to easily place a cellular call to
our friends, or call the employer offering a job.
28 | Chapter 3: Using the Android Development Environment for Real Applications
Browsing the Web
Most employers have an associated website that provides more detailed informa-
tion. We’ll be able to select an employer off a list or off the map and quickly zero
in on their website to find out, for example, what the place looks like.
This is a fun application that could easily be developed further into a full-blown service,
but our intent in this book is to show you just how easy it is to develop and combine
these powerful capabilities in your own application. The complete source code for the
application is available to you on the book’s website, and we will refer to it frequently
throughout this book. Although it’s not absolutely required in order to understand the
material in the book, you are strongly encouraged to download the source to your own
computer. That way, you’ll have it readily available for reference, and it will be easy to
copy sections of code and paste them into your own applications as you move on.
Figure 3-1 shows the screen displayed by MJAndroid when you first run it. It’s a map
of your local area, overlaid with a few buttons and pins.
Figure 3-1. MJAndroid opening screenshot
Android and Social Networking | 29
Downloading the MJAndroid Code
The MJAndroid application source code and project files are available from the O’Reilly
website, at http://www.oreilly.com/catalog/9780596521479. To download it to your
development system, use a browser to navigate to the link given, and select “Download
MJAndroid.” Your operating system (Windows, Linux, or OS X) will ask you to con-
firm that you want the download to happen, and ask you where to put the downloaded
files. It doesn’t matter where you put the downloaded, compressed files, but you want
to extract the uncompressed files into the directory that Eclipse uses as your default
workspace, to make it easy to load the project. The default place is a folder called
workspace under the eclipse directory that you created when you installed Eclipse. If
you can’t remember where that is, start Eclipse, go to File → Switch Workspace, and it
will display the location of the current workspace directory. Expand the compressed
files into that directory, and be sure “use directories” is checked in the decompression
dialog, so the correct folders will be created and the files written to them.
To import the MJAndroid project into Eclipse, go to File → Import..., and you’ll see a
Select dialog list of possible import types. Click on “Existing Projects into Workspace,”
and use the Browse button to find the directory where you just expanded MJAndroid.
Eclipse will import the project, and it should appear in the Project Explorer pane.
A Brief Tour of the MJAndroid Code
MJAndroid is a relatively simple application, despite the capabilities it gives its users.
This section will give you an overview of the code and resource modules, tell you where
they are located in the directory structure, and provide a glimpse of what each com-
ponent does. You may want to refer to this section in the future when you’re trying to
find example code for a particular function and want to locate it in the MJAndroid code
tree. MJAndroid uses a directory structure that is derived directly from the standard
Android application directory structure, so this will also serve as a guide to finding code
in other application source trees.
The Project Root Folder (MJAndroid)
If you use Eclipse’s Package Explorer to look at the MJAndroid project, you will see a
set of folders and files. It turns out all of these were originally created by Eclipse and
the Android Development Tool, and similar folders and files are created for any
Android application. Let’s see what they do:
src folder
src is short for Source, and this is where Eclipse and ADT expect to find all of the
Java source files in your application. Almost all of the work you do to create an
Android application is done in this folder and the res folder. In the next section,
we will take a more detailed look at how the src folder is structured for MJAndroid.
30 | Chapter 3: Using the Android Development Environment for Real Applications
Android Library
This is just what it says: a pointer to the library of Android class files that Eclipse
links to in order to provide the Android APIs. You don’t need to do anything with
this entry, but if you ever need to confirm that a particular Android class is (still)
there, this is where you would look.
assets folder
This folder is useful for holding assets that are used by the application: fonts, ex-
ternal JAR files, and so on. For this book and MJAndroid, we don’t have any assets,
so we will not be using the assets folder.
doc folder
Short for documentation, this is where you can put documentation for a project.
For MJAndroid, web pages that describe the Loco project are stored in this folder.
res folder
res is short for resources, and this is where Eclipse and ADT expect to find the
resources for your application. Resources include most of the XML files that define
the layout of your application, any image files (icons, pictures that are used in your
layout, sprites, etc.)—just about everything that isn’t part of a Java source file.
AndroidManifest.xml file
ThisfileiscreatedbyADTwhenyoucreateanewAndroidproject.Astheextension
suggests, it is an XML file, and it contains a wealth of information about your
application: what the activities, services, and intents are, which one starts first,
which permissions your application needs from the operating system (for restricted
functions such as getting location or making a phone call), and a lot of other in-
formation. This file is so important that ADT provides a special editor to maintain
it. It’s just an XML file, so you could always edit it with a text editor, but you will
see later that the specialized editor makes everything a lot easier.
Eclipse also creates two other files and another directory at the same directory level
(the root directory of the MJAndroid project) that are not shown by Package Explorer.
The .classpath file is used by Eclipse to keep track of the location of standard Java classes
and libraries. Eclipse uses the .project file to store information about the project. You
will never need to touch either of these files directly, so Eclipse doesn’t bother you with
them in Package Explorer. The bin directory is where Eclipse puts the compiled class
files for each of your Java source files (the ones in src). You can see all of these files if
you list the directory of the root folder, but you don’t really need to pay any attention
to them, because Eclipse will do it all for you.
The Source Folder (src)
The package name for MJAndroid is com.microjobsinc.mjandroid. Eclipse lays out the
equivalent directory structure, just as it would for any Java project, and shows you the
whole thing when you open src. In addition to these package folders, there is a folder
named for the package that contains all the Java files for the project. These include:
A Brief Tour of the MJAndroid Code | 31
MicroJobs.java
The main source file for the application. It designates the Activity that starts first,
displays the map that is the centerpiece of the application, and calls other Activities
or Services as necessary to implement different features in the user interface.
MicroJobsDatabase.java
A database helper that provides easy access to the local MJAndroid database. This
is where all the employer, user, and job information is stored, using SQLite.
AddJob.java and EditJob.java
Part of the database portion of MJAndroid. These provide screens through which
the user can add or edit job entries in the database.
MicroJobsDetail.java
The Activity that displays all of the detail information about a particular job
opportunity.
MicroJobsEmpDetail.java
The Activity that displays information about an employer, including name, ad-
dress, reputation, email address, phone number, etc.
MicroJobsList.java
The Activity that displays a list of jobs (as opposed to the map view in
MicroJobs.java). It shows a simple list containing Employer and Job entries, and
allows the user to sort the list by either field and call up specifics of the job or
employer by touching the name on the list.
R.java
This file is created automatically by Eclipse and the ADT to contain Java references
for all the resources that are defined in the res folder (see the next section). You
should never have to edit this file by hand, as it is maintained for you as you add
or edit resources. Take a look, though, just to see how resources are defined for
later use in the other Java source files.
The Resource Folder (res)
The res folder contains three folders, and another pointer to the same Android
Manifest.xml file that shows up in the root directory:
drawable
As you might suspect, this contains all the drawable images that MJAndroid will
use: any JPEG or PNG or GIF files or bitmaps.
layout
As with many modern application environments, Android allows you to separate
what is displayed by an Activity from how it is displayed. This directory contains
XML files that describe the “how”; in other words, they are the layout files for each
Activity in the application. When a program runs, Android applies the rules in
these files to create the visible layout, a process known as “inflating.”
32 | Chapter 3: Using the Android Development Environment for Real Applications
values
Good programming practice calls for the separation of data that does not directly
affect the operation of an application, making it a lot easier to do things like trans-
lation to foreign languages, theming, etc. We aren’t going to be super strict about
this in MJAndroid, but we will at least put all of the obvious user-visible text into
a file called strings.xml. You’ll see how easy it is to retrieve these for use in the
actual Android Activity source code.
First Steps: Building and Running the MicroJobs Application
So now that we know a bit about which files are located in which folders, what happens
when we ask Android to run the MJAndroid application? And for that matter, how do
we ask Android to run the application? Let’s take a closer look at the Android SDK
environment and the views and commands available to us for running and debugging
any application.
A Very Short Tour of the Android SDK/Eclipse IDE
The Android SDK provides three “perspectives” for working with Android projects and
applications. If you’re new to Eclipse, a perspective is a collection of Eclipse views that
provides a particular viewpoint of an application. Eclipse and the Android SDK have
preassembled sets of views that developers have found useful, and you can switch be-
tween those views, either by selecting one from the Window menu or by using the icons
in the upper-right corner of the Eclipse window. You are also free to customize the
perspectives, but in this book we will assume you use the standard ones provided:
Java
This is the default perspective, launched by Eclipse when you first say that you
want to view the workspace. It includes:
Package Explorer
Used for viewing folders and selecting files
Source Editor
Used for editing Java and XML source files
Tabbed Views
Contains a set of useful views, accessed by tabs:
• Problems, which lists errors that Eclipse and the Android SDK find in the
application
• Javadoc, which extracts and displays Javadoc documentation from the
application
• Declaration, which makes it easy to find the declaration for any variable in
the code
First Steps: Building and Running the MicroJobs Application | 33
• Console, which shows the console terminal output from either the emulator
or the Android phone
• Search, which is used to search for results
• Progress, which displays progress as an application is launched and runs
Debug
This perspective is primarily for debugging the application, obviously. If you select
Debug from the Run menu, Eclipse switches automatically to this perspective,
providing you with views that are useful for debugging:
Debug
A view of the application call stack, showing you how you got to the current
debug point
Source View
This shows you the current source location in the running (or stopped)
application
Console and Tasks Views
This contains the console terminal (as in the Java perspective), and a window
where development tasks can be recorded and tracked
Variables, Breakpoints, and Expressions
This is where you can view current variable values, view breakpoints, and
evaluate expressions while debugging
Outline
This shows you an outline of the current activity being executed: the classes
declared, and the instances and methods defined
DDMS
This perspective, which stands for Dalvik Debug Monitor Service, is unique to
Android. It provides Android-specific debug information, including:
Devices
This shows you what devices (emulated or hardware) are available to run your
applications.
Emulator Control
This is where you can adjust parameters that define how the telephony and
location emulators work. When running on the emulator, we’ll use this to
manually send location updates to the location provider.
LogCat
This is a view of the very powerful logging facility available under Android,
which allows you to see everything going on in the target system, and to filter
out the information you really care about.
34 | Chapter 3: Using the Android Development Environment for Real Applications
Other documents randomly have
different content
Ten minutes later they parted the foliage and came abruptly
within full view of the village. All uttered cries of consternation at the
furiousness of the battle that was taking place between the two
savage tribes.
S
CHAPTER XXVI
The Terrible Battle
PEARS and arrows and darts flew thick and fast, striking down
many a man on both sides. Fierce cries filled the atmosphere and
made the Americans shudder. Here in the untamed wilds of Brazil
was taking place as terrible a battle as the world had ever known.
Savages—wild, hostile Indians—were the participants, and no people
anywhere were more terrible when excited to insane fury.
For some time none of the explorers spoke. They were too
captivated by the scene. But at last Mr. Holton turned thought into
action.
“Get your rifles in readiness,” he commanded. “It’s up to us to
drive this tribe away. The chief’s men seem unable to do it.
“Now we’re all good shots,” he went on. “Suppose we fire a
volley of bullets and see if we can’t make them leave without
bloodshed. If we can’t, we’ll have to shoot to kill. Come on, now.”
The whites raised their rifles, and, one at a time, pulled the
triggers. Five shots rang out, much to the surprise of the savages.
But as no damage seemed to be done by the strange reports, the
Indians regained confidence and sent spears and arrows in the
explorers’ direction. As a result, one of the crew went down,
wounded in the thigh.
“We’ll have to shoot to kill,” said Mr. Lewis at once.
He raised his rifle and, taking careful aim, fired at the nearest
native, who went down instantly.
Mr. Lewis’s shot was followed by those of the other whites, and
at once panic ensued among the invading savages.
After only a thin defense, they took to their heels with cries of
fright and bewilderment, leaving their dead and wounded behind.
“Guess that drove them off all right,” said Bob with a grim smile.
“Come on, let’s——But wait! Look! The chief’s tribe is worshiping us.”
Bob was right. The Indians had fallen to their knees, waving
their arms and muttering words that were not understood even by
Professor Bigelow.
Even the chief, accustomed as he was to the rifles and the
whites’ power to bring down animals, bowed his head in awe at his
tribe’s deliverance.
It was a most embarrassing situation, and for a time the
explorers were at a loss to know what to do next.
Finally Professor Bigelow walked forward and uttered kind
words, at the same time raising hands for the savages to rise to their
feet.
He succeeded well. At once they got to their feet and resumed
something of their usual attitude, although they were not quite
convinced that these people were not gods.
The chief went forward and conversed with them so rapidly that
Professor Bigelow could not keep up.
“He’s telling of his visit to our camp,” the scientist said. “He
perhaps considers it a much-prized experience.”
As soon as the chief had finished, the Indians jabbered
excitedly, eager to get all the details. Occasionally they would look at
the whites as if they considered them super-beings.
“They can’t get over the thought that we have higher powers
than they have,” mused Bob. “But maybe,” he hesitated, his
thoughts going back to the terrible trophy chamber of dried human
heads that was one of the tribe’s prized possessions, “it will be just
as well to let them go on thinking that way. It would be hard to say
when they might turn against us if they thought we were ordinary
persons.”
“Turn against us?” demanded Mr. Lewis, rather surprised. “What
makes you think they would do that? They seem all right.”
“Don’t know that they would,” Bob replied, exchanging meaning
glances with Joe. “Still it’s wise to be on the safe side.”
It was evident that Bob’s significant statement had the men
highly puzzled. Finally Professor Bigelow demanded an explanation.
“There’s nothing to it—except that these people are
headhunters,” said Joe. “If you don’t believe it just take a look at the
place where they keep the heads. And say! They’ve killed a couple of
white men, too.”
Astonished gasps came from Mr. Holton and Mr. Lewis, but not
from Professor Bigelow. Anthropologist as he was, he had suspected
this from the start. Very few savage tribes in the wilds of Brazil did
not have that custom.
Suddenly a groan made all turn about, to see that the Indian of
the crew who had been wounded by a spear had regained
consciousness. His side apparently pained severely, for on his face
was a look of agony.
Mr. Holton got to work at once.
“Ask the chief if we can have some water,” he said to Professor
Bigelow. “Bob, suppose you run down to the boats and bring a box
of antiseptic. Go as fast as you can. Meanwhile we’ll be taking care
of others that were wounded.”
Bob grabbed a rifle and dashed off down the path for the
stream.
He reached the boats in record time and hurriedly got out a box
of first-aid materials. Then he made his way back to the village.
But he had gone only a few yards when a fluttering noise
caused him to look up.
At once his jaw dropped in astonishment, and a look of surprise
and wonder came on his face.
Android Application Development Programming With The Google Sdk 1st Edition Rick Rogers
T
CHAPTER XXVII
Human Heads Still Dripping!
HE sight that Bob beheld was one that few hunters and
scientists have the opportunity of seeing. Strange sights were
common enough in all little-known lands, but this was indeed a
wonder of wonders.
Not thirty feet in the air a bird resembling an eagle was carrying
a half-grown tapir with apparently perfect ease, although the tapir
was three times heavier than itself. The tapir was very much alive,
as indicated by its writhing movements, but these availed it nothing.
It might as well have been caught in an iron vise.
For several minutes Bob stared spellbound, taken completely
aback.
Finally he called himself to action and raised his rifle.
“Dad and Mr. Lewis would no doubt welcome the addition of
such an unusual specimen as this eagle,” he thought and then pulled
the trigger.
The report of the gun was immediately followed by the dropping
of the bird and its prey. It fluttered about for a moment and then lay
still. The tapir had been killed instantly by the fall.
Much to Bob’s surprise, the bird could be lifted easily, and he
hastened on to the Indian settlement, confident that the naturalists
would nearly throw a fit over the strange eagle.
And he thought right. Mr. Holton and Mr. Lewis exclaimed in
delight and surprise when they caught sight of Bob and the strange
creature he was carrying.
“Where did you ever find it?” asked Mr. Lewis, and Bob was
forced to tell of the entire experience.
“The great hairy eagle,” pronounced Mr. Holton, when the youth
had finished. “I thought they were confined to the jungles of Guiana,
didn’t you, Ben?” he asked of Joe’s father.
“Yes,” was the reply. “Never heard of their being found here.
Such is unusual indeed. The claws are the most powerful of any
known bird.”
But there was little time for further examining the specimen, for
the wounded Indians needed treatment. The member of the crew
was looked after first, and then they turned to the chief’s men, many
of whom were seriously wounded. As for those who had been struck
by poisoned arrows, treatment was unnecessary, for death had set
in long before.
The better part of an hour was spent in giving first-aid to the
unfortunate savages, and in the end they felt that a large number of
lives had been saved by their actions.
“But don’t think that the natives have no cure for human ills,”
said Professor Bigelow. “The chances are that they know of many
remedies that surpass those of civilization in curing properties.”
When the task was completed, the Indians invited the whites to
come in the main hut and participate in a feast in honor of their
ability to drive off the hostile invaders. The invitation was accepted
at once, for the explorers were all very hungry.
“Wonder what they’ll give us to eat?” asked Joe, as they went
into the thatched hut.
“Perhaps it’ll be better not to know,” Bob grinned.
Whatever it was, however, it tasted good, and they ate heartily
of everything.
“Now I’m going to get in touch with the chief, whose name I
recently learned is Reemikuk,” announced Professor Bigelow. “But
first, however, I must have my typewriter. That means a trip to the
boats.”
“And while he’s doing that, Mr. Lewis and I can have a look
about the village,” Bob’s father said. “Perhaps you boys can show us
the places and things of interest. Will you do it?”
“To be sure we will,” returned Joe. “But first,” he said with a
grim smile, “you must prepare yourselves to see things that are
unpleasant.”
“What do you mean?” his father demanded.
For answer the youths led the way to the trophy house and its
hideous contents.
Impulsively the naturalists shrank back in disgust at the scene.
Never had they laid eyes on such a place of horror before.
“To think,” muttered Mr. Lewis, “that even these wild people
could do such hideous things!”
But despite the gruesomeness of the place they spent several
minutes there, unable to tear themselves away from its terrible
fascination.
At last Mr. Holton made for the outside.
“Now for something more pleasant,” he said. “What is there,
boys?”
“Plenty,” answered Joe. “There are games and baskets and
carvings and....”
All the remainder of that day was spent in examining the many
articles of interest made by the simple savages.
When at last they went back to the hut that was to be theirs
during their stay at the village, they found the professor in earnest
conversation with the chief and a witch doctor.
The Indians were talking slowly, so that the scientist could pick
up every word. He glanced up at the other whites only for a
moment, so deeply engrossed was he in what the savages were
telling him.
“He seems to be enjoying himself immensely,” observed Joe
aside to his chum.
“No doubt about it,” Bob replied. “And look how the Indians are
regarding the typewriter. Probably think it’s another of the whites’
magics.”
Professor Bigelow was enjoying himself. Every strange custom
of the savages appealed to him as a wonderful item to put in the
book he intended to write about the primitive inhabitants of these
wild regions. But two days later something happened that, although
considered a very interesting custom by the anthropologist, was not
to the liking of the other whites. A band of twenty-five warriors had
gone into the upper reaches of the river several days before, and
now they returned laden with—human heads!
“Ugh! Me for the hut,” said Bob, a sickly feeling creeping over
him as he viewed the ghastly trophies.
And the others, with the exception of Professor Bigelow, felt the
same way. The anthropologist, however, seemed to be thoroughly
enjoying the terrible scene.
“How thrilling a custom!” he said to his friends that night, as
they prepared to retire.
For answer the others only groaned.
But if the explorers thought the mere carrying in of human
heads was gruesome, they were to witness something still more
terrible before a week would pass.
“B
CHAPTER XXVIII
The Forced Get-away
OB!”
“Joe!”
“Did you see it?”
“Yes. Human bones! These savages are cannibals!”
It was night—a dark, lowering night. The moon was nowhere in
sight. Not a star twinkled down from the heavy jungle sky. Huge,
roaring fires blazed in front of the chief’s large hut, while about them
danced scores of painted savages, shouting and screaming and
gesticulating.
It was a scene wild enough to strike terror to the heart of
anyone. Bob and Joe gazed fearfully into the raging mob, wondering
if the lives of them and their companions would be taken for the
feast.
The boys moved over to their elders, who were standing at the
other side of their thatched dwelling.
“Cannibals!” Professor Bigelow was muttering. He had seen too.
Mr. Holton and Mr. Lewis nodded, on their faces a grave
expression. They were so taken aback as to be almost speechless.
“I think perhaps we had better get away from here,” said the
professor, who, although deeply attentive to scientific work, knew
when he was in a dangerous situation. “I know enough of the ways
of primitive people to surmise what they’ll probably do to us if we
stay. Their appetites for human flesh will be so stimulated that they
will no doubt kill us also. Lucky that this happened as late as it did. I
wouldn’t have wanted to leave so soon if I had not secured about all
the information there is to be obtained about them.”
Just before leaving, Bob and Joe got out their cameras and took
motion pictures of the gruesome feast, and in the end they were
almost convinced that nothing of this kind had ever been shown on
the silver screen.
With the aid of flashlights, whose beams, by the way, were
concealed from the savages, the explorers had gathered their
belongings together and were now ready to leave for the boats. Of
course it would be perilous traveling at night through the jungle, but
the chance had to be taken.
At that moment an Indian entered their hut, glanced about, and
then started to call to the others.
Displaying a quickness remarkable for his size and weight, Mr.
Holton launched himself full force at the fellow, sending him to the
ground unconscious.
“Now let’s get away—quick!” he said. “There’s no telling when
the whole tribe will be in here after us.”
As quietly as possible, the explorers and their Indian crew
dashed away down the trail for the stream, never looking back, but
fearing that they would hear the screams of the cannibals at any
moment.
The flashlights rendered traveling easy, and as they had been
over the trail many times, they reached the boats in record time.
Their possessions were piled inside. Then they climbed hastily in
and were paddled swiftly away.
It was not until they had reached the main stream that they felt
safe. Then they turned the boats downstream on the journey back
to the coast.
“It isn’t wise to tax good fortune too much,” said Mr. Lewis, as
the narrow stream faded in the distance. “We came up here for two
definite purposes, and we’ve accomplished them both. First,
Professor Bigelow has made a rather extensive study of little-known
Indians, and second, Mr. Holton and I have collected hundreds of
specimens for the museum. You boys have met with success in
taking moving pictures, also. Now that our work is finished, we’d
better get to the Purús at once.”
However, “at once” was a bit too hastily, for there were
dangerous rapids that had to be portaged, totally unknown animals
that diverted the naturalists’ attention, and a hundred and one
reasons for making slow progress, even downstream. But at last
they sighted the Purús in the distance.
“Now to hunt up Senhor del Pereo, the man who fitted us out
with our boats and crew,” said Mr. Holton.
They found that individual in his house at the edge of the little
town that rested between the two rivers.
He was more than glad to see the explorers back after such a
long, perilous journey, and insisted that they remain at his house
overnight, or until a boat could be found that would take them to
the Amazon. The explorers accepted the invitation at once, glad of
the chance to partake of the comforts of civilization after those long
weeks into the unknown.
The next day they were fortunate in getting passage on a boat
bound for Manáos. It was a small steamer, scheduled to reach its
destination in less than five days.
At Manáos the explorers had another streak of good luck,
finding a large liner that would take them straight to New York.
Down the mighty Amazon they steamed, at last coming into the
port at Pará for a short stay.
After a walk about town, the Americans again boarded the
vessel for the trip to New York.
It was an ideal evening as they steamed majestically out of the
busy harbor and turned toward the United States.
“Do you know, Joe, old boy,” remarked Bob, as they sat with
their elders on deck in the light of the full moon, “the farther away
we get from the region we explored the more I prize our
experience.”
Joe nodded.
“It was great,” he agreed. “And just think. We were lost—lost in
the wilds of Brazil.”
Transcriber's Notes
The four books in this series have been transcribed in
the same manner. This means that in some books, table of
contents and or/list of series names have been added.
Except in cases of obvious typographical errors, archaic
and inconsistent spelling has been retained.
*** END OF THE PROJECT GUTENBERG EBOOK LOST IN THE
WILDS OF BRAZIL ***
Updated editions will replace the previous one—the old editions will
be renamed.
Creating the works from print editions not protected by U.S.
copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.
START: FULL LICENSE
THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK
To protect the Project Gutenberg™ mission of promoting the free
distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.
Section 1. General Terms of Use and
Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.
1.B. “Project Gutenberg” is a registered trademark. It may only be
used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
1.E. Unless you have removed all references to Project Gutenberg:
1.E.1. The following sentence, with active links to, or other
immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
1.E.2. If an individual Project Gutenberg™ electronic work is derived
from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.
1.E.3. If an individual Project Gutenberg™ electronic work is posted
with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.
1.E.4. Do not unlink or detach or remove the full Project
Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.
1.E.5. Do not copy, display, perform, distribute or redistribute this
electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.
1.E.7. Do not charge a fee for access to, viewing, displaying,
performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.
1.E.8. You may charge a reasonable fee for copies of or providing
access to or distributing Project Gutenberg™ electronic works
provided that:
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You provide a full refund of any money paid by a user who
notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.
• You provide, in accordance with paragraph 1.F.3, a full refund of
any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™
electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.
1.F.
1.F.1. Project Gutenberg volunteers and employees expend
considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.
1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for
the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.
1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you
discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.
1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
1.F.5. Some states do not allow disclaimers of certain implied
warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.
1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,
the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.
Section 2. Information about the Mission
of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.
Volunteers and financial support to provide volunteers with the
assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.
Section 3. Information about the Project
Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.
The Foundation’s business office is located at 809 North 1500 West,
Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.
The Foundation is committed to complying with the laws regulating
charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.
While we cannot and do not solicit contributions from states where
we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.
International donations are gratefully accepted, but we cannot make
any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Section 5. General Information About
Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
This website includes information about Project Gutenberg™,
including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
Programming Android Zigurd Mednieks Laird Dornin Blake Meike
PDF
Learning Android 1st Edition Marko Gargenta
PDF
Learning Android 1st Edition Marko Gargenta
PDF
Blake Nakamura Masumi Programming Android 2nd Edition Mednieks Zigurd
PDF
Developing Android Applications with Adobe AIR 1st Edition Véronique Brossier
PDF
Developing Android Applications with Adobe AIR 1st Edition Véronique Brossier
PDF
Learning the iPhone SDK for JavaScript Programmers Create Native Apps with Ob...
PDF
Mobile App Development With Ionic Crossplatform Apps With Ionic Angular And C...
Programming Android Zigurd Mednieks Laird Dornin Blake Meike
Learning Android 1st Edition Marko Gargenta
Learning Android 1st Edition Marko Gargenta
Blake Nakamura Masumi Programming Android 2nd Edition Mednieks Zigurd
Developing Android Applications with Adobe AIR 1st Edition Véronique Brossier
Developing Android Applications with Adobe AIR 1st Edition Véronique Brossier
Learning the iPhone SDK for JavaScript Programmers Create Native Apps with Ob...
Mobile App Development With Ionic Crossplatform Apps With Ionic Angular And C...

Similar to Android Application Development Programming With The Google Sdk 1st Edition Rick Rogers (20)

PDF
Mobile app development with Ionic cross platform apps with Ionic Angular and ...
PDF
Programming iOS 4 Fundamentals of iPhone iPad and iPod Touch Development 1st ...
PDF
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
PDF
Learning the iOS 4 SDK for JavaScript Programmers Create Native Apps with Obj...
PDF
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
PDF
Programming Android Java Programming for the New Generation of Mobile Devices...
PDF
Programming iOS 4 Fundamentals of iPhone iPad and iPod Touch Development 1st ...
PDF
Android Cookbook 1st Edition Ian F. Darwin
PDF
Programming Android Java Programming for the New Generation of Mobile Devices...
PDF
Android Cookbook Problems And Solutions For Android Developers Darwin
PDF
Learning React Native Building Native Mobile Apps With Javascript 2nd Edition...
PDF
Programming Android Java Programming for the New Generation of Mobile Devices...
PDF
Programming Android Java Programming for the New Generation of Mobile Devices...
PDF
Code In The Cloud 1st Edition Mark C Chucarroll
PDF
Programming Flex 2 Chafic Kazoun Joey Lott
PDF
Beginning android application development wei meng lee
PDF
Download full ebook of Learning Node Shelley Powers instant download pdf
PDF
Exam Ref 70485 Advanced Windows Store App Development Using C Roberto Brunetti
PDF
Android Cookbook Early Release Ian F Darwin
PDF
High Performance Android Apps Improve Ratings with Speed Optimizations and Te...
Mobile app development with Ionic cross platform apps with Ionic Angular and ...
Programming iOS 4 Fundamentals of iPhone iPad and iPod Touch Development 1st ...
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
Learning the iOS 4 SDK for JavaScript Programmers Create Native Apps with Obj...
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
Programming Android Java Programming for the New Generation of Mobile Devices...
Programming iOS 4 Fundamentals of iPhone iPad and iPod Touch Development 1st ...
Android Cookbook 1st Edition Ian F. Darwin
Programming Android Java Programming for the New Generation of Mobile Devices...
Android Cookbook Problems And Solutions For Android Developers Darwin
Learning React Native Building Native Mobile Apps With Javascript 2nd Edition...
Programming Android Java Programming for the New Generation of Mobile Devices...
Programming Android Java Programming for the New Generation of Mobile Devices...
Code In The Cloud 1st Edition Mark C Chucarroll
Programming Flex 2 Chafic Kazoun Joey Lott
Beginning android application development wei meng lee
Download full ebook of Learning Node Shelley Powers instant download pdf
Exam Ref 70485 Advanced Windows Store App Development Using C Roberto Brunetti
Android Cookbook Early Release Ian F Darwin
High Performance Android Apps Improve Ratings with Speed Optimizations and Te...
Ad

Recently uploaded (20)

PPTX
Cell Types and Its function , kingdom of life
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Classroom Observation Tools for Teachers
PDF
RMMM.pdf make it easy to upload and study
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Lesson notes of climatology university.
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Cell Structure & Organelles in detailed.
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Presentation on HIE in infants and its manifestations
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Cell Types and Its function , kingdom of life
GDM (1) (1).pptx small presentation for students
Classroom Observation Tools for Teachers
RMMM.pdf make it easy to upload and study
human mycosis Human fungal infections are called human mycosis..pptx
Lesson notes of climatology university.
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
O7-L3 Supply Chain Operations - ICLT Program
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
202450812 BayCHI UCSC-SV 20250812 v17.pptx
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Cell Structure & Organelles in detailed.
O5-L3 Freight Transport Ops (International) V1.pdf
Presentation on HIE in infants and its manifestations
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Chinmaya Tiranga quiz Grand Finale.pdf
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Ad

Android Application Development Programming With The Google Sdk 1st Edition Rick Rogers

  • 1. Android Application Development Programming With The Google Sdk 1st Edition Rick Rogers download https://ebookbell.com/product/android-application-development- programming-with-the-google-sdk-1st-edition-rick-rogers-2483424 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Android Programming Android Application Development Rk Raji https://ebookbell.com/product/android-programming-android-application- development-rk-raji-5903262 Android Programming Android Application Development Raji Rk https://ebookbell.com/product/android-programming-android-application- development-raji-rk-6766916 Android Wearable Programming Expand On Your Android Development Capabilities By Building Applications For Android Wear 1st Edition Steven F Daniel https://ebookbell.com/product/android-wearable-programming-expand-on- your-android-development-capabilities-by-building-applications-for- android-wear-1st-edition-steven-f-daniel-23129878 Android Application Development Cookbook Second Edition 2016 Second Edition Rick Boyer https://ebookbell.com/product/android-application-development- cookbook-second-edition-2016-second-edition-rick-boyer-57645008
  • 3. Android Application Development For Dummies 2nd Edition Michael Burton Donn Felker https://ebookbell.com/product/android-application-development-for- dummies-2nd-edition-michael-burton-donn-felker-57723130 Android Application Development For Dummies Donn Felker https://ebookbell.com/product/android-application-development-for- dummies-donn-felker-25565548 Android Application Development Course Code And401 Version 7 4th Edition Coll https://ebookbell.com/product/android-application-development-course- code-and401-version-7-4th-edition-coll-36894592 Android Application Development Cookbook 93 Recipes For Building Winning Apps 1st Edition Weimeng Lee https://ebookbell.com/product/android-application-development- cookbook-93-recipes-for-building-winning-apps-1st-edition-weimeng- lee-4072054 Android Application Development For Java Programmers James Sheusi https://ebookbell.com/product/android-application-development-for- java-programmers-james-sheusi-4144872
  • 7. Android Application Development Rick Rogers, John Lombardo, Zigurd Mednieks, and Blake Meike Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo
  • 8. Android Application Development by Rick Rogers, John Lombardo, Zigurd Mednieks, and Blake Meike Copyright © 2009 Rick Rogers, John Lombardo, Zigurd Mednieks, and Blake Meike. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://mysafaribooksonline.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected]. Editor: Andy Oram Production Editor: Sumita Mukherji Copyeditor: Genevieve d’Entremont Proofreader: Sada Preisch Indexer: Joe Wizda Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: May 2009: First Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Android Application Development, the image of an Eastern quoll and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein. TM This book uses RepKover™, a durable and flexible lay-flat binding. ISBN: 978-0-596-52147-9 [M] 1241533714
  • 9. Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Part I. Development Kit Walk-Through 1. Getting to Know Android . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Why Android? 3 The Open Handset Alliance 4 The Android Execution Environment 5 Components of an Android Application 6 Android Activity Lifecycle 8 Android Service Lifecycle 10 How This Book Fits Together 10 2. Setting Up Your Android Development Environment . . . . . . . . . . . . . . . . . . . . . . . . . 13 Setting Up Your Development Environment 13 Creating an Android Development Environment 14 Hello, Android 18 Where We’re Going 18 Starting a New Android Application: HelloWorld 18 Writing HelloWorld 22 Running HelloWorld 24 3. Using the Android Development Environment for Real Applications . . . . . . . . . . . . 27 MicroJobs: This Book’s Main Sample Application 27 Android and Social Networking 27 Downloading the MJAndroid Code 30 A Brief Tour of the MJAndroid Code 30 The Project Root Folder (MJAndroid) 30 The Source Folder (src) 31 The Resource Folder (res) 32 First Steps: Building and Running the MicroJobs Application 33 iii
  • 10. A Very Short Tour of the Android SDK/Eclipse IDE 33 Loading and Starting the Application 35 Digging a Little Deeper: What Can Go Wrong? 36 Running an Application on the T-Mobile Phone 39 Summary 41 4. Under the Covers: Startup Code and Resources in the MJAndroid Application . . . . 43 Initialization Parameters in AndroidManifest.xml 44 Initialization in MicroJobs.java 46 More Initialization of MicroJobs.java 52 Summary 56 5. Debugging Android Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 The Tools 57 Eclipse Java Editor 58 Java Errors 58 The Debugger 64 Logcat 67 Android Debug Bridge (adb) 71 DDMS: Dalvik Debug Monitor Service 74 Traceview 75 Summary 80 6. The ApiDemos Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Application Setup in the Manifest File 81 Finding the Source to an Interesting Example 83 Custom Title Demo 83 Linkify Demo 84 Adding Your Own Examples to ApiDemos 84 7. Signing and Publishing Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Test Your Application 88 Attach an End User License Agreement If Desired 89 Create and Attach an Icon and Label 89 Clean Up for Release 90 Version Your Application 90 Obtaining a Signing Certificate and API Key 90 Getting a Signing Certificate for an Application You Are Going to Ship 91 Getting a Signing Certificate While Debugging 93 Signing Your Application 95 Retesting Your Application 96 Publishing on Android Market 96 Signing Up As an Android Developer 96 iv | Table of Contents
  • 11. Uploading Your Application 96 Part II. Programming Topics 8. Persistent Data Storage: SQLite Databases and Content Providers . . . . . . . . . . . . . 101 Databases 101 Basic Structure of the MicroJobsDatabase Class 102 Reading Data from the Database 107 Modifying the Database 110 Content Providers 114 Introducing NotePad 116 Content Providers 118 Consuming a Content Provider 129 9. Location and Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 Location-Based Services 137 Mapping 139 The Google Maps Activity 139 The MapView and MapActivity 140 Working with MapViews 140 MapView and MyLocationOverlay Initialization 141 Pausing and Resuming a MapActivity 144 Controlling the Map with Menu Buttons 145 Controlling the Map with the KeyPad 147 Location Without Maps 148 The Manifest and Layout Files 148 Connecting to a Location Provider and Getting Location Updates 149 Updating the Emulated Location 152 10. Building a View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 Android GUI Architecture 157 The Model 157 The View 158 The Controller 159 Putting It Together 159 Assembling a Graphical Interface 161 Wiring Up the Controller 166 Listening to the Model 168 Listening for Touch Events 173 Listening for Key Events 176 Alternative Ways to Handle Events 177 Advanced Wiring: Focus and Threading 179 Table of Contents | v
  • 12. The Menu 183 11. A Widget Bestiary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 Android Views 188 TextView and EditText 188 Button and ImageButton 191 Adapters and AdapterViews 192 CheckBoxes, RadioButtons, and Spinners 193 ViewGroups 198 Gallery and GridView 198 ListView and ListActivity 202 ScrollView 204 TabHost 205 Layouts 208 Frame Layout 209 LinearLayout 209 TableLayout 213 AbsoluteLayout 215 RelativeLayout 216 12. Drawing 2D and 3D Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 Rolling Your Own Widgets 221 Layout 222 Canvas Drawing 226 Drawables 237 Bitmaps 242 Bling 243 Shadows, Gradients, and Filters 246 Animation 247 OpenGL Graphics 252 13. Inter-Process Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 Intents: Simple, Low-Overhead IPC 258 Intent Objects Used in Inter-Process Communication 258 Activity Objects and Navigating the User Interface Hierarchy 259 Example: An Intent to Pick How We Say “Hello World” 259 Getting a Result via Inter-Process Communication 262 Remote Methods and AIDL 265 Android Interface Definition Language 266 Classes Underlying AIDL-Generated Interfaces 270 Publishing an Interface 273 Android IPC Compared with Java Native Interface (JNI) 274 What Binder Doesn’t Do 275 vi | Table of Contents
  • 13. Binder and Linux 275 14. Simple Phone Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 Quick and Easy Phone Calls 277 Creating an Example Application to Run the call Method 278 Embedding the Code Snippet in a Simple Application 279 Exploring the Phone Code Through the Debugger 280 Creating an Instance of an Intent 282 Adding Data to an Instance of an Intent 283 Initiating a Phone Call 284 Exception Handling 284 Android Application-Level Modularity and Telephony 285 15. Telephony State Information and Android Telephony Classes . . . . . . . . . . . . . . . . 287 Operations Offered by the android.telephony Package 287 Package Summary 288 Limitations on What Applications Can Do with the Phone 288 Example: Determining the State of a Call 289 Android Telephony Internals 291 Inter-Process Communication and AIDL in the android.internal.telephony Package 291 The android.internal.telephony Package 292 The android.internal.telephony.gsm Package 295 Exploring Android Telephony Internals 299 Android and VoIP 302 Appendix: Wireless Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309 Table of Contents | vii
  • 15. Preface When Google announced the development of Android, the field of mobile platforms was already well established. Even in the narrower category of open source platforms, a number of viable alternatives were being pushed by proponents. Yet Android has stimulated not only widespread technical interest but rampant speculation about its potential to completely transform the world of the personal device. Instead of a con- venient prop to support a set of familiar functions, such as phone calls, email, and restaurant lookups, the electronic device could become an open-ended window into the whole world—could become, in short, anything that the user and the developer could think to make it. How much of the cogent analysis and fervid hype will come to pass can be discussed elsewhere; this book is for those who want to get to know the programming environ- ment for Android and learn what they themselves can do to make a difference. We have spent many grueling months investigating the source code over multiple releases and trying out the functions of the library and development kit. We have been working hard to uncover the true Android, going beyond any documentation we could find online or in print. This book, read carefully, can enable any Java programmer to develop useful and robust applications for Android. It also takes you into the internals in some places, so you know how Android supports what you’re doing—and so you can play around with its open source code if you like. Audience This book is intended for experienced software developers who want to develop ap- plications in the Android mobile environment. It assumes you have some experience with the Java programming language, with using Java to implement user interfaces, and that you are at least familiar with the technologies Android uses, such as XML, SQL, GTalk(XMPP), OpenGL-ES, and HTTP. ix
  • 16. How This Book Is Organized This book is organized around the core example program introduced in Chapter 2. Later chapters illustrate development techniques by adding to the example through implementing modular extensions, where this is feasible. Some chapters (and the Ap- pendix) cover more advanced topics that are not required for many applications. Part I, Development Kit Walk-Through, gets you started with the basics you’ll need to write applications. Chapter 1, Getting to Know Android, explains Android’s place in the market and its basic architecture. Chapter 2, Setting Up Your Android Development Environment, tells you how to down- load the software you need, including Eclipse and the Android plug-in, and how to get started programming. Chapter 3, Using the Android Development Environment for Real Applications, describes the files that make up a typical Android program. Chapter 4, Under the Covers: Startup Code and Resources in the MJAndroid Applica- tion, looks at the fundamental Java code and XML resources that every application needs. Chapter 5, Debugging Android Applications, introduces a number of tools for debugging and performance, including Eclipse, logs, the Android Debug Bridge (adb), DDMS, and Traceview. Chapter 6, The ApiDemos Application, offers a high-level tour of the sample Android code included in the toolkit, with tips for exploring it yourself. Chapter 7, Signing and Publishing Your Application, shows you how to make your ap- plication ready for public use. Part II, Programming Topics, explores in depth the major libraries you’ll need, and shows you how to use them effectively. Chapter 8, Persistent Data Storage: SQLite Databases and Content Providers, shows how to use the two most powerful means in Android for storing and serving data. Chapter 9, Location and Mapping, shows how to determine and display the user’s lo- cation, and how to use Google Maps. Chapter 10, Building a View, introduces graphical programming on Android by ex- plaining how to create and manipulate windows and views. Chapter 11, A Widget Bestiary, covers the most popular and useful graphical interface elements provided by Android. Chapter 12, Drawing 2D and 3D Graphics, shows how to lay out graphics, and delves into drawing, transforming, and animating your own graphics. x | Preface
  • 17. Chapter 13, Inter-Process Communication, covers Intents and Remote Methods, which allow you to access the functionality of other applications. Chapter 14, Simple Phone Calls, shows how to dial a number from an application, and explains how Android carries out the request. Chapter 15, Telephony State Information and Android Telephony Classes, shows how to get information about telephony service and phone calls, and offers a tour of tel- ephony internals. Appendix, Wireless Protocols, offers some background and history on wireless services. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values deter- mined by context. This icon signifies a tip, suggestion, or general note. This icon indicates a warning or caution. Using Code Examples This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does Preface | xi
  • 18. require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Android Application Development by Rick Rogers, John Lombardo, Zigurd Mednieks, and Blake Meike. Copyright 2009 Rick Rogers, John Lombardo, Zigurd Mednieks, and Blake Meike, 978-0-596-52147-9.” If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at [email protected]. Safari® Books Online When you see a Safari® Books Online icon on the cover of your favorite technology book, that means the book is available online through the O’Reilly Network Safari Bookshelf. Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free at http://my.safaribooksonline.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at: http://www.oreilly.com/catalog/9780596521479 To comment or ask technical questions about this book, send email to: [email protected] For more information about our books, conferences, Resource Centers, and the O’Reilly Network, see our website at: http://www.oreilly.com xii | Preface
  • 19. Acknowledgments We’d like to thank Bill Dimmick, Brad O’Hearne, and Hycel Taylor for their thoughtful and careful reviews of this book under a high-pressure timeline. Rick Rogers Like anything worth doing, I suppose, this book ended up taking more time and effort than any of us planned in the beginning. I’d like to thank my coauthors and the great folks at O’Reilly for sticking with it and bringing the work to fruition, through all the twists and turns. I’d also like to thank my family and friends, who encouraged me all through the process, and lent an ear when I just needed to talk. Most especially, though, I want to dedicate the book to my wife, Susie, whose patience knows no bounds, and whose amazing attitude toward life is an enduring inspiration for me no matter what I’m doing. John Lombardo I would like to thank my wonderful wife, Dena, who kept life from interfering when I closed the office door to work on the book. I want to dedicate this book to my mother, Marguerite Megaris, who died suddenly in 2007. I gave her a copy of my first book, Embedded Linux (New Riders), back in 2001. She cracked it open to a page with some assembly code, looked at it for about 10 seconds, closed it, and said, “That’s nice, dear.” We had a good laugh over that. I’d also like to thank all the wonderful people at O’Reilly for all their hard work. I’d especially like to thank Andy Oram, who coddled and prodded us in just the right doses to keep the book humming along at a good clip. Zigurd Mednieks Thanks to Terry, Maija, and Charles for putting up with my schedule while I was writ- ing, and to Andy Oram and my coauthors for letting me participate, and hopefully, contribute. Blake Meike I am very grateful to have been invited to work with such an amazing group of people. Thanks to Zigurd for suggesting it; Andy Oram for practically holding my pen; and Rick, John, and Isabel Kunkle for making those Thursday morning calls a pleasure. Thanks to Mike Morton for actually reading both the text and the code. Though it may seem obvious, thanks to the Google Android developers. Not bad guys. Not bad at all. Finally, love and thanks to my wife, Catherine, who never let me see any disappoint- ment when I said, yet again, “Can’t. Gotta work on the book this weekend.” Yes, babe, let’s do the bookcase now. Preface | xiii
  • 21. PART I Development Kit Walk-Through This book gets you started with Android. We’ll explain what’s special about Android’s features and how its architecture achieves its goals, and show you how to get started programming. You’ll learn the tools that let you write programs using Eclipse; run them on the Android emulator; and carry out debugging, tracing, and profiling. The last chapter in Part 1 shows you how to sign your program for public distribution.
  • 23. CHAPTER 1 Getting to Know Android Why Android? Google’s Android mobile phone software platform may be the next big opportunity for application software developers. Google announced the Open Handset Alliance and the Android platform in November of 2007, releasing the first beta version of the Android Software Development Kit (SDK) at the same time. Within a matter of a few months, over 1 million people had down- loaded versions of the SDK from Google’s website. In the United States, T-Mobile announced the G1 Android mobile phone in October of 2008, and estimates are that several hundred thousand G1s were sold before the end of that year. There are already several competing mobile phone software stacks in the market, so why is there such interest in Android? Android has the potential for removing the barriers to success in the development and sale of a new generation of mobile phone application software. Just as the the stand- ardized PC and Macintosh platforms created markets for desktop and server software, Android, by providing a standard mobile phone application environment, will create a market for mobile applications—and the opportunity for applications developers to profit from those applications. Why hasn’t it been profitable to develop mobile applications for smartphones until now? And what are the problems that Android alleviates? Fragmentation About 70 million smartphones were sold in 2007, so there are a lot of phones available to run applications, but each brand has a different application environ- ment. This is particularly true of Linux-based phones, where each handset vendor has had to assemble scores of pieces of third-party software to create a viable mobile phone platform. There is no chance that they would all choose the same compo- nents to build a mobile smartphone. 3
  • 24. Java was supposed to help this situation, with J2ME and the wireless Java recom- mendations (CDC, CLDC, MIDP, JTWI, MSA, etc.) providing a common applications environment across handsets. Unfortunately, almost every handset that supports J2ME also support vendor-proprietary extensions that limit the port- ability of applications. Proprietary software stacks Most existing smartphones use proprietary, relatively closed software stacks, such as Nokia’s Series 60 with the Symbian operating system, or Microsoft’s Windows Mobile. Modifications to these stacks (adding a driver, for example) have to be done either by the stack owner or by the handset manufacturer. The stacks are not open source, so changing anything in the stack is difficult at best. Most Linux- based phones to date have an open source kernel (as required by the GPL license), but keep other details of the software stack (application framework, multimedia framework, applications) proprietary. Closed networks Series 60 and Windows Mobile do allow the addition of third-party applications, but mobile operators often lock the handsets so applications cannot be added. The operators claim this is needed to preserve the integrity of their mobile networks, making sure that viruses and spam are not inadvertently installed by end users. It also suits the operator’s business model, because their mobile phone customers are confined to the operators’ “walled garden” of applications, both on the phone and in the network. Android includes an open catalog of applications, Android Market, that users can download over the air to their Android phones. It also allows direct loading of applications via USB connection. Android gives developers a way to develop unique, creative applications and get those applications in the hands of customers. Hundreds of thousands of Android mobile phone users are already there, looking for the next clever or useful application, and that application could be yours. The Open Handset Alliance Google and 33 other companies announced the formation of the Open Handset Alli- ance on November 5, 2007. According to the joint press release from that day: This alliance shares a common goal of fostering innovation on mobile devices and giving consumers a far better user experience than much of what is available on today’s mobile platforms. By providing developers a new level of openness that enables them to work more collaboratively, Android will accelerate the pace at which new and compelling mobile services are made available to consumers. For us as mobile application developers, that means we are free to develop whatever creative mobile applications we can think of, free to market them (or give them, at our option) to Android mobile phone owners, and free to profit from that effort any way 4 | Chapter 1: Getting to Know Android
  • 25. we can. Each member of the Open Handset Alliance has its own reasons for partici- pating and contributing its intellectual property, and we are free to benefit. The Open Handset Alliance integrates contributed software and other intellectual property from its member companies and makes it available to developers through the open source community. Software is licensed through the Apache V2 license, which you can see at http://www.apache.org/licenses/LICENSE-2.0.txt. Use of the Apache li- cense is critical, because it allows handset manufacturers to take Android code, modify it as necessary, and then either keep it proprietary or release it back to the open source community, at their option. The original Alliance members include handset manufac- turers (HTC, LG, Motorola, Samsung), mobile operators (China Mobile Communica- tions, KDDI, DoCoMo, Sprint/Nextel, T-Mobile, Telecom Italia, Telefonica), semiconductor companies (Audience, Broadcom, Intel, Marvell, NVidia Qualcomm, SiRF, Synaptics), software companies (Ascender, eBay, esmertec, Google, LivingImage, LiveWire, Nuance, Packet Video, SkyPop, SONiVOX), and commercialization com- panies (Aplix, Noser, TAT, Wind River). The Alliance includes the major partners needed to deliver a platform for mobile phone applications in all of the major geographies. The Alliance releases software through Google’s developer website (http://developer .android.com). The Android SDK for use by application software developers can be downloaded directly from that website. (The Android Platform Porting Kit for use by handset manufacturers who want to port the Android platform to a handset design is not covered in this book.) The Android Execution Environment Applications in Android are a bit different from what you may be used to in the desktop and server environments. The differences are driven by a few key concepts unique to the mobile phone environment and unique to Google’s intentions for Android. As you write applications for an Android handset, you will use these concepts to guide the design and implementation of the application: Limited resources Mobile phones today are very powerful handheld computers, but they are still limited. The fundamental limitation of a mobile device is battery capacity. Every clock tick of the processor, every refresh of memory, every backlit pixel on the user’s screen takes energy from the battery. Battery size is limited, and users don’t like frequent battery charging. As a result, the computing resources are limited— clock rates are in the hundreds of MHz, memory is at best a few gigabytes, data storage is at best a few tens of gigabytes. Throughout this book we will talk about the mechanisms included in Android to optimize for these limited resources. The Android Execution Environment | 5
  • 26. Mobile mashups InthedesktopInternetworld,mashupsmakeitveryeasytocreatenewapplications by reusing the data and user interface elements provided by existing applications. Google Maps is a great example: you can easily create a web-based application that incorporates maps, satellite imagery, and traffic updates using just a few lines of JavaScript on your own web page. Android extends that concept to the mobile phone. In other mobile environments, applications are separate, and with the ex- ception of browser-based applications, you are expected to code your applications separately from the other applications that are running on the handset. In Android you can easily create new applications that incorporate existing applications. Chapter 13 focuses on these mobile mashups. Interchangeable applications In other mobile software environments, applications are coded to access data from specific data providers. If you need to send an email from a Windows Mobile ap- plication, for example, you code explicit references to Pocket Outlook’s email in- terface, and send the email that way. But what if the user wants to use another email client? Android incorporates a fundamental mechanism (Intents) that is independent of specific application implementations. In an Android application, you don’t say you want to send email through a specific application; instead, you say you want to send an email through whatever application is available. The operating system takes care of figuring out what application can send emails, starts that application if needed, and connects your request so the email can be sent. The user can sub- stitute different browsers, different MP3 players, or different email clients at will, and Android adapts automatically. Components of an Android Application Your Android applications will be built from four basic component types that are de- fined by the Android architecture: Activities These are comparable to standalone utilities on desktop systems, such as office applications. Activities are pieces of executable code that come and go in time, instantiated by either the user or the operating system and running as long as they are needed. They can interact with the user and request data or services from other activities or services via queries or Intents (discussed in a moment). Most of the executable code you write for Android will execute in the context of an Activity. Activities usually correspond to display screens: each Activity shows one screen to the user. When it is not actively running, an Activity can be killed by the operating system to conserve memory. 6 | Chapter 1: Getting to Know Android
  • 27. Services These are analogous to services or daemons in desktop and server operating sys- tems. They are executable pieces of code that usually run in the background from the time of their instantiation until the mobile handset is shut down. They generally don’t expose a user interface. The classic example of a Service is an MP3 player that needs to keep playing queued files, even while the user has gone on to use other applications. Your application may need to implement Services to perform background tasks that persist without a user interface. Broadcast and Intent Receivers These respond to requests for service from another application. A Broadcast Receiver responds to a system-wide announcement of an event. These announce- ments can come from Android itself (e.g., battery low) or from any program run- ning on the system. An Activity or Service provides other applications with access to its functionality by executing an Intent Receiver, a small piece of executable code that responds to requests for data or services from other activities. The requesting (client) activity issues an Intent, leaving it up to the Android framework to figure out which application should receive and act on it. Intents are one of the key architectural elements in Android that facilitate the cre- ation of new applications from existing applications (mobile mashups). You will use Intents in your application to interact with other applications and services that provide information needed by your application. Intents and Intent Receivers are covered in more detail in Chapter 13. Content providers These are created to share data with other activities or services. A content provider uses a standard interface in the form of a URI to fulfill requests for data from other applications that may not even know which content provider they are using. For example, when an application issues a query for Contact data, it addresses the query to a URI of the form: content://contacts/people The operating system looks to see which applications have registered themselves as content providers for the given URI, and sends the request to the appropriate application (starting the application if it is not already running). If there is more than one content provider registered for the requested URI, the operating system asks the user which one he wants to use. An application doesn’t have to use all of the Android components, but a well-written application will make use of the mechanisms provided, rather than reinventing func- tionality or hardcoding references to other applications. URIs and Intents together al- low Android to provide a very flexible user environment. Applications can be easily added, deleted, and substituted, and the loose coupling of intents and URIs keeps everything working together. Components of an Android Application | 7
  • 28. Android Activity Lifecycle Android is designed around the unique requirements of mobile applications. In par- ticular, Android recognizes that resources (memory and battery, for example) are limi- ted on most mobile devices, and provides mechanisms to conserve those resources. The mechanisms are evident in the Android Activity Lifecycle, which defines the states or events that an activity goes through from the time it is created until it finishes running. The lifecycle is shown diagrammatically in Figure 1-1. Your activity monitors and reacts to these events by instantiating methods that override the Activity class methods for each event: onCreate Called when your activity is first created. This is the place you normally create your views, open any persistent datafiles your activity needs to use, and in general ini- tialize your activity. When calling onCreate, the Android framework is passed a Bundle object that contains any activity state saved from when the activity ran before. Start activity Usernavigates backtoactivity Processiskilled Activitycomes toforeground Activitynolongervisible NO YES Activityinteracts withuser Activitybecomes visible Activity exits onCreate() onStart() In foreground? onResume() onPause() onStop() onDestroy() onRestart() Figure 1-1. Android Activity lifecycle 8 | Chapter 1: Getting to Know Android
  • 29. onStart Called just before your activity becomes visible on the screen. Once onStart com- pletes, if your activity can become the foreground activity on the screen, control will transfer to onResume. If the activity cannot become the foreground activity for some reason, control transfers to the onStop method. onResume Called right after onStart if your activity is the foreground activity on the screen. Atthispointyouractivityisrunningandinteractingwiththeuser.Youarereceiving keyboard and touch inputs, and the screen is displaying your user interface. onResume is also called if your activity loses the foreground to another activity, and that activity eventually exits, popping your activity back to the foreground. This is where your activity would start (or resume) doing things that are needed to update the user interface (receiving location updates or running an animation, for example). onPause Called when Android is just about to resume a different activity, giving that activity the foreground. At this point your activity will no longer have access to the screen, so you should stop doing things that consume battery and CPU cycles unnecessa- rily. If you are running an animation, no one is going to be able to see it, so you might as well suspend it until you get the screen back. Your activity needs to take advantage of this method to store any state that you will need in case your activity gains the foreground again—and it is not guaranteed that your activity will resume. If the mobile device you are running on runs out of memory, there is no virtual memory on disk to use for expansion, so your activity may have to make way for a system process that needs memory. Once you exit this method, Android may kill your activity at any time without returning control to you. onStop Called when your activity is no longer visible, either because another activity has taken the foreground or because your activity is being destroyed. onDestroy The last chance for your activity to do any processing before it is destroyed. Nor- mally you’d get to this point because the activity is done and the framework called its finish method. But as mentioned earlier, the method might be called because Android has decided it needs the resources your activity is consuming. It is important to take advantage of these methods to provide the best user experience possible. This is the first place in this book we’ve discussed how programming for mobile devices is different from programming for desktop devices, and there will be many more such places as you go through later chapters. Your users will appreciate it if you write your activities with the activity lifecycle in mind, and you will ultimately benefit. Android Activity Lifecycle | 9
  • 30. Android Service Lifecycle Thelifecycleforaserviceissimilartothatforanactivity,butdifferentinafewimportant details: onCreate and onStart differences Services can be started when a client calls the Context.startService(Intent) method. If the service isn’t already running, Android starts it and calls its onCreate method followed by the onStart method. If the service is already running, its onStart method is invoked again with the new intent. So it’s quite possible and normal for a service’s onStart method to be called repeatedly in a single run of the service. onResume, onPause, and onStop are not needed Recall that a service generally has no user interface, so there isn’t any need for the onPause, onResume, or onStop methods. Whenever a service is running, it is always in the background. onBind If a client needs a persistent connection to a service, it can call the Context.bind Service method. This creates the service if it is not running, and calls onCreate but not onStart. Instead, the onBind method is called with the client’s intent, and it returns an IBind object that the client can use to make further calls to the service. It’s quite normal for a service to have clients starting it and clients bound to it at the same time. onDestroy As with an activity, the onDestroy method is called when the service is about to be terminated.Androidwillterminateaservicewhentherearenomoreclientsstarting or bound to it. As with activities, Android may also terminate a service when memory is getting low. If that happens, Android will attempt to restart the service when the memory pressure passes, so if your service needs to store persistent in- formation for that restart, it’s best to do so in the onStart method. How This Book Fits Together Android is a sophisticated platform whose parts all work together: drawing and layout, inter-process communication and data storage, search and location. Introducing it in pieces is a challenge, but we’ve entertained the conceit of introducing the complexities of the platform in a linear order. The platform is also so rich that we can’t hope to show you how to use everything you want, or even a large subset of its capabilities. We expect you to consult the official documentation while reading this book and trying the examples. You should also use other online resources—but be careful about web pages or forum postings that have 10 | Chapter 1: Getting to Know Android
  • 31. been around a while, because interfaces change. There is also a substantial amount of misinformation out on the Web; we discovered scads of it while writing the book. This book is written for experienced developers who want to quickly learn what they need to know to build Android applications. The book is written with references to an example application (MJAndroid, discussed in much more detail in the next chapter) that you can freely download and reuse. The major topics covered in the book include: New Android concepts Android builds upon a lot of legacy technology (Java, Linux, and the Internet, just to name a few), but it also introduces some new concepts needed to enable the application environment. Android development environment We’ll show how to install the free, open source Android development environment on your own system, and how to use that environment to develop, test, and debug your own applications. You’ll not only learn the mechanics of using the system, but also what’s going on behind the scenes, so you’ll have a better understanding of how the whole system fits together. Android user interface The Android user interface elements are similar to things you’ve seen before, but also different. We’ll show you what the principal elements are, how they’re used, and what they look like on the screen. We’ll also show you the basic layout types available for the Android screen. Intents Android makes it easy to leverage existing applications through the use of Intents. For example, if you want to dial a phone number, you don’t have to do all the work in your application, or even know what applications are available that know how to dial. You can just ask Android to find you an installed application that knows how to dial out, and pass it the string of numbers. Location-based services and mapping As you’d expect from a Google-sponsored environment, mapping and location are major features of Android. You’ll see how easy it is to create sophisticated mapping and location-based applications. Persistent data Android includes the SQLite database libraries and tools, which your application can use to store persistent data. Content providers, which we’ve already intro- duced, provide data to other applications. Using the libraries can be a little tricky, but in Chapter 8 we’ll guide you through the creation of a database, and reading, writing, and deleting data records. Graphics Your application has access to 2D and 3D graphics capabilities in Android. Ani- mation and various advanced effects are also provided. This book will show you How This Book Fits Together | 11
  • 32. how to use those libraries so you can build a compelling user interface for your application. Communications Android, even more than most smartphone operating systems, places great em- phasis on communication—by voice, by text messaging, by instant messaging, and byInternet.You’llseehowyourapplicationcantakeadvantageofthesecapabilities so your users can become part of a larger community of data and users. The next three chapters, Chapters 2 through 4, set you up with a working application, and will give you a sense of how the files and basic classes fit together. Chapter 5 empowers you to better understand what you’re doing and helps you debug your first efforts. The Android toolkit naturally comes with an enormous number of working code ex- amples in its ApiDemos application. Unfortunately, its very size and sophistication make it a formidable castle for novices to enter. Chapter 6 guides you through it. A bit of experience with ApiDemos will convince you that you need some more back- ground and tutorial help. In Chapter 7, we’ll show you how to sign and publish your application, which you need to do in order to test it with Google Maps, even before you’re ready to go public. Chapter 8 presents tutorials on two data storage systems. Chapter 9 presents location and mapping, which are key features that draw people to mobile devices and which you’ll surely want to incorporate into your application. We then turn to a critical part of any end-user application, graphics, in three information-packed chapters, Chapters 10 through 12. Chapter 13 takes another step into the complexity and unique power of Android, by discussing how applications can offer functionality to other applications. This allows for powerful mashups, which involve one program standing on the shoulders of other programs. Let’s not forget that Android runs on telephones. Chapters 14 and 15 wrap up the book by showing you how to place and track phone calls. There’s even more to Android than these features, of course, but programmers of all stripes will find in this book what they need to create useful and efficient programs for the Android platform. 12 | Chapter 1: Getting to Know Android
  • 33. CHAPTER 2 Setting Up Your Android Development Environment Setting Up Your Development Environment Android applications, like most mobile phone applications, are developed in a host- target development environment. In other words, you develop your application on a host computer (where resources are abundant) and download it to a target mobile phone for testing and ultimate use. Applications can be tested and debugged either on a real Android device or on an emulator. For most developers, using an emulator is easier for initial development and debugging, followed by final testing on real devices. To write your own Android mobile phone applications, you’ll first need to collect the required tools and set up an appropriate development environment on your PC or Mac. In this chapter we’ll collect the tools you need, download them and install them on your computer, and write a sample application that will let you get the feel of writing and running Android applications on an emulator. Linux, Windows, and OS X are all supported development environments, and we’ll show you how to install the latest set of tools on each. Then, we’ll show you any configuration you need to do after installing the tools (setting PATH environment variables and the like), again for each of the three operating systems. Finally, we’ll write a short little “Hello, Android” application that demonstrates what needs to be done in order to get a generic application running. The Android SDK supports several different integrated development environments (IDEs). For this book we will focus on Eclipse because it is the IDE that is best integrated with the SDK, and, hey, it’s free. No matter which operating system you are using, you will need essentially the same set of tools: • The Eclipse IDE • Sun’s Java Development Kit (JDK) • The Android Software Developer’s Kit (SDK) • The Android Developer Tool (ADT), a special Eclipse plug-in 13
  • 34. Since you’re probably going to develop on only one of the host operating systems, skip to the appropriate section that pertains to your selected operating system. Creating an Android Development Environment The Android Software Development Kit supports Windows (XP and Vista), Linux (tested on Ubuntu Dapper Drake, but any recent Linux distro should work), and Mac OS X (10.4.8 or later, Intel platform only) as host development environments. Instal- lation of the SDK is substantially the same for any of the operating systems, and most of this description applies equally to all of them. Where the procedure differs, we will clearly tell you what to do for each environment: 1. Install JDK: The Android SDK requires JDK version 5 or version 6. If you already have one of those installed, skip to the next step. In particular, Mac OS X comes with the JDK version 5 already installed, and many Linux distributions include a JDK. If the JDK is not installed, go to http://java.sun.com/javase/downloads and you’ll see a list of Java products to download. You want JDK 6 Update n for your operating system, where n is 6 at the time of this writing. Windows (XP and Vista) • Select the distribution for “Windows Offline Installation, Multi-language.” • Read, review, and accept Sun’s license for the JDK. (The license has become very permissive, but if you have a problem with it, alternative free JDKs exist.) • Once the download is complete, a dialog box will ask you whether you want to run the downloaded executable. When you select “Run,” the Windows Installer will start up and lead you through a dialog to install the JDK on your PC. Linux • Select the distribution for “Linux self-extracting file.” • Read, review, and accept Sun’s license for the JDK. (The license has become very permissive, but if you have a problem with it, alternative free JDKs exist.) • You will need to download the self-extracting binary to the location in which you want to install the JDK on your filesystem. If that is a system- wide directory (such as /usr/local), you will need root access. After the file is downloaded, make it executable (chmod +x jdk-6version-linux- i586.bin), and execute it. It will self-extract to create a tree of directories. Mac OS X Mac OS X comes with JDK version 5 already loaded. 14 | Chapter 2: Setting Up Your Android Development Environment
  • 35. 2. Install Eclipse: The Android SDK requires Eclipse version 3.3 or later. If you do not have that version of Eclipse installed yet, you will need to go to http://www .eclipse.org/downloads to get it, and you might as well get version 3.4 (also known as Ganymede), since that package includes the required plug-ins mentioned in the next step. You want the version of the Eclipse IDE labeled “Eclipse IDE for Java Developers,”andobviouslyyouwanttheversionforyouroperatingsystem.Eclipse will ask you to select a mirror site, and will then start the download. Windows (XP or Vista) The Eclipse download comes as a big ZIP file that you install by extracting the files to your favorite directory. For this book, we’ll assume that you extracted to C:/eclipse. Eclipse is now installed, but it will not show up in your Start menu of applications. You may want to create a Windows shortcut for C:/eclipse/ eclipse.exe and place it on your desktop, in your Start menu, or someplace else where you can easily find it. Linux and Mac OS X Note that, as of this writing, the version of Eclipse installed if you request it on Ubuntu Hardy Heron is 3.2.2, which does not contain all the plug-ins needed for Android. The Eclipse download comes as a big tarball (.gz file) that you install by extracting the files to your favorite directory. For this book, we’ll assume that you extracted to /usr/lib/eclipse. The executable itself is located in that directory and is named eclipse. 3. Check for required plug-ins: You can skip this step if you just downloaded a current version of Eclipse as we recommended. If you are using a preinstalled ver- sion of Eclipse, you need to make sure you have the Java Development Tool (JDT) and Web Standard Tools (WST) plug-ins. You can easily check to see whether they are installed by starting Eclipse and selecting menu options “Windows → Preferences...”. The list of preferences should include one for “Java” and one for either “XML” or “Web and XML.” If they aren’t on the list, the easiest thing to do is reinstall Eclipse, as described in the previous step. Installing “Eclipse IDE for Java Developers” will automatically get the needed plug-ins. 4. Install Android SDK: This is where you should start if you already have the right versions of Eclipse and the JDK loaded. The Android SDK is distributed through Google’s Android site, http://developer.android.com/sdk/1.1_r1/index.html. You will need to read, review, and accept the terms of the license to proceed. When you get to the list of downloads, you will see a table of distributions. Select the one for your operating system (XP and Vista use the same distribution). The package (file) names include the release number. For example, as this is written, the latest version of the SDK is 1.1_r1, so the filename for Windows is android-sdk- windows-1.1_r1.zip. Setting Up Your Development Environment | 15
  • 36. For versions 3.3 and later of Eclipse, the Android download site provides directions about how to install the plug-in through Eclipse’s software updates utility. If you’re using Eclipse 3.2 or the software update technique doesn’t work for you, download the SDK from the Android site and install it using instructions in the next paragraph. The file you download is another archive file, as with Eclipse: a ZIP file on Win- dows, a tar-zipped file for Linux and MacOS X. Do the same thing as for Eclipse: extract the archive file to a directory where you want to install Android, and make a note of the directory name (you’ll need it in step 6). The extraction will create a directory tree containing a bunch of subdirectories, including one called tools. 5. Update the environment variables: To make it easier to launch the Android tools, add the tools directory to your path. • On Windows XP, click on Start, then right-click on My Computer. In the pop- up menu, click on Properties. In the resulting System Properties dialog box, select the Advanced tab. Near the bottom of the Advanced tab is a button, “En- vironment Variables,” that takes you to an Environment Variables dialog. User environment variables are listed in the top half of the box, and System environ- ment variables in the bottom half. Scroll down the list of System environment variables until you find “Path”; select it, and click the “Edit” button. Now you will be in an Edit System Variable dialog that allows you to change the envi- ronment variable “Path.” Add the full path of the tools directory to the end of the existing Path variable and click “OK.” You should now see the new version of the variable in the displayed list. Click “OK” and then “OK” again to exit the dialog boxes. • On Windows Vista, click on the Microsoft “flag” in the lower left of the desktop, then right-click on Computer. At the top of the resulting display, just below the menu bar, click on “System Properties.” In the column on the left of the resulting box, click on “Advanced system settings.” Vista will warn you with a dialog box that says “Windows needs your permission to continue”; click “Continue.” Near the bottom of the System Properties box is a button labeled “Environment Variables” that takes you to an Environment Variables dialog. User environment variables are listed in the top half of the box, and System environment variables in the bottom half. Scroll down the list of System environment variables until you find “Path”; select it, and click the “Edit” button. Now you will be in an Edit System Variable dialog that allows you to change the environment variable “Path.” Add the full path of the tools directory to the end of the existing Path variable, and click “OK.” You should now see the new version of the variable in the displayed list. Click “OK” and then “OK” again to exit the dialog boxes. • On Linux, the PATH environment variable can be defined in your ~/.bashrc ~/.bash_profile file. If you have either of those files, use a text editor such as gedit, vi, or Emacs to open the file and look for a line that exports the PATH 16 | Chapter 2: Setting Up Your Android Development Environment
  • 37. variable. If you find such a line, edit it to add the full path of the tools directory to the path. If there is no such line, you can add a line like this: export PATH=${PATH}:your_sdk_dir/tools where you put the full path in place of your_sdk_dir. • On Mac OS X, look for a file named .bash_profile in your home directory (note the initial dot in the filename). If there is one, use an editor to open the file and look for a line that exports the PATH variable. If you find such a line, edit it to add the full path of the tools directory to the path. If there is no such line, you can add a line like this: export PATH=${PATH}:your_sdk_dir/tools where you put the full path in place of your_sdk_dir. 6. Install the Android plug-in (ADT): Throughout this book, we will make use of the Android Development Tool plug-in that Google supplies for use in building Android applications. The plug-in is installed in much the same way as any other Eclipse plug-in: a. Start Eclipse, if it’s not already running. b. From the menu bar, select “Help → Software Updates → Find and Install...”. c. In the Install/Update dialog, select “Search for new features to install” and click on “Next.” d. In the Install dialog, click on “New Remote Site.” A “New Update Site” dialog pops up. Enter a name for the plug-in (“Android Plugin” will do), and the URL for updates: https://dl-ssl.google.com/android/eclipse. Click “OK.” e. The new site should now appear in the list of sites on the Install dialog. Click “Finish.” f. In the Search Results dialog, select the checkbox for “Android Plugin → Developer Tools” and click “Next.” g. The license agreement for the plug-in appears. Read it, and if you agree, select “Accept terms of the license agreement” and click “Next.” Click “Finish.” h. You will get a warning that the plug-in is not signed. Choose to install it anyway by clicking “Install All.” i. Restart Eclipse. j. After Eclipse restarts, you need to tell it where the SDK is located. From the menu bar, select “Window → Preferences.” In the Preferences dialog, select “Android” in the left column. k. Use the “Browse” button to navigate to the place you installed the Android SDK, and click on “Apply,” then on “OK.” Setting Up Your Development Environment | 17
  • 38. Congratulations—you have installed a complete Android development environment without spending a penny. As you’ll see in this and subsequent chapters, the environ- ment includes a very sophisticated set of tools to make Android programming easier, including: • An Integrated Development Environment based on Eclipse, arguably the premier IDE for Java development. Eclipse itself brings many valuable development fea- tures. Google and OHA have taken advantage of Eclipse’s extensibility to provide features customized for Android, including debugging capabilities that are tuned to the needs of mobile application developers like you. • A Java development environment and Dalvik virtual machine that build on Sun’s JDK foundation to provide a very sophisticated programming environment for your applications. • A complete mobile phone emulator that allows you to test your applications with- out having to download them to a target mobile phone. The emulator includes features for testing your application under different mobile phone communication conditions (fading, dropped connections, etc.). • Test tools, such as Traceview, which allow you to tune your application to take best advantage of the limited resources available on a mobile phone. Hello, Android So enough downloading; let’s write a program. A “Hello World!” program is tradi- tional, and we will start with something similar to demonstrate what you need to do to create, build, and test an Android application. We won’t explore much of the An- droid API for this program—that’s left for the following chapters—but here we’ll get a taste for the development environment and the steps you go through to create an application for Android. Where We’re Going There isn’t much functionality in this program. We just want to display some text on the Android emulator window that says “Hello Android!” (see Figure 2-1). Starting a New Android Application: HelloWorld Several components are needed to build an Android application. Fortunately, the Eclipse IDE with the Android plug-in automates a lot of the work needed to create and maintain these components. We will start by using the IDE to create a project for our application. Start up Eclipse and select “File → New → Project...” from the menu bar (be sure to select “Project...”, not “Java Project”). You’ll see a list of project types, similar to the menu in Figure 2-2. 18 | Chapter 2: Setting Up Your Android Development Environment
  • 39. Select “Android Project” and click “Next” to get the “New Android Project” dialog box (Figure 2-3). We’ll use “HelloWorld” as the name for both the Project and the Application. You don’t need to change the button or checkbox selections, and we’ll use the package name com.oreilly.helloworld as shown. Every Android application has to have at least one Activity (an executable that usually has a user interface), so let’s say we’re going to include an Activity called Hello WorldActivity, as shown in the dialog box. Click “Finish,” and the Android Software Development Kit does a number of things for you, to make your life easier as a Figure 2-1. “Hello Android” screenshot Figure 2-2. Eclipse New Project menu Hello, Android | 19
  • 40. developer. In Figure 2-4, I’ve expanded the tree in the Package Explorer window to show some of the files and directories that the Android SDK created. The Android SDK created a HelloWorld directory in the default Eclipse workspace for your project. It also created subdirectories for your source files (.src), references to the Android Library, assets, resources (.res), and a manifest file (AndroidManifest.xml). In each of the subdirectories it created another level of subdirectories as appropriate. Let’s take a quick look at them: Sources (under src) • Contains a directory structure that corresponds to the package name you gave for your application: in this case, com.android.helloworld. • Contains a Java template for the Activity you indicated was in the application (HelloWorldActivity) and may contain a directory of resource references (R.java). R.java is actually generated by the Android SDK the first time you Figure 2-3. Eclipse New Android Project dialog 20 | Chapter 2: Setting Up Your Android Development Environment
  • 41. compile your application; it contains the Java version of all the resources you define in the res directory (covered later). We’ll come back to R.java later. Figure 2-4. Eclipse project listing after creation of the HelloWorld project Hello, Android | 21
  • 42. Android Library This is just what it says. If you like, you can expand the android.jar tree and see the names of the modules included in the library. This is where your application will go for Android library references. assets Files you want to bundle with your application. We won’t have any for HelloWorld. Resources (under res) • Drawable resources are any images, bitmaps, etc., that you need for your ap- plication. For HelloWorld, the Android SDK has supplied us with the default Android icon, and that’s all we’ll need. • Layout resources tell Android how to arrange items on the screen when the application runs. These resources are XML files that give you quite a bit of freedom in laying out the screen for different purposes. For HelloWorld, we’ll just use the defaults generated by the Android SDK. • Values are constants, strings, etc., available for use by your application. Keeping them outside the sources makes it easier to customize the application, such as adapting it for different languages. Manifest (AndroidManifest.xml) This is another XML file that tells the Android build system what it needs to know to build and package your application so it can be installed on an Android phone or the emulator. This file has its own specialized editor, which we’ll describe when we get to more complicated applications. Writing HelloWorld In the Eclipse Package Explorer window, double-click on HelloWorldActivity.java. This opens the source file of that name in the center window, ready for editing: package com.oreilly.helloworld; import android.app.Activity; import android.os.Bundle; public class HelloWorldActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } 22 | Chapter 2: Setting Up Your Android Development Environment
  • 43. Looking quickly at the template code that the Android SDK has provided for us, we can note several things: • The Android SDK has included the package reference we asked for, which is con- sistent with the directory structure it created. • It has also created a (collapsed) set of imports for the library references it knows we need. • It created a class definition for the Activity we said we wanted (Hello WorldActivity), including a method called OnCreate. For the moment, don’t worry about the parameter passed into OnCreate. The savedInstanceState Bundle is a way of passing data between activities and storing data between instantiations of the same Activity. We won’t need to use this for HelloWorld. • One special line of code has been included in OnCreate: setContentView (R.layout.main); Remember that Android uses layouts to define screen layouts on the target, and that main.xml was the name of the default layout file that the Android SDK created for us under .res/layout. The R.java file is generated automatically and contains Java references for each of the resources under .res. You will never need to edit the R.java file by hand; the Android SDK takes care of it as you add, change, or delete resources. Again in the Eclipse Package Explorer window, double-click on main.xml and you will see the default layout screen in the center window. There are two tabs at the bottom of the panel that say “Layout” and “main.xml”. Click on the one that says “main.xml” to bring up the code version: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout> Again, let’s look at the key features of this template code: • Like any other XML file, this one starts with a reference to the XML version and encoding used. • LinearLayout is one of the screen layout formats provided by the Android SDK. There are several others, which can be combined hierarchically to create very Hello, Android | 23
  • 44. complex screen layouts. For our purposes, a simple linear layout is fine. More Layout types are covered later in the book in Chapter 11. —The LinearLayout definition: xmlns:android="http://schemas.android.com/apk/res/android" identifies the XML schema being used. —This code: android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" defines an orientation, width, and height for the entire scope of the layout. • TextView describes an area where text can be displayed and edited. It resembles the text boxes you may have encountered when programming in other graphical environments. —Within the TextView definition: android:layout_width="fill_parent" android:layout_height="wrap_content" define a width and height for the TextView box. —This code: android:text="@string/hello" provides some text to display in the TextView. The actual string is defined in a separate file, res/values/strings.xml. If we open that file (again by clicking on it in the Package Explorer), we see a specialized string editor added by ADT. If you select “hello (String)” by clicking on it, you’ll see the current value for that string. By a stroke of luck, the Android SDK has already included text that is close to what we wanted to display anyway. Just to show them who’s boss, change the value of the String hello to say “Hello Android!”, or something else equally clever. Save the Project either from the Eclipse File menu (File → Save) or by clicking on the disk icon in the menu bar. Believe it or not, we’re done. We don’t have to write a single line of Java to create this application. Running HelloWorld From the Eclipse menu bar, select Run → Run. A “Run As” dialog box will pop up. Select “Android Application” from the list, which displays the dialog shown in Fig- ure 2-5. 24 | Chapter 2: Setting Up Your Android Development Environment
  • 45. A command window will pop up, followed quickly by an emulator window that looks just like a mobile phone. The emulated phone will then go through its boot sequence, which takes a few minutes (relax; if anything goes wrong, it will tell you). After a few minutes you should see the screen shown in Figure 2-6. Figure 2-6. First try at HelloAndroid Notice anything different between that screen image and the one we showed in Fig- ure 2-1? The application prints out “Hello Android!”, or whatever you wrote into the android:text line earlier, but it also displays the title of the application as “Hello World”. Let’s change the title to match our creative change to the application text. In the Package Explorer in the left panel of the Eclipse workbench, reopen the strings.xml file (the one where we found the String hello before). This will open the file in the editing window. The intent of this file is to give you a place to define strings that will be used by your application, without actually embedding them in the Java source code. The other string that’s defined here is app_name. To make things consistent, change the definition of app_name to HelloAndroid, as shown in Figure 2-7. Figure 2-5. Eclipse Application Type selection Hello, Android | 25
  • 46. Now when we run the application, we get a screen that looks just like what we set out to do, as shown previously in Figure 2-1. Congratulations! You’ve just created your first Android program by doing nothing more than changing the text in one line of code. There are much greater challenges ahead. Figure 2-7. HelloWorld String editing 26 | Chapter 2: Setting Up Your Android Development Environment
  • 47. CHAPTER 3 Using the Android Development Environment for Real Applications MicroJobs: This Book’s Main Sample Application We want to take a look at applications that are more complex than “Hello, Android,” and that’s what we’ll do in this chapter. Based on the theory that it’s often easiest to explain things through an example, we’ll take an in-depth look at a more complex application, called MicroJobs. Some of the application’s code modules are named MJAndroid, so we’ll also use that name for the code associated with MicroJobs. We’ll first take a look at what we want the MicroJobs application to do, then we’ll quickly get into the code itself. After looking at the structure of the application, we’ll describe in detail how to build the application and how to get it running on the emu- lator. Finally, we’ll take a look at some helpful debug hints in case you’re developing a similar application and it doesn’t start up. The reasons are not always obvious in the Android environment. Android and Social Networking One of the great promises of Android mobile phones is their ability to run applications that enhance opportunities for social networking between users. This promise echoes the reality of the Internet. The first generation of Internet applications were about user access to information, and many of those applications have been very popular. The second wave of Internet applications has been about connecting users to each other. Applications such as Facebook, YouTube, and many others enhance our ability to connect with people of similar interests, and allow the application’s users to provide some or all of the content that makes the application what it is. Android has the po- tential to take that concept and add a new dimension: mobility. It’s expected that a whole new generation of applications will be built for users of mobile devices: social networkingapplicationsthatareeasytousewhilewalkingdownthestreet;applications 27
  • 48. that are aware of the user’s location; applications that allow the easy sharing of content- rich information, such as pictures and videos. As mentioned in the previous chapter, we are going to study just such an application as an example of Android application development. The code is available for you to download from the book’s website (http://www.oreilly.com/catalog/9780596521479), and is based on an actual entry in the first round of the Android Developer Challenge, sponsored by Google. The application is an example of a class of applications known as “friend finders” because that’s the central idea. In the case of the MicroJobs application, instead of finding friends, the user is trying to locate a temporary job in the vicinity, so she can work for a few hours and make some money. The premise is that employers looking for temporary help have entered available jobs, descriptions, hours, and offered wages in a web-based database that is accessible from Android mobile phones. Anyone looking for a few hours’ work can use the MicroJobs application to access that database, look for jobs in the immediate area, communicate with friends about potential employers and potential jobs, and call the employer directly if she is interested in the position. For our purposes here, we won’t create an online service; we’ll just have some canned data on the phone. The application has a number of features that extend that central idea in ways that are unique to mobile handsets: Mapping The Android mobile phone environment provides very rich support for dynamic, interactive maps, and we’re going to take full advantage of its capabilities. You’ll see that with very little code, we’ll be able to show dynamic maps of our local neighborhood, getting location updates from the internal GPS to automatically scroll the map as we move. We’ll be able to scroll the map in two directions, zoom in and out, and even switch to satellite views. Finding friends and events A graphic overlay on the map will show us where jobs are placed in the area, and will allow us to get more information about a job by just touching its symbol on the map. We will access Android’s Contact Manager application to get address informationforourfriends(telephonenumbers,instantmessagingaddresses,etc.), and access the MicroJobs database to get more information about posted jobs. Instant messaging When we find friends we want to chat with, we will be able to contact them via instant messages (IMs), by trading SMS messages with our friends’ mobile phones. Talking with friends or employers If IMing is too slow or cumbersome, we’ll be able to easily place a cellular call to our friends, or call the employer offering a job. 28 | Chapter 3: Using the Android Development Environment for Real Applications
  • 49. Browsing the Web Most employers have an associated website that provides more detailed informa- tion. We’ll be able to select an employer off a list or off the map and quickly zero in on their website to find out, for example, what the place looks like. This is a fun application that could easily be developed further into a full-blown service, but our intent in this book is to show you just how easy it is to develop and combine these powerful capabilities in your own application. The complete source code for the application is available to you on the book’s website, and we will refer to it frequently throughout this book. Although it’s not absolutely required in order to understand the material in the book, you are strongly encouraged to download the source to your own computer. That way, you’ll have it readily available for reference, and it will be easy to copy sections of code and paste them into your own applications as you move on. Figure 3-1 shows the screen displayed by MJAndroid when you first run it. It’s a map of your local area, overlaid with a few buttons and pins. Figure 3-1. MJAndroid opening screenshot Android and Social Networking | 29
  • 50. Downloading the MJAndroid Code The MJAndroid application source code and project files are available from the O’Reilly website, at http://www.oreilly.com/catalog/9780596521479. To download it to your development system, use a browser to navigate to the link given, and select “Download MJAndroid.” Your operating system (Windows, Linux, or OS X) will ask you to con- firm that you want the download to happen, and ask you where to put the downloaded files. It doesn’t matter where you put the downloaded, compressed files, but you want to extract the uncompressed files into the directory that Eclipse uses as your default workspace, to make it easy to load the project. The default place is a folder called workspace under the eclipse directory that you created when you installed Eclipse. If you can’t remember where that is, start Eclipse, go to File → Switch Workspace, and it will display the location of the current workspace directory. Expand the compressed files into that directory, and be sure “use directories” is checked in the decompression dialog, so the correct folders will be created and the files written to them. To import the MJAndroid project into Eclipse, go to File → Import..., and you’ll see a Select dialog list of possible import types. Click on “Existing Projects into Workspace,” and use the Browse button to find the directory where you just expanded MJAndroid. Eclipse will import the project, and it should appear in the Project Explorer pane. A Brief Tour of the MJAndroid Code MJAndroid is a relatively simple application, despite the capabilities it gives its users. This section will give you an overview of the code and resource modules, tell you where they are located in the directory structure, and provide a glimpse of what each com- ponent does. You may want to refer to this section in the future when you’re trying to find example code for a particular function and want to locate it in the MJAndroid code tree. MJAndroid uses a directory structure that is derived directly from the standard Android application directory structure, so this will also serve as a guide to finding code in other application source trees. The Project Root Folder (MJAndroid) If you use Eclipse’s Package Explorer to look at the MJAndroid project, you will see a set of folders and files. It turns out all of these were originally created by Eclipse and the Android Development Tool, and similar folders and files are created for any Android application. Let’s see what they do: src folder src is short for Source, and this is where Eclipse and ADT expect to find all of the Java source files in your application. Almost all of the work you do to create an Android application is done in this folder and the res folder. In the next section, we will take a more detailed look at how the src folder is structured for MJAndroid. 30 | Chapter 3: Using the Android Development Environment for Real Applications
  • 51. Android Library This is just what it says: a pointer to the library of Android class files that Eclipse links to in order to provide the Android APIs. You don’t need to do anything with this entry, but if you ever need to confirm that a particular Android class is (still) there, this is where you would look. assets folder This folder is useful for holding assets that are used by the application: fonts, ex- ternal JAR files, and so on. For this book and MJAndroid, we don’t have any assets, so we will not be using the assets folder. doc folder Short for documentation, this is where you can put documentation for a project. For MJAndroid, web pages that describe the Loco project are stored in this folder. res folder res is short for resources, and this is where Eclipse and ADT expect to find the resources for your application. Resources include most of the XML files that define the layout of your application, any image files (icons, pictures that are used in your layout, sprites, etc.)—just about everything that isn’t part of a Java source file. AndroidManifest.xml file ThisfileiscreatedbyADTwhenyoucreateanewAndroidproject.Astheextension suggests, it is an XML file, and it contains a wealth of information about your application: what the activities, services, and intents are, which one starts first, which permissions your application needs from the operating system (for restricted functions such as getting location or making a phone call), and a lot of other in- formation. This file is so important that ADT provides a special editor to maintain it. It’s just an XML file, so you could always edit it with a text editor, but you will see later that the specialized editor makes everything a lot easier. Eclipse also creates two other files and another directory at the same directory level (the root directory of the MJAndroid project) that are not shown by Package Explorer. The .classpath file is used by Eclipse to keep track of the location of standard Java classes and libraries. Eclipse uses the .project file to store information about the project. You will never need to touch either of these files directly, so Eclipse doesn’t bother you with them in Package Explorer. The bin directory is where Eclipse puts the compiled class files for each of your Java source files (the ones in src). You can see all of these files if you list the directory of the root folder, but you don’t really need to pay any attention to them, because Eclipse will do it all for you. The Source Folder (src) The package name for MJAndroid is com.microjobsinc.mjandroid. Eclipse lays out the equivalent directory structure, just as it would for any Java project, and shows you the whole thing when you open src. In addition to these package folders, there is a folder named for the package that contains all the Java files for the project. These include: A Brief Tour of the MJAndroid Code | 31
  • 52. MicroJobs.java The main source file for the application. It designates the Activity that starts first, displays the map that is the centerpiece of the application, and calls other Activities or Services as necessary to implement different features in the user interface. MicroJobsDatabase.java A database helper that provides easy access to the local MJAndroid database. This is where all the employer, user, and job information is stored, using SQLite. AddJob.java and EditJob.java Part of the database portion of MJAndroid. These provide screens through which the user can add or edit job entries in the database. MicroJobsDetail.java The Activity that displays all of the detail information about a particular job opportunity. MicroJobsEmpDetail.java The Activity that displays information about an employer, including name, ad- dress, reputation, email address, phone number, etc. MicroJobsList.java The Activity that displays a list of jobs (as opposed to the map view in MicroJobs.java). It shows a simple list containing Employer and Job entries, and allows the user to sort the list by either field and call up specifics of the job or employer by touching the name on the list. R.java This file is created automatically by Eclipse and the ADT to contain Java references for all the resources that are defined in the res folder (see the next section). You should never have to edit this file by hand, as it is maintained for you as you add or edit resources. Take a look, though, just to see how resources are defined for later use in the other Java source files. The Resource Folder (res) The res folder contains three folders, and another pointer to the same Android Manifest.xml file that shows up in the root directory: drawable As you might suspect, this contains all the drawable images that MJAndroid will use: any JPEG or PNG or GIF files or bitmaps. layout As with many modern application environments, Android allows you to separate what is displayed by an Activity from how it is displayed. This directory contains XML files that describe the “how”; in other words, they are the layout files for each Activity in the application. When a program runs, Android applies the rules in these files to create the visible layout, a process known as “inflating.” 32 | Chapter 3: Using the Android Development Environment for Real Applications
  • 53. values Good programming practice calls for the separation of data that does not directly affect the operation of an application, making it a lot easier to do things like trans- lation to foreign languages, theming, etc. We aren’t going to be super strict about this in MJAndroid, but we will at least put all of the obvious user-visible text into a file called strings.xml. You’ll see how easy it is to retrieve these for use in the actual Android Activity source code. First Steps: Building and Running the MicroJobs Application So now that we know a bit about which files are located in which folders, what happens when we ask Android to run the MJAndroid application? And for that matter, how do we ask Android to run the application? Let’s take a closer look at the Android SDK environment and the views and commands available to us for running and debugging any application. A Very Short Tour of the Android SDK/Eclipse IDE The Android SDK provides three “perspectives” for working with Android projects and applications. If you’re new to Eclipse, a perspective is a collection of Eclipse views that provides a particular viewpoint of an application. Eclipse and the Android SDK have preassembled sets of views that developers have found useful, and you can switch be- tween those views, either by selecting one from the Window menu or by using the icons in the upper-right corner of the Eclipse window. You are also free to customize the perspectives, but in this book we will assume you use the standard ones provided: Java This is the default perspective, launched by Eclipse when you first say that you want to view the workspace. It includes: Package Explorer Used for viewing folders and selecting files Source Editor Used for editing Java and XML source files Tabbed Views Contains a set of useful views, accessed by tabs: • Problems, which lists errors that Eclipse and the Android SDK find in the application • Javadoc, which extracts and displays Javadoc documentation from the application • Declaration, which makes it easy to find the declaration for any variable in the code First Steps: Building and Running the MicroJobs Application | 33
  • 54. • Console, which shows the console terminal output from either the emulator or the Android phone • Search, which is used to search for results • Progress, which displays progress as an application is launched and runs Debug This perspective is primarily for debugging the application, obviously. If you select Debug from the Run menu, Eclipse switches automatically to this perspective, providing you with views that are useful for debugging: Debug A view of the application call stack, showing you how you got to the current debug point Source View This shows you the current source location in the running (or stopped) application Console and Tasks Views This contains the console terminal (as in the Java perspective), and a window where development tasks can be recorded and tracked Variables, Breakpoints, and Expressions This is where you can view current variable values, view breakpoints, and evaluate expressions while debugging Outline This shows you an outline of the current activity being executed: the classes declared, and the instances and methods defined DDMS This perspective, which stands for Dalvik Debug Monitor Service, is unique to Android. It provides Android-specific debug information, including: Devices This shows you what devices (emulated or hardware) are available to run your applications. Emulator Control This is where you can adjust parameters that define how the telephony and location emulators work. When running on the emulator, we’ll use this to manually send location updates to the location provider. LogCat This is a view of the very powerful logging facility available under Android, which allows you to see everything going on in the target system, and to filter out the information you really care about. 34 | Chapter 3: Using the Android Development Environment for Real Applications
  • 55. Other documents randomly have different content
  • 56. Ten minutes later they parted the foliage and came abruptly within full view of the village. All uttered cries of consternation at the furiousness of the battle that was taking place between the two savage tribes.
  • 57. S CHAPTER XXVI The Terrible Battle PEARS and arrows and darts flew thick and fast, striking down many a man on both sides. Fierce cries filled the atmosphere and made the Americans shudder. Here in the untamed wilds of Brazil was taking place as terrible a battle as the world had ever known. Savages—wild, hostile Indians—were the participants, and no people anywhere were more terrible when excited to insane fury. For some time none of the explorers spoke. They were too captivated by the scene. But at last Mr. Holton turned thought into action. “Get your rifles in readiness,” he commanded. “It’s up to us to drive this tribe away. The chief’s men seem unable to do it. “Now we’re all good shots,” he went on. “Suppose we fire a volley of bullets and see if we can’t make them leave without bloodshed. If we can’t, we’ll have to shoot to kill. Come on, now.” The whites raised their rifles, and, one at a time, pulled the triggers. Five shots rang out, much to the surprise of the savages. But as no damage seemed to be done by the strange reports, the Indians regained confidence and sent spears and arrows in the explorers’ direction. As a result, one of the crew went down, wounded in the thigh. “We’ll have to shoot to kill,” said Mr. Lewis at once. He raised his rifle and, taking careful aim, fired at the nearest native, who went down instantly. Mr. Lewis’s shot was followed by those of the other whites, and at once panic ensued among the invading savages.
  • 58. After only a thin defense, they took to their heels with cries of fright and bewilderment, leaving their dead and wounded behind. “Guess that drove them off all right,” said Bob with a grim smile. “Come on, let’s——But wait! Look! The chief’s tribe is worshiping us.” Bob was right. The Indians had fallen to their knees, waving their arms and muttering words that were not understood even by Professor Bigelow. Even the chief, accustomed as he was to the rifles and the whites’ power to bring down animals, bowed his head in awe at his tribe’s deliverance. It was a most embarrassing situation, and for a time the explorers were at a loss to know what to do next. Finally Professor Bigelow walked forward and uttered kind words, at the same time raising hands for the savages to rise to their feet. He succeeded well. At once they got to their feet and resumed something of their usual attitude, although they were not quite convinced that these people were not gods. The chief went forward and conversed with them so rapidly that Professor Bigelow could not keep up. “He’s telling of his visit to our camp,” the scientist said. “He perhaps considers it a much-prized experience.” As soon as the chief had finished, the Indians jabbered excitedly, eager to get all the details. Occasionally they would look at the whites as if they considered them super-beings. “They can’t get over the thought that we have higher powers than they have,” mused Bob. “But maybe,” he hesitated, his thoughts going back to the terrible trophy chamber of dried human heads that was one of the tribe’s prized possessions, “it will be just as well to let them go on thinking that way. It would be hard to say when they might turn against us if they thought we were ordinary persons.” “Turn against us?” demanded Mr. Lewis, rather surprised. “What makes you think they would do that? They seem all right.”
  • 59. “Don’t know that they would,” Bob replied, exchanging meaning glances with Joe. “Still it’s wise to be on the safe side.” It was evident that Bob’s significant statement had the men highly puzzled. Finally Professor Bigelow demanded an explanation. “There’s nothing to it—except that these people are headhunters,” said Joe. “If you don’t believe it just take a look at the place where they keep the heads. And say! They’ve killed a couple of white men, too.” Astonished gasps came from Mr. Holton and Mr. Lewis, but not from Professor Bigelow. Anthropologist as he was, he had suspected this from the start. Very few savage tribes in the wilds of Brazil did not have that custom. Suddenly a groan made all turn about, to see that the Indian of the crew who had been wounded by a spear had regained consciousness. His side apparently pained severely, for on his face was a look of agony. Mr. Holton got to work at once. “Ask the chief if we can have some water,” he said to Professor Bigelow. “Bob, suppose you run down to the boats and bring a box of antiseptic. Go as fast as you can. Meanwhile we’ll be taking care of others that were wounded.” Bob grabbed a rifle and dashed off down the path for the stream. He reached the boats in record time and hurriedly got out a box of first-aid materials. Then he made his way back to the village. But he had gone only a few yards when a fluttering noise caused him to look up. At once his jaw dropped in astonishment, and a look of surprise and wonder came on his face.
  • 61. T CHAPTER XXVII Human Heads Still Dripping! HE sight that Bob beheld was one that few hunters and scientists have the opportunity of seeing. Strange sights were common enough in all little-known lands, but this was indeed a wonder of wonders. Not thirty feet in the air a bird resembling an eagle was carrying a half-grown tapir with apparently perfect ease, although the tapir was three times heavier than itself. The tapir was very much alive, as indicated by its writhing movements, but these availed it nothing. It might as well have been caught in an iron vise. For several minutes Bob stared spellbound, taken completely aback. Finally he called himself to action and raised his rifle. “Dad and Mr. Lewis would no doubt welcome the addition of such an unusual specimen as this eagle,” he thought and then pulled the trigger. The report of the gun was immediately followed by the dropping of the bird and its prey. It fluttered about for a moment and then lay still. The tapir had been killed instantly by the fall. Much to Bob’s surprise, the bird could be lifted easily, and he hastened on to the Indian settlement, confident that the naturalists would nearly throw a fit over the strange eagle. And he thought right. Mr. Holton and Mr. Lewis exclaimed in delight and surprise when they caught sight of Bob and the strange creature he was carrying. “Where did you ever find it?” asked Mr. Lewis, and Bob was forced to tell of the entire experience.
  • 62. “The great hairy eagle,” pronounced Mr. Holton, when the youth had finished. “I thought they were confined to the jungles of Guiana, didn’t you, Ben?” he asked of Joe’s father. “Yes,” was the reply. “Never heard of their being found here. Such is unusual indeed. The claws are the most powerful of any known bird.” But there was little time for further examining the specimen, for the wounded Indians needed treatment. The member of the crew was looked after first, and then they turned to the chief’s men, many of whom were seriously wounded. As for those who had been struck by poisoned arrows, treatment was unnecessary, for death had set in long before. The better part of an hour was spent in giving first-aid to the unfortunate savages, and in the end they felt that a large number of lives had been saved by their actions. “But don’t think that the natives have no cure for human ills,” said Professor Bigelow. “The chances are that they know of many remedies that surpass those of civilization in curing properties.” When the task was completed, the Indians invited the whites to come in the main hut and participate in a feast in honor of their ability to drive off the hostile invaders. The invitation was accepted at once, for the explorers were all very hungry. “Wonder what they’ll give us to eat?” asked Joe, as they went into the thatched hut. “Perhaps it’ll be better not to know,” Bob grinned. Whatever it was, however, it tasted good, and they ate heartily of everything. “Now I’m going to get in touch with the chief, whose name I recently learned is Reemikuk,” announced Professor Bigelow. “But first, however, I must have my typewriter. That means a trip to the boats.” “And while he’s doing that, Mr. Lewis and I can have a look about the village,” Bob’s father said. “Perhaps you boys can show us the places and things of interest. Will you do it?”
  • 63. “To be sure we will,” returned Joe. “But first,” he said with a grim smile, “you must prepare yourselves to see things that are unpleasant.” “What do you mean?” his father demanded. For answer the youths led the way to the trophy house and its hideous contents. Impulsively the naturalists shrank back in disgust at the scene. Never had they laid eyes on such a place of horror before. “To think,” muttered Mr. Lewis, “that even these wild people could do such hideous things!” But despite the gruesomeness of the place they spent several minutes there, unable to tear themselves away from its terrible fascination. At last Mr. Holton made for the outside. “Now for something more pleasant,” he said. “What is there, boys?” “Plenty,” answered Joe. “There are games and baskets and carvings and....” All the remainder of that day was spent in examining the many articles of interest made by the simple savages. When at last they went back to the hut that was to be theirs during their stay at the village, they found the professor in earnest conversation with the chief and a witch doctor. The Indians were talking slowly, so that the scientist could pick up every word. He glanced up at the other whites only for a moment, so deeply engrossed was he in what the savages were telling him. “He seems to be enjoying himself immensely,” observed Joe aside to his chum. “No doubt about it,” Bob replied. “And look how the Indians are regarding the typewriter. Probably think it’s another of the whites’ magics.”
  • 64. Professor Bigelow was enjoying himself. Every strange custom of the savages appealed to him as a wonderful item to put in the book he intended to write about the primitive inhabitants of these wild regions. But two days later something happened that, although considered a very interesting custom by the anthropologist, was not to the liking of the other whites. A band of twenty-five warriors had gone into the upper reaches of the river several days before, and now they returned laden with—human heads! “Ugh! Me for the hut,” said Bob, a sickly feeling creeping over him as he viewed the ghastly trophies. And the others, with the exception of Professor Bigelow, felt the same way. The anthropologist, however, seemed to be thoroughly enjoying the terrible scene. “How thrilling a custom!” he said to his friends that night, as they prepared to retire. For answer the others only groaned. But if the explorers thought the mere carrying in of human heads was gruesome, they were to witness something still more terrible before a week would pass.
  • 65. “B CHAPTER XXVIII The Forced Get-away OB!” “Joe!” “Did you see it?” “Yes. Human bones! These savages are cannibals!” It was night—a dark, lowering night. The moon was nowhere in sight. Not a star twinkled down from the heavy jungle sky. Huge, roaring fires blazed in front of the chief’s large hut, while about them danced scores of painted savages, shouting and screaming and gesticulating. It was a scene wild enough to strike terror to the heart of anyone. Bob and Joe gazed fearfully into the raging mob, wondering if the lives of them and their companions would be taken for the feast. The boys moved over to their elders, who were standing at the other side of their thatched dwelling. “Cannibals!” Professor Bigelow was muttering. He had seen too. Mr. Holton and Mr. Lewis nodded, on their faces a grave expression. They were so taken aback as to be almost speechless. “I think perhaps we had better get away from here,” said the professor, who, although deeply attentive to scientific work, knew when he was in a dangerous situation. “I know enough of the ways of primitive people to surmise what they’ll probably do to us if we stay. Their appetites for human flesh will be so stimulated that they will no doubt kill us also. Lucky that this happened as late as it did. I
  • 66. wouldn’t have wanted to leave so soon if I had not secured about all the information there is to be obtained about them.” Just before leaving, Bob and Joe got out their cameras and took motion pictures of the gruesome feast, and in the end they were almost convinced that nothing of this kind had ever been shown on the silver screen. With the aid of flashlights, whose beams, by the way, were concealed from the savages, the explorers had gathered their belongings together and were now ready to leave for the boats. Of course it would be perilous traveling at night through the jungle, but the chance had to be taken. At that moment an Indian entered their hut, glanced about, and then started to call to the others. Displaying a quickness remarkable for his size and weight, Mr. Holton launched himself full force at the fellow, sending him to the ground unconscious. “Now let’s get away—quick!” he said. “There’s no telling when the whole tribe will be in here after us.” As quietly as possible, the explorers and their Indian crew dashed away down the trail for the stream, never looking back, but fearing that they would hear the screams of the cannibals at any moment. The flashlights rendered traveling easy, and as they had been over the trail many times, they reached the boats in record time. Their possessions were piled inside. Then they climbed hastily in and were paddled swiftly away. It was not until they had reached the main stream that they felt safe. Then they turned the boats downstream on the journey back to the coast. “It isn’t wise to tax good fortune too much,” said Mr. Lewis, as the narrow stream faded in the distance. “We came up here for two definite purposes, and we’ve accomplished them both. First, Professor Bigelow has made a rather extensive study of little-known Indians, and second, Mr. Holton and I have collected hundreds of
  • 67. specimens for the museum. You boys have met with success in taking moving pictures, also. Now that our work is finished, we’d better get to the Purús at once.” However, “at once” was a bit too hastily, for there were dangerous rapids that had to be portaged, totally unknown animals that diverted the naturalists’ attention, and a hundred and one reasons for making slow progress, even downstream. But at last they sighted the Purús in the distance. “Now to hunt up Senhor del Pereo, the man who fitted us out with our boats and crew,” said Mr. Holton. They found that individual in his house at the edge of the little town that rested between the two rivers. He was more than glad to see the explorers back after such a long, perilous journey, and insisted that they remain at his house overnight, or until a boat could be found that would take them to the Amazon. The explorers accepted the invitation at once, glad of the chance to partake of the comforts of civilization after those long weeks into the unknown. The next day they were fortunate in getting passage on a boat bound for Manáos. It was a small steamer, scheduled to reach its destination in less than five days. At Manáos the explorers had another streak of good luck, finding a large liner that would take them straight to New York. Down the mighty Amazon they steamed, at last coming into the port at Pará for a short stay. After a walk about town, the Americans again boarded the vessel for the trip to New York. It was an ideal evening as they steamed majestically out of the busy harbor and turned toward the United States. “Do you know, Joe, old boy,” remarked Bob, as they sat with their elders on deck in the light of the full moon, “the farther away we get from the region we explored the more I prize our experience.” Joe nodded.
  • 68. “It was great,” he agreed. “And just think. We were lost—lost in the wilds of Brazil.” Transcriber's Notes The four books in this series have been transcribed in the same manner. This means that in some books, table of contents and or/list of series names have been added. Except in cases of obvious typographical errors, archaic and inconsistent spelling has been retained.
  • 69. *** END OF THE PROJECT GUTENBERG EBOOK LOST IN THE WILDS OF BRAZIL *** Updated editions will replace the previous one—the old editions will be renamed. Creating the works from print editions not protected by U.S. copyright law means that no one owns a United States copyright in these works, so the Foundation (and you!) can copy and distribute it in the United States without permission and without paying copyright royalties. Special rules, set forth in the General Terms of Use part of this license, apply to copying and distributing Project Gutenberg™ electronic works to protect the PROJECT GUTENBERG™ concept and trademark. Project Gutenberg is a registered trademark, and may not be used if you charge for an eBook, except by following the terms of the trademark license, including paying royalties for use of the Project Gutenberg trademark. If you do not charge anything for copies of this eBook, complying with the trademark license is very easy. You may use this eBook for nearly any purpose such as creation of derivative works, reports, performances and research. Project Gutenberg eBooks may be modified and printed and given away—you may do practically ANYTHING in the United States with eBooks not protected by U.S. copyright law. Redistribution is subject to the trademark license, especially commercial redistribution. START: FULL LICENSE
  • 70. THE FULL PROJECT GUTENBERG LICENSE
  • 71. PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK To protect the Project Gutenberg™ mission of promoting the free distribution of electronic works, by using or distributing this work (or any other work associated in any way with the phrase “Project Gutenberg”), you agree to comply with all the terms of the Full Project Gutenberg™ License available with this file or online at www.gutenberg.org/license. Section 1. General Terms of Use and Redistributing Project Gutenberg™ electronic works 1.A. By reading or using any part of this Project Gutenberg™ electronic work, you indicate that you have read, understand, agree to and accept all the terms of this license and intellectual property (trademark/copyright) agreement. If you do not agree to abide by all the terms of this agreement, you must cease using and return or destroy all copies of Project Gutenberg™ electronic works in your possession. If you paid a fee for obtaining a copy of or access to a Project Gutenberg™ electronic work and you do not agree to be bound by the terms of this agreement, you may obtain a refund from the person or entity to whom you paid the fee as set forth in paragraph 1.E.8. 1.B. “Project Gutenberg” is a registered trademark. It may only be used on or associated in any way with an electronic work by people who agree to be bound by the terms of this agreement. There are a few things that you can do with most Project Gutenberg™ electronic works even without complying with the full terms of this agreement. See paragraph 1.C below. There are a lot of things you can do with Project Gutenberg™ electronic works if you follow the terms of this agreement and help preserve free future access to Project Gutenberg™ electronic works. See paragraph 1.E below.
  • 72. 1.C. The Project Gutenberg Literary Archive Foundation (“the Foundation” or PGLAF), owns a compilation copyright in the collection of Project Gutenberg™ electronic works. Nearly all the individual works in the collection are in the public domain in the United States. If an individual work is unprotected by copyright law in the United States and you are located in the United States, we do not claim a right to prevent you from copying, distributing, performing, displaying or creating derivative works based on the work as long as all references to Project Gutenberg are removed. Of course, we hope that you will support the Project Gutenberg™ mission of promoting free access to electronic works by freely sharing Project Gutenberg™ works in compliance with the terms of this agreement for keeping the Project Gutenberg™ name associated with the work. You can easily comply with the terms of this agreement by keeping this work in the same format with its attached full Project Gutenberg™ License when you share it without charge with others. 1.D. The copyright laws of the place where you are located also govern what you can do with this work. Copyright laws in most countries are in a constant state of change. If you are outside the United States, check the laws of your country in addition to the terms of this agreement before downloading, copying, displaying, performing, distributing or creating derivative works based on this work or any other Project Gutenberg™ work. The Foundation makes no representations concerning the copyright status of any work in any country other than the United States. 1.E. Unless you have removed all references to Project Gutenberg: 1.E.1. The following sentence, with active links to, or other immediate access to, the full Project Gutenberg™ License must appear prominently whenever any copy of a Project Gutenberg™ work (any work on which the phrase “Project Gutenberg” appears, or with which the phrase “Project Gutenberg” is associated) is accessed, displayed, performed, viewed, copied or distributed:
  • 73. This eBook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook. 1.E.2. If an individual Project Gutenberg™ electronic work is derived from texts not protected by U.S. copyright law (does not contain a notice indicating that it is posted with permission of the copyright holder), the work can be copied and distributed to anyone in the United States without paying any fees or charges. If you are redistributing or providing access to a work with the phrase “Project Gutenberg” associated with or appearing on the work, you must comply either with the requirements of paragraphs 1.E.1 through 1.E.7 or obtain permission for the use of the work and the Project Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9. 1.E.3. If an individual Project Gutenberg™ electronic work is posted with the permission of the copyright holder, your use and distribution must comply with both paragraphs 1.E.1 through 1.E.7 and any additional terms imposed by the copyright holder. Additional terms will be linked to the Project Gutenberg™ License for all works posted with the permission of the copyright holder found at the beginning of this work. 1.E.4. Do not unlink or detach or remove the full Project Gutenberg™ License terms from this work, or any files containing a part of this work or any other work associated with Project Gutenberg™. 1.E.5. Do not copy, display, perform, distribute or redistribute this electronic work, or any part of this electronic work, without prominently displaying the sentence set forth in paragraph 1.E.1
  • 74. with active links or immediate access to the full terms of the Project Gutenberg™ License. 1.E.6. You may convert to and distribute this work in any binary, compressed, marked up, nonproprietary or proprietary form, including any word processing or hypertext form. However, if you provide access to or distribute copies of a Project Gutenberg™ work in a format other than “Plain Vanilla ASCII” or other format used in the official version posted on the official Project Gutenberg™ website (www.gutenberg.org), you must, at no additional cost, fee or expense to the user, provide a copy, a means of exporting a copy, or a means of obtaining a copy upon request, of the work in its original “Plain Vanilla ASCII” or other form. Any alternate format must include the full Project Gutenberg™ License as specified in paragraph 1.E.1. 1.E.7. Do not charge a fee for access to, viewing, displaying, performing, copying or distributing any Project Gutenberg™ works unless you comply with paragraph 1.E.8 or 1.E.9. 1.E.8. You may charge a reasonable fee for copies of or providing access to or distributing Project Gutenberg™ electronic works provided that: • You pay a royalty fee of 20% of the gross profits you derive from the use of Project Gutenberg™ works calculated using the method you already use to calculate your applicable taxes. The fee is owed to the owner of the Project Gutenberg™ trademark, but he has agreed to donate royalties under this paragraph to the Project Gutenberg Literary Archive Foundation. Royalty payments must be paid within 60 days following each date on which you prepare (or are legally required to prepare) your periodic tax returns. Royalty payments should be clearly marked as such and sent to the Project Gutenberg Literary Archive Foundation at the address specified in Section 4, “Information
  • 75. about donations to the Project Gutenberg Literary Archive Foundation.” • You provide a full refund of any money paid by a user who notifies you in writing (or by e-mail) within 30 days of receipt that s/he does not agree to the terms of the full Project Gutenberg™ License. You must require such a user to return or destroy all copies of the works possessed in a physical medium and discontinue all use of and all access to other copies of Project Gutenberg™ works. • You provide, in accordance with paragraph 1.F.3, a full refund of any money paid for a work or a replacement copy, if a defect in the electronic work is discovered and reported to you within 90 days of receipt of the work. • You comply with all other terms of this agreement for free distribution of Project Gutenberg™ works. 1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™ electronic work or group of works on different terms than are set forth in this agreement, you must obtain permission in writing from the Project Gutenberg Literary Archive Foundation, the manager of the Project Gutenberg™ trademark. Contact the Foundation as set forth in Section 3 below. 1.F. 1.F.1. Project Gutenberg volunteers and employees expend considerable effort to identify, do copyright research on, transcribe and proofread works not protected by U.S. copyright law in creating the Project Gutenberg™ collection. Despite these efforts, Project Gutenberg™ electronic works, and the medium on which they may be stored, may contain “Defects,” such as, but not limited to, incomplete, inaccurate or corrupt data, transcription errors, a copyright or other intellectual property infringement, a defective or
  • 76. damaged disk or other medium, a computer virus, or computer codes that damage or cannot be read by your equipment. 1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for the “Right of Replacement or Refund” described in paragraph 1.F.3, the Project Gutenberg Literary Archive Foundation, the owner of the Project Gutenberg™ trademark, and any other party distributing a Project Gutenberg™ electronic work under this agreement, disclaim all liability to you for damages, costs and expenses, including legal fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE. 1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a defect in this electronic work within 90 days of receiving it, you can receive a refund of the money (if any) you paid for it by sending a written explanation to the person you received the work from. If you received the work on a physical medium, you must return the medium with your written explanation. The person or entity that provided you with the defective work may elect to provide a replacement copy in lieu of a refund. If you received the work electronically, the person or entity providing it to you may choose to give you a second opportunity to receive the work electronically in lieu of a refund. If the second copy is also defective, you may demand a refund in writing without further opportunities to fix the problem. 1.F.4. Except for the limited right of replacement or refund set forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
  • 77. INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PURPOSE. 1.F.5. Some states do not allow disclaimers of certain implied warranties or the exclusion or limitation of certain types of damages. If any disclaimer or limitation set forth in this agreement violates the law of the state applicable to this agreement, the agreement shall be interpreted to make the maximum disclaimer or limitation permitted by the applicable state law. The invalidity or unenforceability of any provision of this agreement shall not void the remaining provisions. 1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the trademark owner, any agent or employee of the Foundation, anyone providing copies of Project Gutenberg™ electronic works in accordance with this agreement, and any volunteers associated with the production, promotion and distribution of Project Gutenberg™ electronic works, harmless from all liability, costs and expenses, including legal fees, that arise directly or indirectly from any of the following which you do or cause to occur: (a) distribution of this or any Project Gutenberg™ work, (b) alteration, modification, or additions or deletions to any Project Gutenberg™ work, and (c) any Defect you cause. Section 2. Information about the Mission of Project Gutenberg™ Project Gutenberg™ is synonymous with the free distribution of electronic works in formats readable by the widest variety of computers including obsolete, old, middle-aged and new computers. It exists because of the efforts of hundreds of volunteers and donations from people in all walks of life. Volunteers and financial support to provide volunteers with the assistance they need are critical to reaching Project Gutenberg™’s goals and ensuring that the Project Gutenberg™ collection will
  • 78. remain freely available for generations to come. In 2001, the Project Gutenberg Literary Archive Foundation was created to provide a secure and permanent future for Project Gutenberg™ and future generations. To learn more about the Project Gutenberg Literary Archive Foundation and how your efforts and donations can help, see Sections 3 and 4 and the Foundation information page at www.gutenberg.org. Section 3. Information about the Project Gutenberg Literary Archive Foundation The Project Gutenberg Literary Archive Foundation is a non-profit 501(c)(3) educational corporation organized under the laws of the state of Mississippi and granted tax exempt status by the Internal Revenue Service. The Foundation’s EIN or federal tax identification number is 64-6221541. Contributions to the Project Gutenberg Literary Archive Foundation are tax deductible to the full extent permitted by U.S. federal laws and your state’s laws. The Foundation’s business office is located at 809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up to date contact information can be found at the Foundation’s website and official page at www.gutenberg.org/contact Section 4. Information about Donations to the Project Gutenberg Literary Archive Foundation Project Gutenberg™ depends upon and cannot survive without widespread public support and donations to carry out its mission of increasing the number of public domain and licensed works that can be freely distributed in machine-readable form accessible by the widest array of equipment including outdated equipment. Many
  • 79. small donations ($1 to $5,000) are particularly important to maintaining tax exempt status with the IRS. The Foundation is committed to complying with the laws regulating charities and charitable donations in all 50 states of the United States. Compliance requirements are not uniform and it takes a considerable effort, much paperwork and many fees to meet and keep up with these requirements. We do not solicit donations in locations where we have not received written confirmation of compliance. To SEND DONATIONS or determine the status of compliance for any particular state visit www.gutenberg.org/donate. While we cannot and do not solicit contributions from states where we have not met the solicitation requirements, we know of no prohibition against accepting unsolicited donations from donors in such states who approach us with offers to donate. International donations are gratefully accepted, but we cannot make any statements concerning tax treatment of donations received from outside the United States. U.S. laws alone swamp our small staff. Please check the Project Gutenberg web pages for current donation methods and addresses. Donations are accepted in a number of other ways including checks, online payments and credit card donations. To donate, please visit: www.gutenberg.org/donate. Section 5. General Information About Project Gutenberg™ electronic works Professor Michael S. Hart was the originator of the Project Gutenberg™ concept of a library of electronic works that could be freely shared with anyone. For forty years, he produced and distributed Project Gutenberg™ eBooks with only a loose network of volunteer support.
  • 80. Project Gutenberg™ eBooks are often created from several printed editions, all of which are confirmed as not protected by copyright in the U.S. unless a copyright notice is included. Thus, we do not necessarily keep eBooks in compliance with any particular paper edition. Most people start at our website which has the main PG search facility: www.gutenberg.org. This website includes information about Project Gutenberg™, including how to make donations to the Project Gutenberg Literary Archive Foundation, how to help produce our new eBooks, and how to subscribe to our email newsletter to hear about new eBooks.
  • 81. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com