Android Book
Android Book
com/Android/
The Busy Coder's Guide to Android
Development
by Mark L. Murphy
CommonsWare books may be purchased in printed (bulk) or digital form for educational or
business use. For more information, contact [email protected].
Printing History:
Jul 2008: Version 1.0 ISBN: 978-0-9816780-0-9
The CommonsWare name and logo, “Busy Coder's Guide”, and related trade dress are
trademarks of CommonsWare, LLC.
All other trademarks referenced in this book are trademarks of their respective firms.
The publisher and author(s) assume no responsibility for errors or omissions or for damages
resulting from the use of the information contained herein.
iii
iv
vi
vii
viii
ix
xi
Thanks!
And, most of all, thanks for your interest in this book! I sincerely hope you
find it useful and at least occasionally entertaining.
Prerequisites
If you are interested in programming for Android, you will need at least
basic understanding of how to program in Java. Android programming is
done using Java syntax, plus a class library that resembles a subset of the
Java SE library (plus Android-specific extensions). If you have not
programmed in Java before, you probably should quick learn how that
works before attempting to dive into programming for Android.
iii
Warescription
This book will be published both in print and in digital (ebook) form. The
ebook versions of all CommonsWare titles are available via an annual
subscription – the Warescription.
Each subscriber gets personalized editions of all editions of each title: both
those mirroring printed editions and in-between updates that are only
available in ebook form. That way, your ebooks are never out of date for
long, and you can take advantage of new material as it is made available
instead of having to wait for a whole new print edition. For example, when
new releases of the Android SDK are made available, this book will be
quickly updated to be accurate with changes in the APIs.
iv
Be the first to report a unique concrete problem, and we'll give you a coupon
for a six-month Warescription as a bounty for helping us deliver a better
product. You can use that coupon to get a new Warescription, renew an
existing Warescription, or give the coupon to a friend, colleague, or some
random person you meet on the subway.
• Typographical errors
• Sample applications that do not work as advertised, in the
environment described in the book
• Factual errors that cannot be open to interpretation
By "unique", we mean ones not yet reported. Each book has an errata page
on the CommonsWare Web site; most known problems will be listed there.
• Places where you think we are in error, but where we feel our
interpretation is reasonable
• Places where you think we could add sample applications, or expand
upon the existing material
• Samples that do not work due to "shifting sands" of the underlying
environment (e.g., changed APIs with new releases of an SDK)
However, those "softer" issues do not qualify for the formal bounty program.
Questions about the bug bounty, or problems you wish to report for bounty
consideration, should be sent to [email protected].
The source code samples shown in this book are available for download
from the CommonsWare Web site. All of the Android projects are licensed
under the Apache 2.0 License, in case you have the desire to reuse any of it.
Each CommonsWare book edition will be available for use under the
Creative Commons Attribution-Noncommercial-Share Alike 3.0 license as of
the fourth anniversary of its publication date, or when 4,000 copies of the
edition have been sold, whichever comes first. That means that, once four
years have elapsed (perhaps sooner!), you can use this prose for non-
commercial purposes. That is our Four-to-Free Guarantee to our readers and
the broader community. For the purposes of this guarantee, new
Warescriptions and renewals will be counted as sales of this edition, starting
from the time the edition is published.
Note that future editions of this book will become free on later dates, each
four years from the publication of that edition or based on sales of that
specific edition. Releasing one edition under the Creative Commons license
does not automatically release all editions under that license.
vi
CHAPTER 1
The Big Picture
Android devices, by and large, will be mobile phones. While the Android
technology is being discussed for use in other areas (e.g., car dashboard
"PCs"), for the most part, you can think of Android as being used on phones.
On the plus side, circa 2008, Android-style smartphones are sexy. Offering
Internet services over mobile devices dates back to the mid-1990's and the
Handheld Device Markup Language (HDML). However, only in recent years
have phones capable of Internet access taken off. Now, thanks to trends like
text messaging and to products like Apple's iPhone, phones that can serve as
Internet access devices are rapidly gaining popularity. So, working on
Android applications gives you experience with an interesting technology
(Android) in a fast-moving market segment (Internet-enabled phones),
which is always a good thing.
The problem comes when you actually have to program the darn things.
Anyone with experience in programming for PDAs or phones has felt the
pain of phones simply being small in all sorts of dimensions:
• Screens are small (you won't get comments like, "is that a 24-inch
LCD in your pocket, or...?")
Moreover, applications running on a phone have to deal with the fact that
they're on a phone.
People with mobile phones tend to get very irritated when those phones
don't work, which is why the "can you hear me now?" ad campaign from
Verizon Wireless has been popular for the past few years. Similarly, those
same people will get irritated at you if your program "breaks" their phone:
As you might expect, much of this book deals with that framework and how
you write programs that work within its confines and take advantage of its
capabilities.
When you write a desktop application, you are "master of your own
domain". You launch your main window and any child windows – like dialog
boxes – that are needed. From your standpoint, you are your own world,
leveraging features supported by the operating system, but largely ignorant
of any other program that may be running on the computer at the same
time. If you do interact with other programs, it is typically through an API,
such as using JDBC (or frameworks atop it) to communicate with MySQL or
another database.
Activities
The building block of the user interface is the activity. You can think of an
activity as being the Android analogue for the window or dialog in a desktop
application.
While it is possible for activities to not have a user interface, most likely your
"headless" code will be packaged in the form of content providers or
services, described below.
Content Providers
Content providers provide a level of abstraction for any data stored on the
device that is accessible by multiple applications. The Android development
model encourages you to make your own data available to other
applications, as well as your own – building a content provider lets you do
that, while maintaining complete control over how your data gets accessed.
Intents
Intents are system messages, running around the inside of the device,
notifying applications of various events, from hardware state changes (e.g.,
an SD card was inserted), to incoming data (e.g., an SMS message arrived),
to application events (e.g., your activity was launched from the device's
main menu). Not only can you respond to intents, but you can create your
own, to launch other activities, or to let you know when specific situations
arise (e.g., raise such-and-so intent when the user gets within 100 meters of
this-and-such location).
Services
Activities, content providers, and intent receivers are all short-lived and can
be shut down at any time. Services, on the other hand, are designed to keep
running, if needed, independent of any activity. You might use a service for
checking for updates to an RSS feed, or to play back music even if the
controlling activity is no longer operating.
Storage
You can package data files with your application, for things that do not
change, such as icons or help files. You also can carve out a small bit of space
on the device itself, for databases or files containing user-entered or
retrieved data needed by your application. And, if the user supplies bulk
storage, like an SD card, you can read and write files on there as needed.
Network
Multimedia
Android devices have the ability to play back and record audio and video.
While the specifics may vary from device to device, you can query the device
to learn its capabilities and then take advantage of the multimedia
capabilities as you see fit, whether that is to play back music, take pictures
with the camera, or use the microphone for audio note-taking.
GPS
Phone Services
And, of course, Android devices are typically phones, allowing your software
to initiate calls, send and receive SMS messages, and everything else you
expect from a modern bit of telephony technology.
Root Contents
...
...
...
...
When you create your application, you will get a starter manifest generated
for you. For a simple application, offering a single activity and nothing else,
the auto-generated manifest will probably work out fine, or perhaps require
a few minor modifications. On the other end of the spectrum, the manifest
file for the Android API demo suite is over 1,000 lines long. Your production
Android applications will probably fall somewhere in the middle.
...
...
...
10
Every programming language or environment book starts off with the ever-
popular "Hello, World!" demonstration: just enough of a program to prove
you can build things, not so much that you cannot understand what is going
on. However, the typical "Hello, World!" program has no interactivity (e.g.,
just dumps the words to a console), and so is really boring.
This chapter demonstrates a simple project, but one using Advanced Push-
Button Technology™ and the current time, to show you how a simple
Android activity works.
To work with anything in Android, you need a project. With ordinary Java, if
you wanted, you could just write a program as a single file, compile it with
javac, and run it with java, without any other support structures. Android is
more complex, but to help keep it manageable, Google has supplied tools to
help create the project. If you are using an Android-enabled IDE, such as
Eclipse with the Android plugin, you can create a project inside of the IDE
(e.g., select File > New > Project, then choose Android > Android
Project).
If you are using tools that are not Android-enabled, you can use the
activityCreator.py script, found in the tools/ directory in your SDK
installation. Just pass activityCreator.py the package name of the activity
13
you want to create and a --out switch indicating where the project files
should be generated. For example:
For the purposes of the samples shown in this book, you can download their
project directories in a ZIP file on the CommonsWare Web site. These
projects are ready for use; you do not need to run activityCreator.py on
those unpacked samples.
The Activity
package com.commonsware.android.skeleton;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Date;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
14
updateTime();
setContentView(btn);
}
Or, if you download the source files off the Web site, you can just use the Now
project directly.
package com.commonsware.android.skeleton;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Date;
The package declaration needs to be the same as the one you used when
creating the project. And, like any other Java project, you need to import any
classes you reference. Most of the Android-specific classes are in the android
package.
Activities are public classes, inheriting from the android.Activity base class.
In this case, the activity holds a button (btn). Since, for simplicity, we want
15
to trap all button clicks just within the activity itself, we also have the
activity class implement OnClickListener.
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
The onCreate() method is invoked when the activity is started. The first
thing you should do is chain upward to the superclass, so the stock Android
activity initialization can be done.
We will discuss that magical Bundle icicle in a later chapter. For the
moment, consider it an opaque handle that all activities receive upon
creation.
16
To build the activity, either use your IDE's built-in Android packaging tool,
or run ant in the base directory of your project. Then, to run the activity:
17
Clicking the button – in other words, pretty much anywhere on the phone's
screen – will update the time shown in the button's label.
Note that the label is centered horizontally and vertically, as those are the
default styles applied to button captions. We can control that formatting,
which will be covered in a later chapter.
18
With that in mind, it's time to break out the XML and learn out to lay out
Android activity views that way.
...
...
...
19
...
...
20
Every GUI toolkit has some basic widgets: fields, labels, buttons, etc.
Android's toolkit is no different in scope, and the basic widgets will provide
a good introduction as to how widgets work in Android activities.
Assigning Labels
...
...
Fleeting Images
...
...
21
...
...
Useful Properties
...
Useful Methods
...
22
23
Thinking Linearly
...
...
Orientation
...
Fill Model
...
Weight
...
Gravity
...
Padding
...
Example
...
24
...
...
...
...
...
Order of Evaluation
...
Example
...
Tabula Rasa
...
25
...
...
...
...
Example
...
Scrollwork
...
26
Back in the chapter on basic widgets, you saw how fields could have
constraints placed upon them to limit possible input, such as numeric-only
or phone-number-only. These sorts of constraints help users "get it right"
when entering information, particularly on a mobile device with cramped
keyboards.
...
27
Using ArrayAdapter
...
...
...
Spin Control
...
...
...
...
28
The widgets and containers covered to date are not only found in many GUI
toolkits (in one form or fashion), but also are widely used in building GUI
applications, whether Web-based, desktop, or mobile. The widgets and
containers in this chapter are a little less widely used, though you will likely
find many to be quite useful.
...
...
Making Progress
...
29
Putting It On My Tab
...
The Pieces
...
The Idiosyncrasies
...
Wiring It Together
...
...
30
Like applications for the desktop and some mobile operating systems, such
as PalmOS and Windows Mobile, Android supports activities with
"application" menus. Some Android phones will have a dedicated menu key
for popping up the menu; others will offer alternate means for triggering the
menu to appear.
Also, as with many GUI toolkits, you can create "context menus". On a
traditional GUI, this might be triggered by the right-mouse button. On
mobile devices, context menus typically appear when the user "taps-and-
holds" over a particular widget. For example, if a TextView had a context
menu, and the device was designed for finger-based touch input, you could
push the TextView with your finger, hold it for a second or two, and a pop-up
menu will appear for the user to choose from.
Where Android differs from most other GUI toolkits is in terms of menu
construction. While you can add items to the menu, you do not have full
control over the menu's contents, nor the timing of when the menu is built.
Part of the menu is system-defined, and that portion is managed by the
Android framework itself.
Flavors of Menu
...
31
Menus of Options
...
Menus in Context
...
Taking a Peek
...
32
Other GUI toolkits let you use HTML for presenting information, from
limited HTML renderers (e.g., Java/Swing, wxWidgets) to embedding
Internet Explorer into .NET applications. Android is much the same, in that
you can embed the built-in Web browser as a widget in your own activities,
for displaying HTML or full-fledged browsing. The Android browser is
based on WebKit, the same engine that powers Apple's Safari Web browser.
The Android browser is sufficiently complex that it gets its own Java package
(android.webkit), though using the WebView widget itself can be simple or
powerful, based upon your requirements.
...
Loading It Up
...
...
33
...
34
Sometimes, your activity (or other piece of Android code) will need to speak
up.
Not every interaction with Android users will be neat, tidy, and containable
in activities composed of views. Errors will crop up. Background tasks may
take way longer than expected. Something asynchronous may occur, such as
an incoming message. In these and other cases, you may need to
communicate with the user outside the bounds of the traditional user
interface.
Of course, this is nothing new. Error messages in the form of dialog boxes
have been around for a very long time. More subtle indicators also exist,
from task tray icons to bouncing dock icons to a vibrating cell phone.
Android has quite a few systems for letting you alert your users outside the
bounds of an Activity-based UI. One, notifications, is tied heavily into
intents and services and, as such, is covered in a later chapter. In this
chapter, you will see two means of raising pop-up messages: toasts and
alerts.
Raising Toasts
...
35
Alert! Alert!
...
36
Ideally, you want your activities to be downright snappy, so your users don't
feel that your application is sluggish. Responding to user input quickly (e.g.,
200ms) is a fine goal. At minimum, though, you need to make sure you
respond within 5 seconds, lest the ActivityManager decide to play the role of
the Grim Reaper and kill off your activity as being non-responsive.
Of course, your activity might have real work to do, which takes non-
negligible amounts of time. There are two ways of dealing with this:
...
37
Messages
...
Runnables
...
Running In Place
...
...
...
38
While this may sound like a broken record...please remember that Android
devices, by and large, are phones. As such, some activities are more
important that others – taking a call is probably more important to users
than is playing Sudoku. And, since it is a phone, it probably has less RAM
than does your current desktop or notebook.
As a result, your activity may find itself being killed off because other
activities are going on and the system needs your activity's memory. Think
of it as the Android equivalent of the "circle of life" – your activity dies so
others may live, and so on. You cannot assume that your activity will run
until you think it is complete, or even until the user thinks it is complete.
Schroedinger's Activity
...
39
...
...
...
...
40
Android has many different ways for you to store data for long-term use by
your activity. The simplest to use is the preferences system.
Preferences can either be for a single activity or shared among all activities
in an application. Eventually, preferences might be shareable across
applications, but that is not supported as of the time of this writing.
...
...
43
...
44
...
...
45
Resources are static bits of information held outside the Java source code.
You have seen one type of resource – the layout – frequently in the examples
in this book. There are many other types of resource, such as images and
strings, that you can take advantage of in your Android applications.
...
String Theory
...
Plain Strings
...
String Formats
...
47
Styled Text
...
Styled Formats
...
...
...
Miscellaneous Values
...
Dimensions
...
Colors
...
Arrays
...
48
...
49
For Android, SQLite is "baked into" the Android runtime, so every Android
application can create SQLite databases. Since SQLite uses a SQL interface,
it is fairly straightforward to use for people with experience in other SQL-
based databases. However, its native API is not JDBC, and JDBC might be
too much overhead for a memory-limited device like a phone, anyway.
Hence, Android programmers have a different API to learn – the good news
being is that it is not that difficult.
This chapter will cover the basics of SQLite use in the context of working on
Android. It by no means is a thorough coverage of SQLite as a whole. If you
want to learn more about SQLite and how to use it in other environment
than Android, a fine book is The Definitive Guide to SQLite by Michael
Owens.
51
...
...
...
Makin' Data
...
...
Raw Queries
...
Regular Queries
...
52
...
Using Cursors
...
...
...
...
53
Java has as many, if not more, third-party libraries than any other modern
programming language. Here, "third-party libraries" refer to the
innumerable JARs that you can include in a server or desktop Java
application – the things that the Java SDKs themselves do not provide.
In the case of Android, the Dalvik VM at its heart is not precisely Java, and
what it provides in its SDK is not precisely the same as any traditional Java
SDK. That being said, many Java third-party libraries still provide
capabilities that Android lacks natively and therefore may be of use to you
in your project, for the ones you can get working with Android's flavor of
Java.
This chapter explains what it will take for you to leverage such libraries and
the limitations on Android's support for arbitrary third-party code.
...
...
55
The expectation is that most, if not all, Android devices will have built-in
Internet access. That could be WiFi, cellular data services (EDGE, 3G, etc.),
or possibly something else entirely. Regardless, most people – or at least
those with a data plan or WiFi access – will be able to get to the Internet
from their Android phone.
Not surprisingly, the Android platform gives developers a wide range of ways
to make use of this Internet access. Some offer high-level access, such as the
integrated WebKit browser component we saw in an earlier chapter. If you
want, you can drop all the way down to using raw sockets. Or, in between,
you can leverage APIs – both on-device and from 3rd-party JARs – that give
you access to specific protocols: HTTP, XMPP, SMTP, and so on.
The emphasis of this book is on the higher-level forms of access: the WebKit
component and Internet-access APIs, as busy coders should be trying to
reuse existing components versus rolling one's own on-the-wire protocol
wherever possible.
...
57
...
Parsing Responses
...
Stuff To Consider
...
...
58
Up to now, the focus of this book has been on activities opened directly by
the user from the device's launcher. This, of course, is the most obvious case
for getting your activity up and visible to the user. And, in many cases it is
the primary way the user will start using your application.
However, remember that the Android system is based upon lots of loosely-
coupled components. What you might accomplish in a desktop GUI via
dialog boxes, child windows, and the like are mostly supposed to be
independent activities. While one activity will be "special", in that it shows
up in the launcher, the other activities all need to be reached...somehow.
An intent is basically a message that you pass to Android saying, "Yo! I want
to do...er...something! Yeah!" How specific the "something" is depends on
the situation – sometimes you know exactly what you want to do (e.g., open
up one of your other activities), and sometimes you don't.
In the abstract, Android is all about intents and receivers of those intents.
So, now that we are well-versed in creating activities, let's dive into intents,
so we can create more complex applications while simultaneously being
"good Android citizens".
61
...
Pieces of Intents
...
Stock Options
...
Intent Routing
...
...
Narrow Receivers
...
62
This, of course, implies that one of your activities has the means to start up
another activity. For example, if somebody clicks on an event from the view-
calendar activity, you might want to show the view-event activity for that
event. This means that, somehow, you need to be able to cause the view-
event activity to launch and show a specific event (the one the user clicked
upon).
63
This chapter covers the first scenario; the next chapter handles the second.
...
Start 'Em Up
...
Make an Intent
...
...
64
Sometimes, you know just what you want to do, such as display one of your
other activities.
Sometimes, you have a pretty good idea of what you want to do, such as view
the content represented by a Uri, or have the user pick a piece of content of
some MIME type.
Sometimes, you're lost. All you have is a content Uri, and you don't really
know what you can do with it.
For example, suppose you were creating a common tagging subsystem for
Android, where users could tag pieces of content – contacts, Web URLs,
geographic locations, etc. Your subsystem would hold onto the Uri of the
content plus the associated tags, so other subsystems could, say, ask for all
pieces of content referencing some tag.
That's all well and good. However, you probably need some sort of
maintenance activity, where users could view all their tags and the pieces of
content so tagged. This might even serve as a quasi-bookmark service for
items on their phone. The problem is, the user is going to expect to be able
to do useful things with the content they find in your subsystem, such as
dial a contact or show a map for a location.
65
The problem is, you have absolutely no idea what is all possible with any
given content Uri. You probably can view any of them, but can you edit
them? Can you dial them? Since new applications with new types of content
could be added by any user at any time, you can't even assume you know all
possible combinations just by looking at the stock applications shipped on
all Android devices.
Android offers various means by which you can present to your users a set of
likely activities to spawn for a given content Uri...even if you have no idea
what that content Uri really represents. This chapter explores some of these
Uri action introspection tools.
Pick 'Em
...
Adaptable Adapters
...
...
Asking Around
...
66
Any Uri in Android that begins with the content:// scheme represents a
resource served up by a content provider. Content providers offer data
encapsulation using Uri instances as handles – you neither know nor care
where the data represented by the Uri comes from, so long as it is available
to you when needed. The data could be stored in a SQLite database, or in
flat files, or retrieved off a device, or be stored on some far-off server
accessed over the Internet.
Given a Uri, you can perform basic CRUD (create, read, update, delete)
operations using a content provider. Uri instances can represent either
collections or individual pieces of content. Given a collection Uri, you can
create new pieces of content via insert operations. Given an instance Uri,
you can read data represented by the Uri, update that data, or delete the
instance outright.
Android lets you use existing content providers, plus create your own. This
chapter covers using content providers; the next chapter will explain how
you can serve up your own data using the content provider framework.
Pieces of Me
...
69
Getting a Handle
...
Makin' Queries
...
...
Doing It By Hand
...
Position
...
Getting Properties
...
Setting Properties
...
...
70
...
71
...
...
73
...
ContentProvider
...
onCreate()
...
query()
...
insert()
...
update()
...
delete()
...
getType()
...
74
DatabaseContentProvider
...
...
...
...
Notify-On-Change Support
...
75
In the late 1990's, a wave of viruses spread through the Internet, delivered
via email, using contact information culled from Microsoft Outlook. A virus
would simply email copies of itself to each of the Outlook contacts that had
an email address. This was possible because, at the time, Outlook did not
take any steps to protect data from programs using the Outlook API, since
that API was designed for ordinary developers, not virus authors.
Nowadays, many applications that hold onto contact data secure that data
by requiring that a user explicitly grant rights for other programs to access
the contact information. Those rights could be granted on a case-by-case
basis or a once at install time.
77
Mother, May I?
...
...
...
...
78
Services are created when manually started (via an API call) or when some
activity tries connecting to the service via inter-process communication
(IPC). Services will live until no longer needed and if RAM needs to be
reclaimed. Running for a long time isn't without its costs, though, so
services need to be careful not to use too much CPU or keep radios active
too much of the time, lest the service cause the device's battery to get used
up too quickly.
This chapter covers how you can create your own services; the next chapter
covers how you can use such services from your activities or other contexts.
Both chapters will analyze the MailBuzz sample application (MailBuzz), with
this chapter focusing mostly on the MailBuzzService implementation.
MailBuzzService polls a supplied email account, either on-demand or on a
stated interval, to see if new messages have arrived, at which it will post a
Notification (as described in the chapter on notifications).
79
Getting Buzzed
...
...
...
...
Manifest Destiny
...
...
80
Services can be used by any application component that "hangs around" for
a reasonable period of time. This includes activities, content providers, and
other services. Notably, it does not include pure intent receivers (i.e., intent
receivers that are not part of an activity), since those will get garbage
collected immediately after each instance processes one incoming Intent.
To use a service, you need to get an instance of the AIDL interface for the
service, then call methods on that interface as if it were a local object. When
done, you can release the interface, indicating you no longer need the
service.
In this chapter, we will look at the client side of the MailBuzz sample
application (MailBuzz). The MailBuzz activity provides fields for the account
information (server type, server, etc.), a checkbox to toggle whether polling
for new mail should go on, a button to push the account information to the
service, and another button to check right now for new messages.
81
...
...
Prometheus Unbound
...
Manual Transmission
...
82
Your phone also probably chirps at you for more than just incoming calls:
low battery, alarm clocks, appointment notifications, incoming text message
or email, etc.
Not surprisingly, Android has a whole framework for dealing with these
sorts of things, collectively called "notifications".
Types of Pestering
...
Hardware Notifications
...
Icons
...
83
...
84
GPS is not the only way a mobile device can identify your location.
Alternatives include:
Android devices may have one or more of these services available to them.
You, as a developer, can ask the device for your location, plus details on what
providers are available. There are even ways for you to simulate your location
in the emulator, for use in testing your location-enabled applications.
87
...
Finding Yourself
...
On the Move
...
...
Testing...Testing...
...
88
...
89
...
Zoom
...
Center
...
Reticle
...
...
...
...
Overlay Classes
...
90
...
...
91
Android has full capability to play back and record audio and video. This
includes:
93
You as a developer can integrate media playback and recording into your
applications. Recording is outside the scope of this book, in large part
because the current emulator has recording limitations at this time. And,
viewing pictures is mostly a matter of putting an ImageView widget into an
activity. This chapter, therefore, focuses on playback of audio and video.
...
Making Noise
...
Moving Pictures
...
94
Many, if not most, Android devices will be phones. As such, not only will
users be expecting to place and receive calls using Android, but you will
have the opportunity to help them place calls, if you wish.
Whatever the reason, Android has APIs to let you manipulate the phone just
like any other piece of the Android system.
95
...
...
96
One of the firms behind the Open Handset Alliance – Google – has a teeny
weeny Web search service, one you might have heard of in passing. Given
that, it's not surprising that Android has some amount of built-in search
capabilities.
Specifically, Android has "baked in" the notion of searching not only on the
device for data, but over the air to Internet sources of data.
Note that this is fairly new to the Android platform, and so some shifting in
the APIs is likely. Stay tuned for updates to this chapter.
Hunting Season
...
Search Yourself
...
97
...
...
Try It Out
...
98
Installing TourIt
...
...
...
Running TourIt
...
101
Main Activity
...
Configuration Activity
...
...
Map Activity
...
...
Help Activity
...
TourIt's Manifest
...
TourIt's Content
...
102
Data Storage
...
Content Provider
...
Model Classes
...
TourIt's Activities
...
TourListActivity
...
TourViewActivity
...
...
Details Panel
...
103
TourMapActivity
...
TourEditActivity
...
HelpActivity
...
ConfigActivity
...
104
String page=getIntent().getStringExtra(PAGE);
if (page==null) {
browser.loadUrl("file:///android_asset/index.html");
}
else {
browser.loadUrl("file:///android_asset/"+page+".html");
}
}
By default, it will load the home page. If, however, the activity was started by
another activity that passed in a specific page to view, it loads that page
instead.
HelpActivity hooks into the WebKit browser to detect clicks on links. Since
the only links in the help are to other help pages, it simply loads in the
requested page:
return(true);
}
}
ConfigActivity
The ConfigActivity class mostly loads data out of preferences, updates the
layout's widgets to match, then reverses the process when the activity is
paused (e.g., when the user clicks Close from the options menu).
The most interesting thing here is the spinner of location providers – this is
covered in detail in the chapter on location services.
368
Class BoxLayout.................................................................41
Builder..............................................................118, 119
AbsoluteLayout.......................................................96
Bundle................................133, 134, 201, 210, 264, 277
ActionEvent.............................................................20
Button...........................23, 25-28, 30, 31, 155, 159, 322
ActionListener.........................................................20
Calendar..................................................................86
Activity. .8, 68, 101, 117, 118, 126, 128, 132, 137, 147, 173,
174, 206, 207
Canvas............................................................308, 309
ActivityAdapter................................68, 220, 223, 225
CharSequence.......................................................268
ActivityIconAdapter........................................68, 220
CheckBox......................................................34, 37, 39
ActivityManager.....................................................123
Chrono.....................................................................84
Adapter..................................................................220
Clocks......................................................................88
AdapterView...........................................................101
ComponentName...................................224, 225, 275
AlertDialog.......................................................118, 119
CompoundButton...................................................37
AnalogClock............................................................88
ConcurrentLinkedQueue......................................265
ArrayAdapter.................66, 67, 69, 77, 146, 289, 364
ConfigActivity.................282, 289, 291, 305, 362, 368
ArrayList.................................................................146
ContentManager...................................................280
AudioDemo............................................................316
ContentObserver...........................................254, 255
AutoComplete.........................................................79
ContentProvider................173, 174, 177, 238, 239, 243
AutoCompleteTextView..............................33, 78-80
ContentResolver.....................................237, 239, 254
BaseColumns.........................................................252
ContentValues..................175, 237, 238, 247, 249, 253
Box............................................................................41
Context..........................66, 118, 137, 147, 173, 174, 234
369
Cursor....67, 179, 180, 231, 233-237, 239, 246, 247, 253 HttpClient.......................................................188-190
CursorAdapter.........................................................67 HttpMethod...........................................................188
DatabaseHelper.....................................................244 Images.....................................................................158
DatePicker...............................................................83 InputMethod...........................................................32
Dialer......................................................................327 Intent......90, 111, 112, 220, 223-225, 243, 273, 275, 277,
281, 292-295, 305, 314, 339
Dialog.....................................................................128
IntentReceiver...............................................205, 206
DigitalClock............................................................88
IPhone....................................................326, 328, 329
Direction.........................................................237, 361
Iterator...................................................................235
Document..............................................................146
JButton................................................................20, 21
Double...................................................................209
JCheckBox...............................................................66
Drawable..............................................82, 93, 158, 281
JComboBox..............................................................70
EditView.....................................31, 32, 78, 79, 83, 231
JLabel.......................................................................66
ExpandableListView...............................................96
JList..........................................................................66
Field.........................................................................32
JTabbedPane...........................................................90
FloatInputMethod.................................................367
JTable.......................................................................66
FlowLayout..............................................................42
Label........................................................................30
Folder......................................................................195
Launch....................................................................210
Forecast...................................................................191
Linear.......................................................................45
FrameLayout.......................................................91-93
LinearLayout...........................................41-46, 58, 93
Gallery................................................................65, 82
List............................................68, 102, 225, 268, 289
GetMethod......................................................188, 190
ListActivity..........................................68, 69, 92, 299
370
ListCellRenderer.....................................................66 Object......................................................................101
ListView. . .68, 70, 71, 82, 102, 188, 220, 233, 234, 299, OnClickListener............................20, 86, 121, 140, 211
336, 339, 363
OnCompletionListener.........................................319
Location.........................................................189, 290
OnDateSetListener...........................................84, 86
LocationIntentReceiver........................................306
OnItemSelectedListener.........................................72
LocationManager...................288-290, 292, 293, 305
OnPopulateContextMenuListener.................101, 103
LocationProvider...................288-290, 292, 296, 297
OnPreparedListener..............................................319
Lorem.....................................................................336
OnTimeSetListener..........................................84, 86
LoremBase..............................................................337
OutputStream........................................................147
LoremDemo....................................................339, 341
OutputStreamWriter.............................................147
LoremSearch..........................................................341
Overlay...........................................................308, 310
MailBuzz...........................185, 193, 263, 265, 273, 274
OverlayController.................................................308
MailBuzzService....................................263, 264, 267
PackageManager....................................................225
MailClient..............................................................194
Parcelable..............................................................268
Map............................................134, 137, 175, 237, 268
Pick.................................................................216, 258
MapActivity....................................................299-301
PickDemo..............................................................258
MapController........................................301, 302, 305
PixelCalculator................................................308-310
MapView........................................................299-304
PixelConverter.......................................................309
MediaController............................................322, 324
Point..................................................302, 303, 309-311
MediaPlayer......................................315, 316, 319, 320
PostMethod............................................................188
Menu.........................................................98, 100, 223
Prefs........................................................................139
Menu.Item.................................................99-101, 225
ProgressBar........................................90, 125, 126, 129
Menus.....................................................................102
Provider....................................233, 244, 247-252, 361
Message..............................................119, 124, 126, 127
ProviderWrapper..................................................289
MessageCountListener..........................................194
ProximityIntentReceiver.......................................294
MyActivity.............................................................224
RadioButton..................................................37-41, 46
Notification............................................263, 280, 281
RadioGroup..........................37, 38, 40, 41, 46, 48, 49
NotificationManager.....................................280, 281
ReadWrite...............................................................147
Now...............................................................19, 27, 28
371
RectF........................................................................311 TableRow............................................................56-58
Relative.....................................................................53 TabSpec..............................................................93, 94
Resources.........................................................143, 161 TextView.....26, 29-31, 34, 37, 67, 77, 86, 97, 234, 336
RouteAdapter........................................................364 TextWatcher......................................................79, 80
Scroll........................................................................60 TimerTask..............................................................266
372
Command END_TAG................................................................161
FACTORY_TEST_ACTION....................................201
adb pull...................................................................181
FIRST.......................................................................99
adb push..................................................181, 323, 348
GADGET_CATEGORY..........................................202
adb shell.........................................................180, 348
GET.........................................................................188
ant..........................................................................8, 9
GET_CONTENT_ACTION....................................201
ant install...............................................................347
HOME_CATEGORY..............................................202
dex...................................................................185, 186
HORIZONTAL........................................................42
sqlite3.....................................................................180
ID............................................................................174
Constant INBOX....................................................................195
ACCESS_CELL_ID.................................................288 INSERT_ACTION..................................................201
ACCESS_GPS.........................................................288 INTEGER................................................................172
ACCESS_POSITION.............................................288 LARGER...................................................................115
ANSWER_ACTION...............................................201 LENGTH_SHORT...................................................118
BIND_AUTO_CREATE.........................................275 MAIN.....................................................................204
CALL_ACTION......................................................201 MATCH_DEFAULT_ONLY...................................225
CONTENT_URI.....................................................254 MEDIA_MOUNTED_ACTION............................202
DEFAULT................................................................201 NULL.......................................................................175
DELETE_ACTION.................................................201 PERMISSION_GRANTED.....................................261
END_DOCUMENT................................................161 POST......................................................................188
373
PREFERENCE_CATEGORY..................................202 add()..................................................................98, 99
PROJECTION.........................................................232 addId()...................................................................230
READ_CONTACTS................................................258 addMenu().............................................................100
RECEIVE_SMS.......................................................262 addProximityAlert()..............................................293
RESULT_CANCELLED..........................................210 addSeparator().......................................................100
RESULT_FIRST_USER...........................................210 addSubMenu().......................................................100
RUN_ACTION.......................................................201 appendWhere()......................................................178
SELECTED_ALTERNATIVE_CATEGORY............202 beforeTextChanged()..............................................80
SMALLEST..............................................................115 broadcastIntentSerialized()..................................210
SUNDAY..................................................................84 buildQuery()..........................................................178
SYNC_ACTION.....................................................202 bulkInsert()............................................................238
TAB_CATEGORY...................................................202 call()................................................................326-328
TEST_CATEGORY.................................................202 canGoBack()............................................................111
TEXT.......................................................................161 canGoBackOrForward()..........................................111
TITLE.....................................................................234 canGoForward()......................................................111
VERTICAL...............................................................42 check()...............................................................37, 38
WEB_SEARCH_ACTION......................................202 checkAccountImpl().............................................270
clear().....................................................................138
Method
clearCache().............................................................111
374
clearCheck()............................................................37 getAttributeCount()..............................................162
clearHistory()..........................................................111 getAttributeName()...............................................162
commit().................................................................138 getBestProvider()..................................................290
count()....................................................................179 getCheckedRadioButtonId()...................................37
create()....................................................................119 getCollectionType()...............................................251
deleteDatabase()....................................................174 getContentProvider()............................................238
deleteRow()............................................................180 getCurrentLocation()............................................290
dial()...............................................................326-328 getFloat()...............................................................236
drawCircle()...........................................................309 getInputStream()...................................................239
edit().......................................................................138 getIntent().............................................................336
enablePoll()...........................................................270 getLatitude()..........................................................189
endCall()................................................................326 getLocation().........................................................189
equery()..................................................................179 getLongitude().......................................................189
generatePage()........................................................191 getOutputStream()...............................................239
get().........................................................................175 getPackageManager()............................................225
getAltitude()..........................................................290 getParent()...............................................................39
getAsInteger().........................................................175 getParentOfType()..................................................40
getAsString()..........................................................175 getPointXY()..........................................................309
375
getPollState().........................................................270 isChecked()........................................................34, 37
getProgress()...........................................................90 isFirst()...................................................................236
getProviders()........................................................289 isFocused()..............................................................39
getRequiredColumns().........................................249 isLast()...................................................................236
getResources()........................................................143 isNull()...................................................................236
getRootView().........................................................40 isOffhook()............................................................326
getSettings()............................................................114 isSatellite().............................................................304
getSingleType()......................................................251 isTraffic()...............................................................304
getSpeed().............................................................290 isUIThread()...........................................................128
getTitle()................................................................237 loadTime()..............................................................113
getXml()..................................................................161 makeText()..............................................................118
goBack()...................................................................111 managedQuery().............................................231-234
goBackOrForward()................................................111 move()....................................................................236
goForward().............................................................111 moveTo()................................................................236
hasAltitude().........................................................290 newTabSpec()....................................................93, 94
376
onCreate() 20, 21, 26, 27, 38, 48, 98, 103, 108, 132-134, pause()............................................................315, 324
140, 146, 156, 190, 234, 244, 252, 264-266, 303, 310,
329, 335, 336, 339 play()......................................................................324
onItemSelected()...................................................365 postDelayed().........................................................127
onKeyUp().............................................................366 prepare().................................................................315
onPageStarted()......................................................112 putString().............................................................237
onPause()..........................133, 134, 140, 149, 206, 264 query().......................176-178, 180, 246, 247, 252, 253
onPopulateContextMenu()....................................101 queryIntentActivityOptions()..............................225
onReceivedHttpAuthRequest().............................112 queryInternal()......................................................252
onRestart().............................................................134 registerContentObserver()...................................254
onResume() 133, 134, 140, 149, 189, 206, 264, 291, 305 registerIntent()......................................................206
onSearchRequested()............................................335 releaseConnection()..............................................188
onTextChanged()....................................................80 requestFocus().........................................................39
openDatabase()......................................................173 runOnUIThread()..................................................128
377
sendMessage()........................................................124 setIndicator()....................................................93, 94
sendMessageAtFrontOfQueue()...........................124 setItemCheckable()................................................99
sendMessageDelayed()..........................................124 setJavaScriptEnabled()...........................................115
setAccuracy()........................................................290 setLayoutView()......................................................26
setAlphabeticShortcut().........................................99 setMessage()...........................................................119
setAltitudeRequired()...........................................290 setNegativeButton()...............................................119
setCellRenderer()....................................................66 setNeutralButton().................................................119
setColumnShrinkable()..........................................59 setOnCompletionListener()..................................319
setContent()......................................................93, 94 setOnPopulateContextMenuListener()................101
setContentView()..............................................20, 40 setOnPreparedListener().......................................319
setCostAllowed()...................................................290 setOrientation()......................................................42
setCurrentTab()......................................................94 setPadding()............................................................44
setDataSource()......................................................315 setPositiveButton().................................................119
setDefaultFontSize()...............................................115 setProgress()...........................................................90
setDefaultKeyMode()............................................335 setProjectionMap()................................................178
setDropDownViewResource()................................70 setQwertyMode()...................................................99
setDuration()..........................................................118 setResult()..............................................................210
setEnabled()............................................................39 setText()....................................................................21
setFantasyFontFamily()..........................................114 setTextSize()............................................................115
setFollowMyLocation().........................................305 setTitle().................................................................119
setGravity()..............................................................44 setTypeface()...........................................................24
setIcon()..................................................................119 setUseDesktopUserAgent()....................................115
setImageURI()..........................................................31 setView().................................................................118
378
setWebViewClient()...............................................112 updateTime()..........................................................20
showList()..............................................................363 zoomTo()................................................................301
showNotification()................................................282
Property
sRadioOn()............................................................326
android:authorities........................................253, 254
start()......................................................................315
android:autoText......................................................31
startActivity().........................................209, 210, 220
android:background...............................................39
startService().........................................................277
android:capitalize....................................................31
startSubActivity()...........................................210, 216
android:collapseColumns.......................................59
stop()...............................................................315, 320
android:columnWidth............................................74
stopPlayback().......................................................324
android:completionThreshold...............................78
stopService()..........................................................277
android:digits...........................................................31
supportUpdates()...................................................179
android:drawSelectorOnTop.............................71, 82
switch()..................................................................100
android:horizontalSpacing.....................................74
toggle()...............................................................34, 37
android:id.....................................25, 26, 37, 51, 91-93
toggleEdgeZooming()...........................................302
android:indeterminate...........................................90
toggleRadioOnOff()..............................................326
android:indeterminateBehavior............................90
toggleSatellite().....................................................304
android:inputMethod.............................................32
toggleStreetView()................................................304
android:label............................................................13
toggleTraffic()........................................................304
android:layout_above..............................................52
toString().........................................................66, 289
android:layout_alignBaseline.................................52
unbindService().....................................................276
android:layout_alignBottom..................................52
unregisterContentObserver()...............................255
android:layout_alignLeft........................................52
unregisterIntent().................................................206
android:layout_alignParentBottom........................51
update().............................175, 176, 237, 238, 249-253
android:layout_alignParentLeft..............................51
updateInt().............................................................180
android:layout_alignParentRight...........................51
updateInternal()....................................................252
android:layout_alignParentTop.........................51, 55
updateLabel()..........................................................86
android:layout_alignRight......................................52
updateString().......................................................180
379
android:layout_alignTop...................................52, 53 android:padding................................................44, 45
android:layout_below.............................................52 android:paddingBottom.........................................45
android:layout_centerHorizontal...........................51 android:paddingLeft...............................................45
android:layout_centerInParent...............................51 android:paddingRight.............................................45
android:layout_centerVertical................................51 android:paddingTop.........................................45, 92
android:layout_column...........................................57 android:password.....................................................31
android:layout_span...............................................57 android:progress.....................................................90
android:layout_toLeft.............................................52 android:shrinkColumns..........................................58
android:layout_toRight...........................................52 android:singleLine.............................................31, 32
android:layout_weight............................................43 android:spacing.......................................................82
android:manifest......................................................12 android:src...............................................................31
android:nextFocusDown........................................39 android:text.......................................................25, 29
android:nextFocusLeft............................................39 android:textColor..............................................30, 34
android:nextFocusRight.........................................39 android:textStyle................................................29, 31
android:nextFocusUp.............................................39 android:typeface.....................................................29
android:numColumns.............................................74 android:value.........................................................341
android:numeric......................................................31 android:verticalSpacing..........................................74
android:orientation................................................42 android:visibility.....................................................39
380