(Ebook) Android Cookbook by Ian F. Darwin ISBN 9781449374457, 144937445X
(Ebook) Android Cookbook by Ian F. Darwin ISBN 9781449374457, 144937445X
(Ebook) Android Cookbook by Ian F. Darwin ISBN 9781449374457, 144937445X
(Ebook) Android Cookbook by Ian F. Darwin ISBN 9781449374457, 144937445X
1. Visit ebooknice.com to download the full version and
explore more ebooks or textbooks
(Ebook) Android Cookbook by Ian F. Darwin ISBN
9781449374457, 144937445X
_____ Click the link below to download _____
https://ebooknice.com/product/android-cookbook-5903428
Explore and download more ebooks or textbooks at ebooknice.com
2. Here are some recommended products that we believe you will be
interested in. You can click the link to download.
(Ebook) Android Cookbook by Ian F. Darwin ISBN 9781449388416,
1449388418
https://ebooknice.com/product/android-cookbook-2322658
(Ebook) Android Cookbook: Problems and Solutions for Android
Developers by Ian F. Darwin ISBN 9781449374433, 1449374433
https://ebooknice.com/product/android-cookbook-problems-and-solutions-
for-android-developers-5908798
(Ebook) Java Cookbook by Ian F. Darwin ISBN 9781449337049, 144933704X
https://ebooknice.com/product/java-cookbook-4703652
(Ebook) Java Cookbook by Ian F. Darwin ISBN 9781492072584, 1492072583
https://ebooknice.com/product/java-cookbook-32607846
3. (Ebook) Java Cookbook by Ian F. Darwin ISBN 9780596001704, 0596001703
https://ebooknice.com/product/java-cookbook-920270
(Ebook) Java Cookbook - Problems and Solutions for Java Developers
(Early Release) by Ian F. Darwin
https://ebooknice.com/product/java-cookbook-problems-and-solutions-
for-java-developers-early-release-10538990
(Ebook) Java Cookbook - Problems and Solutions for Java Developers
(final release). by Ian F. Darwin ISBN 9781492072584, 1492072583
https://ebooknice.com/product/java-cookbook-problems-and-solutions-
for-java-developers-final-release-10868760
(Ebook) Tomcat. The Definitive Guide by Jason Brittain, Ian F. Darwin
ISBN 9780596101060, 0596101066
https://ebooknice.com/product/tomcat-the-definitive-guide-1021542
(Ebook) Professional Android by Reto Meier, Ian Lake
https://ebooknice.com/product/professional-android-7195564
9. Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
1. Getting Started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.1 Understanding the Android Application Architecture 17
1.2 Understanding the Android Activity Life Cycle 19
1.3 Learning About Android Releases 21
1.4 Learning the Java Language 23
1.5 Creating a “Hello, World” Application from the Command Line 24
1.6 Creating a “Hello, World” App with Apache Maven 29
1.7 Choosing an IDE for Android Development 31
1.8 Setting Up Android Studio 34
1.9 Creating a “Hello, World” App using Android Studio 37
1.10 Converting an Eclipse ADT Project to Android Studio 44
1.11 Preserving History while Converting from Eclipse to Android Studio 48
1.12 Setting Up Eclipse with AndMore (Replacing ADT) 50
1.13 Creating a “Hello, World” Application using Eclipse 59
1.14 Installing the Eclipse Marketplace Client in your Eclipse 66
1.15 Upgrading a Project from Eclipse ADT to Eclipse AndMore 71
1.16 Using Java 8 Features in Android Studio 2 74
1.17 Controlling Emulators/Devices Using Command-Line ADB 76
1.18 Sharing Java Classes from Another Eclipse Project 80
1.19 Referencing Libraries to Implement External Functionality 83
1.20 Using New Features on Old Devices via the Compatibility Libraries 88
1.21 Using SDK Samples to Help Avoid Head Scratching 90
1.22 Taking a Screenshot/Video from the Emulator/Android Device 93
1.23 Program: A Simple CountDownTimer Example 99
1.24 Program: Tipster, a Tip Calculator for the Android OS 102
iii
10. 2. Designing a Successful Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
2.1 Exception Handling 124
2.2 Requesting Android Permissions at Run Time 128
2.3 Accessing Android’s Application Object as a “Singleton” 130
2.4 Keeping Data When the User Rotates the Device 132
2.5 Monitoring the Battery Level of an Android Device 135
2.6 Creating Splash Screens in Android 136
2.7 Designing a Conference/Camp/Hackathon/Institution App 141
2.8 Using Google Analytics in an Android Application 142
2.9 Setting First-Run Preferences 145
2.10 Formatting the Time and Date for Display 147
2.11 Simplifying Date/Time Calculations with the Java 8 java.time API 149
2.12 Controlling Input with KeyListeners 151
2.13 Backing Up Android Application Data 155
2.14 Using Hints Instead of Tool Tips 161
3. Application Testing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
3.1 Setting Up an Android Virtual Device (AVD) for App Testing 166
3.2 Testing on a Huge Range of Devices with Cloud-based Testing 175
3.3 Testing with Eclipse and JUnit 176
3.4 Testing with Android Studio and JUnit 180
3.5 Testing with Robolectric and JUnit 4 186
3.6 Testing with ATSL, Espresso and JUnit 4 188
3.7 Troubleshooting Application Crashes 193
3.8 Debugging Using Log.d and LogCat 196
3.9 Getting Bug Reports Automatically with Crash Reporting 198
3.10 Using a Local Runtime Application Log for Analysis of Field Errors or
Situations 201
3.11 Reproducing Activity Life-Cycle Scenarios for Testing 205
3.12 Keeping Your App Snappy with StrictMode 211
3.13 Static Code Testing with Android Lint 212
3.14 Dynamic Testing with the Monkey Program 214
3.15 Sending Text Messages and Placing Calls Between AVDs 216
4. Inter-/Intra-Process Communication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
4.1 Opening a Web Page, Phone Number, or Anything Else with an Intent 219
4.2 Emailing Text from a View 222
4.3 Sending an Email with Attachments 225
4.4 Pushing String Values Using Intent.putExtra() 226
4.5 Retrieving Data from a Sub-Activity Back to Your Main Activity 227
4.6 Keeping a Background Service Running While Other Apps Are on Display 230
4.7 Sending/Receiving a Broadcast Message 232
iv | Table of Contents
11. 4.8 Starting a Service After Device Reboot 233
4.9 Creating a Responsive Application Using Threads 234
4.10 Using AsyncTask to Do Background Processing 236
4.11 Sending Messages Between Threads Using an Activity Thread Queue and
Handler 244
4.12 Creating an Android Epoch HTML/JavaScript Calendar 245
5. Graphics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
5.1 Using a Custom Font 253
5.2 Drawing a Spinning Cube with OpenGL ES 256
5.3 Adding Controls to the OpenGL Spinning Cube 260
5.4 Freehand Drawing Smooth Curves 263
5.5 Taking a Picture Using an Intent 268
5.6 Taking a Picture Using android.media.Camera 270
5.7 Scanning a Barcode or QR Code with the Google ZXing Barcode Scanner 274
5.8 Using AndroidPlot to Display Charts and Graphs 277
5.9 Using Inkscape to Create an Android Launcher Icon 280
5.10 Creating Easy Launcher Icons from OpenClipArt.org Using Paint.NET 287
5.11 Using Nine Patch Files 294
5.12 Creating HTML5 Charts with Android RGraph 298
5.13 Adding a Simple Raster Animation 302
5.14 Using Pinch to Zoom 306
6. Graphical User Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
6.1 Understanding and Following User Interface Guidelines 312
6.2 Looking Good with Material Design 313
6.3 Choosing a Layout Manager (ViewGroup) and Arranging Components 320
6.4 Handling Configuration Changes by Decoupling the View from the Model 321
6.5 Controlling the Action Bar 325
6.6 Adding a Share Action to your action bar 329
6.7 Building Modern UIs with the Fragment API 339
6.8 Creating a Button and Its Click Event Listener 344
6.9 Enhancing UI Design Using Image Buttons 345
6.10 Using FloatingActionButton 347
6.11 Wiring Up an Event Listener in Five Different Ways 350
6.12 Using CheckBoxes and RadioButtons 355
6.13 Using Card Widgets 359
6.14 Offering a Drop-Down Chooser via the Spinner Class 363
6.15 Handling Long-Press/Long-Click Events 366
6.16 Displaying Text Fields with TextView and EditText 367
6.17 Constraining EditText Values with Attributes and the TextWatcher
Interface 368
Table of Contents | v
12. 6.18 Implementing AutoCompleteTextView 371
6.19 Feeding AutoCompleteTextView Using an SQLite Database Query 373
6.20 Turning Edit Fields into Password Fields 375
6.21 Changing the Enter Key to “Next” on the Soft Keyboard 376
6.22 Processing Key-Press Events in an Activity 379
6.23 Let Them See Stars: Using RatingBar 380
6.24 Making a View Shake 384
6.25 Providing Haptic Feedback 386
6.26 Navigating Different Activities Within a TabView 389
6.27 Formatting Numbers 391
6.28 Formatting with Correct Plurals 395
6.29 Creating a Loading Screen That Will Appear Between Two Activities 398
6.30 Adding a Border with Rounded Corners to a Layout 400
6.31 Detecting Gestures in Android 402
6.32 Creating a Simple App Widget 409
vi | Table of Contents
13. To Dennis M. Ritchie (1941–2011), language pioneer and co-inventor of Unix, who
showed us all where the braces go, reminded us to keep it simple, and gave us so much
more…
15. Preface
===
Ian Darwin
Android is “the open source revolution” applied to cellular telephony and mobile
computing. At least, part of the revolution. There have been many other attempts to
provide open source cell phones, most of them largely defunct, ranging from the
Openmoko FreeRunner to QT Embedded, Moblin, LiMo, Debian Mobile, Maemo,
FireFox OS, Ubuntu Mobile to the open sourced Symbian OS and the now-defunct
HP WebOS. Let’s not forget the established closed source stalwart Apple’s iOS, and
the two minor players (by market share), Microsoft Windows Mobile and the
recently-abandoned BlackBerry OS 10 (both of these have developer toolkits, but
their OS is not available as open source and often has other “click-wrap” restrictions).
Amongst all these offerings, two stand out as major players. Android is definitely
here to stay! This book is here to help the Android developer community share the
knowledge that will help make better apps. Those who contribute knowledge here are
helping to make Android development easier for those who come after.
About Android
Android is a mobile technology platform that provides cell phones, tablets, and other
handheld and mobile devices (even netbooks) with the power and portability of the
Linux operating system and the reliability and portability of a standard high-level
language and API and a vast ecosystem of useful applications. Android apps are
mostly written in the Java language, using tools such as Eclipse and Android Studio,
compiled against the Android API, and translated into bytecode for an Android-
specific VM.
Android is thus related by OS family to other Linux-based cell phone projects.
Android is also related by programming language to BlackBerry’s older Java ME
phones, and to Java and the wider realm of Java Enterprise applications. Not to men‐
ix
16. tion that all current Blackberry devices can run Android applications, and in fact
Blackberry’s newest devices only run Android.
It’s now generally believed that Android has almost three-quarters of the world
smartphone market, although it has not nearly displaced Apple’s iPad in the tablet
market. Sales figures change all the time, but it is clear that Android is, and will
remain, one of the dominant players in the mobile space.
Who This Book Is By
This book was written by several dozen Android developers from the Android com‐
munity at large. Development occurred in the open, on the website http://androidcook
book.com/, which I built (using Java of course) to allow people to contribute, view,
review, and comment on the recipes that would make up this book. A complete list
can be found in “Acknowledgments” on page xv. I am deeply grateful to all the con‐
tributors, who have helped moved this book from a dream to the reality that you have
in your hands (or on-screen if you are reading the ebook format). Thank you all!
Who This Book Is For
This book focusses on building Android applications using Java, the native language
of Android applications. It is of course possible to package up a web application as a
mobile app (see ???), but you will never get the all-important 100%-correct user expe‐
rience with all the current features of Android that way.
So. Java. We assume you know the basics of the Java language. If not, see Recipe 1.4.
We also assume you know the basics of the Java Standard Edition API (since this
forms the basis of Android’s runtime libraries) as well as the basics of Android. The
terms activity, intent, service, and content provider, while not necessarily being what
you dream about at night, should at least be familiar to you. But if not, we’ve got you
covered: see Recipe 1.2.
This book differs from the Android Samples assocated with the Android SDK in that
it tries to focus more on how a given piece of technology works, rather than by giving
you (as the Samples do) a complete, working, example that has both been simplified
(to use very simple data) but complicated by adding in several “neat” features that are
irrelevant to the problem at hand.
What’s in This Book?
Chapter 1 takes you through the steps of setting up the Android development envi‐
ronment and building several simple applications of the well-known “Hello, World”
type pioneered by Brian Kernighan.
x | Preface
17. Chapter 2 covers some of the differences in mobile computing that will hit developers
coming from desktop and enterprise software environments, and talks about how
mobile design (in particular, Android design) differs from those other environments.
Testing is often an afterthought for some developers, so we discuss this early on, in
Chapter 3. Not so that you’ll skip it, but so that you’ll read and heed. We talk about
unit testing individual components as well as testing out your entire application in a
well-controlled way.
Android provides a variety of mechanisms for communicating within an application
and across applications. In Chapter 4 we discuss intents and broadcast receivers, serv‐
ices, AsyncTasks, and handlers.
Chapter 5 covers a range of topics related to graphics, including use of the graphical
drawing and compositing facilities in Android as well as using desktop tools to
develop graphical images, textures, icons, and so on that will be incorporated into
your finished application.
Every mobile app needs a GUI, so Chapter 6 covers the main ins and outs of GUI
development for Android. Examples are given both in XML and, in a few cases, in
Java-coded GUI development.
??? covers all the pop-up mechanisms—menus, dialogs, and toasts—and one that
doesn’t pop up but is also for interaction outside your application’s window, Android’s
notification mechanism.
Lists of items are very common in mobile applications on all platforms. ??? focuses on
the “list” components in Android, the ListView and its newer replacement the
RecyclerView.
Android is rich in multimedia capabilities. ??? shows how to use the most important
of these.
??? shows how to save data into files, databases, and so on. And how to retrieve it
later, of course. Another communication mechanism is about allowing controlled
access to data that is usually in an SQL database. This chapter also shows you how to
make application data available to other applications through something as simple
but ubiquitous (in Android) as the URL, and how to use various cloud-based services
to store data.
Android started out as an operating system for mobile telephones. ??? shows how to
control and react to the telephone device that is in most mobile devices nowadays.
Mobile devices are, for the most part, always-on and always-connected. This has a
major impact on how people use them and think about them. ??? shows the coding
for traditional networked applications. This is followed by ???, and ???.
Preface | xi
18. The now-ubiquitous Global Positioning System has also had a major impact on how
mobile applications work. ??? discusses how to find your location, how to get map
data from Google and OpenStreetMap, and how applications can be location-aware
in ways that are just now being explored.
??? talks about the sensors built into most Android devices and how to use them.
??? talks about the low-energy very-local area networking that Bluetooth enables,
going beyond connecting your Bluetooth headset to your phone.
Android devices are perhaps unique in how much control they give the developer.
Some of these angles are explored in ???. Since Android is Linux-based, a few of the
recipes in this chapter deal with traditional Unix/Linux commands and facilities.
In ???, we explore the use of other programming languages to write all or part of your
Android application. Examples include C, Perl, Python, Lisp, and other languages.
While this edition of this book is in English, and English remains the number-one
technical language worldwide, it is far from the only one. Most end users would
rather have an application that has its text in their language and its icons in a form
that is culturally correct for them. ??? goes over the issues of language and culture and
how they relate to Android.
Most Android developers hope other people will use their applications. But this won’t
happen if users can’t find the applications. ??? shows how to prepare your application
for distribution via the Android Market, and to use that as well as other markets to
get your application out to the people who will use it.
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 ele‐
ments 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.
xii | Preface
19. This icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.
And here is our first caution: the term “I” used in a given recipe
reflects the opinions or experience of that recipe’s contributor, not
necessarily of the book’s editor.
Getting and Using the Code Examples
The code examples in this book vary from a few lines pasted from a complete applica‐
tion, through to fully working apps. For those at the “few lines” end of the spectrum,
you should not expect to be able to compile them from what we provide; these are
intended to be merged into your application. All the examples that we have code for
and that are compilable have been merged into a single GitHub repository, which is
the recommended way of getting the source code and keeping it up to date. This reposi‐
tory can be accessed at https://github.com/IanDarwin/Android-Cookbook-Examples.
Each directory in the repo contains one example program’s project. As you will see if
you visit this page, GitHub allows you to check out the source repository using the
git clone command. As well, the web page offers the option to download the entire
repository as a single (large) ZIP file as well as to browse portions of the repository in
a web browser. Using git will allow you to receive corrections and updates, but the
ZIP will download more quickly.
Contributors of each recipe also have the option to provide a download URL for their
source code, hosted on some other public repository. These are listed both as a hyper‐
link for eBook users and as a QR-format barcode for downloading from the printed
edition. These URLs are included at the end of each recipe. In each case the archive
file is expected to contain a complete Eclipse project. We have no control over these
other repositories, so if one of them is incomplete, or stops working, please refer to
the GitHub repository instead.
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
Preface | xiii
20. permission. Selling or distributing a CD-ROM of examples from O’Reilly books does
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 Cookbook, edited by Ian F.
Darwin (O’Reilly). Copyright 2016 O’Reilly Media, Inc., 978-1-449-37443-3.”
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us at permissions@oreilly.com.
Safari® Books Online
Safari Books Online is an on-demand digital library that lets you
easily search over 7,500 technology and creative reference books
and videos to find the answers you need quickly.
With a subscription, you can read any page and watch any video from our library
online. Read books on your cell phone and mobile devices. Access new titles before
they are available for print, and get exclusive access to manuscripts in development
and post feedback for the authors. Copy and paste code samples, organize your favor‐
ites, download chapters, bookmark key sections, create notes, print out pages, and
benefit from tons of other time-saving features.
O’Reilly Media has uploaded this book to the Safari Books Online service. To have
full digital access to this book and others on similar topics from O’Reilly and other
publishers, sign up 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)
xiv | Preface
21. We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at:
http://shop.oreilly.com/product/0636920038092.do
To comment or ask technical questions about this book, send email to:
bookquestions@oreilly.com
For more information about our books, courses, conferences, and news, see our web‐
site at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments
I would like to thank the dozens of people from the Android community at large who
contributed so many of the recipes in the first edition of this book: Amir Alagic, Jim
Blackler, Luis Vitorio Cargnini, Rupesh Chavan, Adrian Cowham, Nidhin Jose Davis,
Wagied Davids, David Dawes, Enrique Diaz, Marco Dinacci, Claudio Esperanca, Kur‐
osh Fallahzadeh, Daniel Fowler, Jonathan Fuerth, Sunit Katkar, Roger Kind Kristian‐
sen, Vladimir Kroz, Alex Leffelman, Ulysses Levy, Thomas Manthey, Emaad Man‐
zoor, Keith Mendoza, Roberto Calvo Palomino, Federico Paolinelli, Johan Pelgrim,
Catarina Reis, Mike Rowehl, Pratik Rupwal, Oscar Salguero, Ashwini Shahapurkar,
Shraddha Shravagi, Rachee Singh, Saketkumar Srivastav, Corey Sunwold, Kailuo
Wang, and Colin Wilcox.
Thanks to Mike Way who contributed the Permissions recipe Recipe 2.2 for the Sec‐
ond Edition, and Daniel Fowler for updating several of his recipes to coincide with
the Second Edition.
I must also mention the many people at O’Reilly who have helped shape this book,
including my editors Mike Loukides, Courtney Nash, Meghan Blanchette and Dawn
Schanafelt; Adam Witwer and Sarah Schneider in production; production editor Ter‐
esa Elsey, who shepherded the whole production process; external copy editor Audrey
Doyle, who painstakingly read every word and phrase; Stacie Arellano, who proof‐
read it all again; Lucie Haskins, who added index terms to all those recipes; designers
Karen Montgomery and David Futato; illustrators Robert Romano and Rebecca
Demarest; and anyone whom I’ve neglected to mention—you know who you are!
My late son Andrej Darwin helped with some administrative tasks late in the recipe
editing phase of the first edition. Thanks to all my family for their support.
Preface | xv
22. Finally, a note of thanks to my two technical reviewers, Greg Ostravich and Zettie
Chinfong, without whom there would be many more errors and omissions than the
ones that doubtless remain. Rick Isaacs made another pass and tested many recipes.
Thanks also to the many people who pointed out minor errors and omissions in the
first printing of the book, especially Anto Jurkovic and Joseph C. Eddy; most of these
have been corrected at this time. The errors which surely remain are my own.
To all of the above, thank you!
Content Updates
Second Edition, June 2016
Major revision for Android Nougat (7.x). As befits a major revision, there are numer‐
ous new recipes to cover all the new (and a few replaced) APIs over the past several
releases of Android.
xvi | Preface
23. CHAPTER 1
Getting Started
The famous “Hello, World” pattern came about when Kernighan and Plaugher
wanted to write a “recipe” on how to get started in any new programming language
and environment. Their idea was that, if you could get a computer program to print
out “Hello World”, then you had mastered how to use the system in general, how to
create/edit a program’s source code, compile/translate/process it into a runnable pro‐
gram as needed, and run it. And once you’d done that you could, with elaboration,
make the computer do anything! This chapter is affectionately dedicated to these fine
gentlemen, and to everyone who has ever struggled to get started in a new program‐
ming paradigm.
This chapter is a smorgasbord of “how to get started” recipes. We show you how to
create and build an Android app using almost no tooling, using Apache Maven, using
Eclipse, using Gradle, and using Android Studio. Nobody will regularly use all these
techniques, but we chose to cover them all because some readers will like each way of
doing things. Feel free to pick and choose, and try different ways of working on your
application!
1.1 Understanding the Android Application Architecture
Ian Darwin
Problem
An Android application consists of many “moving parts” whose natures and interac‐
tions need to be understood in order to develop effectively.
17
24. Discussion
An Android application consists of one or more of the following components, written
as Java classes:
• An Activity comprises the visual components (”Views”) for one screen as well as
the code that can respond to user events on that screen. Almost every application
has at least one Activity class.
• A Service is a component that has no user interface, and can run for a longer
period of time than an Activity. Two main uses for Services are long-running
tasks (such as a music player), and running medium-length tasks without tying
up the user-interface thread.
• Broadcast Receivers are less common, and are used to respond to system-wide
events such as the network losing or regaining connectivity, the battery running
low, the system rebooting, and so on.
• Content Providers are also relatively rare, and are used when one application
needs to share its data with other applications; they can also be used with Sync
Adapters (see below);
• Sync Adapters synchronize data with cloud services; the best-known examples
are the Contacts and Calendar on the device, which can easily be synchronized to
your Google account.
Your code does not create these objects using the new operator, as in conventional
Java, but requests their invocation using an Intent, an object that specifies your
intention to have something done. Intents can start activities within your application
(by class name), start activities in other applications (by specifying content type and
other information), start services, and request other operations. The interactions
among these components are outlined in Figure 1-1.
18 | Chapter 1: Getting Started
26. But while a jest may be pardonable in such a case, this losing one's
head too often takes place in circumstances involving loss of life or
property. An excited pitying crowd, for example, is gathered round a
person struck in the street with apoplexy. An alarm has been given,
and a curious gaping group has come to witness a case of suicide by
hanging. A concourse of people stand before a house from which
issue the first symptoms of a fire. In such cases the spectators are
usually nerveless and purposeless: the danger to life or property is in
the exact ratio of the number of onlookers. How curious and
instructive to note the change which comes over the scene on the
arrival of a single sensible and self-possessed person. One of the idle
sympathisers of the apoplectic patient suddenly frees the neck and
chest; a second goes sanely in search of temporary appliances; a
third runs zealously for a doctor, and the remainder go about their
business. One stroke of a knife and the would-be suicide has been
placed in the hands of a few of the more intelligent by-standers for
resuscitation. The precise locality of the fire has been reached, and
the fire either extinguished promptly with the means at hand, or
kept under until the arrival of the fire-engines which have been at
once sent for.
Now, what is the real source of this exceptional self-possession—so
all-important in an emergency? Is it not, after all, the quiet
confidence begot of knowing what is best and proper to be done
under given circumstances? It is quite true, no doubt, that presence
of mind is a moral quality more or less independent of technical
knowledge, but in a plain practical way it is directly its result. To
become familiar with difficulties is to divest them of their character
as such, and to enable us to act with all the coolness and precision
exercised in ordinary events. To a surgeon, an accident is a 'case,'
not an 'emergency;' while even an abstract knowledge of 'what to
do' arms the mind of the non-professional against excitement or
confusion. The possession of one little fact, the recollection of some
read or heard of device or remedy, is often, sufficient to steady the
mind and enable it to act effectively. How frequently some half-
forgotten item of surgical knowledge, some stray prescription, or
27. some plan casually recommended ever so long ago, is the means,
here and there, of eluding the fatal possibilities of an emergency.
There is really little excuse for ignorance of the means and methods
required to meet ordinary cases, seeing that information in
abundance is to be had at trifling cost and with little trouble. There
are surgical and medical works, published at almost nominal prices,
the expressed aim of which is to instruct the public what steps to
take in most kinds of accidents, in the absence of professional
assistance. There are works also which, treating mainly of household
matters, contain valuable hints to parents and others on the subject
of accidents to children, as also of fires to person and property;
while here and there in our serial literature may be found useful
advice on such special kinds of emergencies as the bolting of horses,
capsizing of boats, bites by poisonous snakes, &c. But above all, to
those who care to remember what they read, the columns of the
daily newspapers afford much sound instruction in every species of
untoward event. In spite, however, of the ease with which people
might inform themselves, and in spite of frequently bitter
experience, there is a very general apathy regarding such matters.
In upper and middle class families, a certain amount of interest is no
doubt evinced, and books of reference are found in their libraries;
but the practical importance of knowing their contents, and so
forearming against contingencies, is by no means widely recognised.
It is scarcely surprising then to find the masses so indifferent, and as
a consequence so helpless to assist themselves or each other in any
unusual situation.
The idea of giving the subject some place in the common school
course is one, we think, worthy of consideration. Physical education
receives a fair share of encouragement in the higher class of
schools; and some of the exercises enjoined, such as running,
climbing, swimming, and rowing, are direct provisions against
accidents by field or water; while all of them, by giving a degree of
confidence to the mind, are of the greatest value as a training to
meet emergencies generally. Physiology too is gradually making
good its claim to the attention of teachers; and the instruction in
28. Domestic Economy prescribed for girls comprises hints how to act in
what may be called household emergencies. All this is very
satisfactory; and were some pains taken in addition to point out to
pupils of both sexes the commoner dangers by which life is beset,
and were they told in a plain practical way how these are best
averted, we believe the case would be very fairly met. To the skilled
teacher, a short series of lessons of this kind would not necessarily
be any great tax upon his time, but would rather form one of the
most interesting of those 'asides' to which he properly resorts as an
occasional relief to the tedium of school-routine.
To children of a larger growth, we can only repeat that the means of
informing themselves are not beyond reach. There are, of course,
now and then such combinations of circumstances as no knowledge
or training can provide for, just as there are many accidents which
no human foresight can prevent. Leaving these out of the question,
however, few of us pass through life without having at one time or
other to exercise our intelligence and knowledge to preserve either
our own life or property, or the life or property of others in
circumstances where these may be exercised successfully. Our
interest and duty alike enjoin us to take reasonable pains to forearm
ourselves, and the neglect to do so is clearly culpable. But we may
have occasion by and by to present our readers with a few practical
hints on the subject of 'What to do in Emergencies.'
29. THE TRADE IN ARTIFICIAL EYES.
On this subject, the New York Sun gives some amusing particulars:
'Between eight and ten thousand eyes are sold annually in the
United States. An eye-maker gives one in one hundred and twenty-
five as the proportion of one-eyed people. Computing the population
of the country at forty-two millions, this rate gives three hundred
and thirty-six thousand as the number of persons with only one eye
in the Republic. Consequently, while ten thousand people supply
their optical deficiency with an artificial eye, two hundred and
twenty-six thousand go without. In proportion to the population, the
eye-maker said, there are more one-eyed people in Paterson, New
Jersey, than any other town in this or any other country. All towns
that have many foundries and factories, and whose air is
impregnated with soot and smoke, count their one-eyed inhabitants
by the score; but Paterson is ahead of the rest. The eye-maker knew
of the three proprietors of a single foundry there each losing an eye.
Pittsburg comes next. In this city one-eyed folks abound in the
neighbourhood of manufacturing establishments. Once he had four
patients from near a foundry in West Eleventh Street alone. Not only
the foul atmosphere destroys the sight, but flying pieces of metal
burn out the eyes of the workmen. An importer who sells one
thousand five hundred eyes annually sends one-third to Canada;
Chicago takes three hundred; and Cincinnati more than St Louis.
New Orleans, Nashville, and other towns west and south buy the
remainder. The colour for eyes most in demand is what is known as
"Irish blue," a peculiarly light azure that predominates in Ireland.
The average cost of an eye is ten dollars. He sells comparatively few
eyes in this city, as New Yorkers prefer to have their eyes made to
order.'
30. A NOBLE OCCUPATION.
A newspaper records as follows: 'The Duke of Hamilton left Hamilton
Palace for the south yesterday. During his stay of six days he shot
373½ brace of grouse, 4 brace of black-game, 4 hares, and 2
snipes.' This makes a slaughter of seven hundred and sixty-one
animals in six days, or at an average upwards of a hundred and
twenty-six per diem. Hard work!
Printed and Published by W. & R. Chambers, 47 Paternoster Row,
London, and 339 High Street, Edinburgh.
All Rights Reserved.
FOOTNOTES:
[1] Cats! Cats! Cats! 50 Cats are required to capture the rats and
mice that are infesting the Government Magazines. Whoever shall
bring a cat to Deputy-Controller Martindale's office between 11
and 12 o'clock on any day up till the 28th inst., shall receive one
dollar per cat. By order, &c.
31. *** END OF THE PROJECT GUTENBERG EBOOK CHAMBERS'S
JOURNAL OF POPULAR LITERATURE, SCIENCE, AND ART, NO. 723
***
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
33. 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.
34. 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:
35. 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
36. 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
37. 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
38. 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,
39. 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
40. 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
41. 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.
42. 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.
43. Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebooknice.com