Common Tasks and How to Do Them in Android

Implementing Activity callbacks (Android
calls your activity at various key moments in its life cycle. You must know
how to handle each of these to draw your screen, initialize class members,
and acquire data.)

The ApiDemos sample application includes many, many examples of common
tasks and UI features. See the code inside
<sdk>samples/ApiDemos and the other sample applications
under the samples/ folder in the SDK.

Creating an Android Application using the Eclipse Plugin

Using the Android Eclipse plugin is the fastest and easiest way
to start creating a new Android application. The plugin automatically generates
the correct project structure for your application, and keeps the resources
compiled for you automatically.

It is still a good idea to know what is going on though. Take a look at Application Fundamentals
to understand the basics of how an Android application works.

You should also take a look at the ApiDemos application and the other sample
applications included in the SDK, in the <sdk>/samples/
folder in the SDK.

Finally, a great way to started with Android development in Eclipse is to
follow both the Hello,
World and Notepad code
tutorials. In particular, the start of the Hello Android tutorial is an
excellent introduction to creating a new Android application in Eclipse.

Creating an Android Application without the Eclipse Plugin

This topic describes the manual steps in creating an Android application.
Before reading this, you should read Application Fundamentals
to understand the basics of how an Android application works. You might also
want to look at the sample code included with the Android SDK, in the
<sdk>/samples/ directory.

Here is a list of the basic steps in building an application.

Create your required resource files This includes
the AndroidManifest.xml global description file, string files that your application
needs, and layout files describing your user interface. A full list of optional
and required files and syntax details for each is given in File
List for an Android Application.

Design your user interface See User Interface for
details on elements of the Android screen.

Implement your Activity (this page) You
will create one class/file for each screen in your application. Screens will
inherit from an android.app class, typically android.app.Activity for basic screens, android.app.ListActivity for list screens, or android.app.Dialog for dialog boxes. You will implement the required callbacks
that let you draw your screen, query data, and commit changes, and also perform
any required tasks such as opening additional screens or reading data from
the device. Common tasks, such as opening a new screen or reading data from
the device, are described below.
The list of files you'll need for your application are described in List
of Files for an Android Application.

Adding an External Library (.jar) using Eclipse

You can use a third party JAR in your application by adding it to your Eclipse project as follows:

In the Package Explorer panel, right-click on your project and select Properties.

Select Java Build Path, then the tab Libraries.

Press the Add External JARs... button and select the JAR file.

Alternatively, if you want to include third party JARs with your package, create a new directory for them within your project and select Add Library... instead.

It is not necessary to put external JARs in the assets folder.

Implementing Activity Callbacks

Android calls a number of callbacks to let you draw your screen, store data before
pausing, and refresh data after closing. You must implement at least some of
these methods. Read the Activities
document to learn when and in what order these methods
are called. Here are some of the standard types of screen classes that Android provides:

android.app.ListActivity - This is a screen
that is used to display a list of something. It hosts a ListView object,
and exposes methods to let you identify the selected item, receive callbacks
when the selected item changes, and perform other list-related actions.

android.app.Dialog - This is a small, popup dialog-style
window that isn't intended to remain in the history stack. (It is not resizeable
or moveable by the user.)

Opening a New Screen

Your Activity will often need to open another Activity screen as it progresses.
This new screen can be part of the same application or part of another application,
the new screen can be floating or full screen, it can return a result, and you
can decide whether to close this screen and remove it from the history stack
when you are done with it, or to keep the screen open in history. These next
sections describe all these options.

Floating or full?

When you open a new screen you can decide whether to make it transparent or floating,
or full-screen. The choice of new screen affects the event sequence of events
in the old screen (if the new screen obscures the old screen, a different
series of events is called in the old screen). See the Activities document for
details.

Transparent or floating windows are implemented in three
standard ways:

Calling startActivity() or startActivityForResult() will open a new screen in whatever
way it defines itself (if it uses a floating theme it will be floating,
otherwise it will be full screen).

Opening a Screen

When you want to open a new screen, you can either explicitly specify the activity
class to open, or you can let the operating system decide which screen to open,
based upon the data and various parameters you pass in. A screen is opened by
calling startActivity
and passing in an Intent object, which specifies
the criteria for the handling screen. To specify a specific screen, call Intent.setClass
or setClassName with the exact activity class to open. Otherwise, set a variety
of values and data, and let Android decide which screen is appropriate to open.
Android will find one or zero Activities that match the specified requirements;
it will never open multiple activities for a single request. More information
on Intents and how Android resolves them to a specific class is given in the
Intent topic.

Some Intent examples

The following snippet loads the com.android.samples.Animation1 class, and
passes it some arbitrary data.:

Android defines a number of standard values, for instance the action constants
defined by Intent. You can define custom values, but
both the caller and handler must use them. See the <intent-filter>
tag description in The AndroidManifest.xml
File for more information on the manifest syntax for the handling
application.

Returning a Result from a Screen

A window can return a result after it closes. This result will be passed back
into the calling Activity's onActivityResult() method, which can supply an Intent containing arbitrary data, along with
the request code passed to startActivityForResult(). Note that you must call the startActivityForResult()
method that accepts a request code parameter to get this callback. The following
code demonstrates opening a new screen and retrieving a result.

Lifetime of the new screen

An activity can remove itself from the history stack by calling Activity.finish() on itself, or the activity that opened the screen can call
Activity.finishActivity()
on any screens that it opens to close them.

Listening for Button Clicks

Button click and other UI event capturing are covered in Input Events.

Configuring General Window Properties

You can set a number of general window properties, such as whether to display
a title, whether the window is floating, and whether it displays an icon, by
calling methods on the Window member
of the underlying View object for the window. Examples include calling getWindow().requestFeature() (or the convenience
method requestWindowFeature(some_feature))
to hide the title. Here is an example of hiding the title bar:

//Hide the title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);

A better way to achieve the same end is to specify a theme in your Android
Manifest file:

This is preferable because it tells the system not to show a title bar while
your application is starting up. With the explicit method call, your application
will have a title bar visible to the user until onCreate runs.

(Note that this can be applied to either the <application>
tag or to individual <activity> tags.)

Referring to localhost from the emulated
environment

If you need to refer to your host computer's localhost, such as when you
want the emulator client to contact a server running on the same host, use the alias
10.0.2.2 to refer to the host computer's loopback interface.
From the emulator's perspective, localhost (127.0.0.1) refers to its own
loopback interface.

Storing and Retrieving State

If your application is dumped from memory because of space concerns, it will lose
all user interface state information such as checkbox state and text box values
as well as class member values. Android calls Activity.onSaveInstanceState before it pauses the application. This method hands in a Bundle that can be used to store name/value pairs that will
persist and be handed back to the application even if it is dropped from memory.
Android will pass this Bundle back to you when it calls onCreate(). This Bundle only exists while the application is still in the history
stack (whether or not it has been removed from memory) and will be lost when
the application is finalized. See the topics for onSaveInstanceState(Bundle) and
onCreate(Bundle) for
examples of storing and retrieving state.

Storing and Retrieving Larger or More Complex Persistent Data

Your application can store files or complex collection objects, and reserve them
for private use by itself or other activities in the application, or it can expose
its data to all other applications on the device. See Storing,
Retrieving, and Exposing Data to learn how to store and retrieve private data,
how to store and retrieve common data from the device, and how to expose your
private data to other applications.

Playing Media Files

Listening For and Broadcasting Global Messages, and Setting Alarms

You can create a listening class that can be notified or even instantiated whenever
a specific type of system message is sent.

The listening classes, called broadcast receivers, extend BroadcastReceiver. If you want Android to instantiate the object whenever an appropriate
intent notification is sent, define the receiver with a <receiver> element
in the AndroidManifext.xml file. If the caller is expected to instantiate the
object in preparation to receive a message, this is not required. The receiver
will get a call to their BroadcastReceiver.onReceive() method. A receiver can define an <intent-filter> tag
that describes the types of messages it will receive. Just as Android's IntentResolver
will look for appropriate Activity matches for a startActivity() call, it will
look for any matching Receivers (but it will send the message to all matching
receivers, not to the "best" match).

To send a notification, the caller creates an Intent
object and calls Context.sendBroadcast() with that Intent. Multiple recipients can receive
the same message. You can broadcast an Intent message to an intent receiver in
any application, not only your own. If the receiving class is not registered
using <receiver> in its manifest, you can dynamically instantiate
and register a receiver by calling Context.registerReceiver().

Receivers can include intent filters to specify what kinds of intents they are
listening for. Alternatively, if you expect a single known caller to contact
a single known receiver, the receiver does not specify an intent filter, and
the caller specifies the receiver's class name in the Intent by calling Intent.setClassName()
with the recipient's class name. The recipient receives a Context object that refers to its own package, not to the package of the sender.

Note: If a receiver or broadcaster
enforces permissions, your application might need to request permission
to send or receive messages from that object. You can request permission by using
the <uses-permission> tag in the manifest.

Here is a code snippet of a sender and receiver. This example does not demonstrate
registering receivers dynamically. For a full code example, see the AlarmService
class in the ApiDemos project.

Sending the message

// We are sending this to a specific recipient, so we will
// only specify the recipient class name.
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("message","Wake up.");
sendBroadcast(intent);

Receiving the message

Receiver AndroidManifest.xml (because there is no intent filter
child, this class will only receive a broadcast when the receiver class is specified
by name, as is done in this example):

Other system messages

You can listen for other system messages sent by Android as well, such as USB
connection/removal messages, SMS arrival messages, and timezone changes. See
Intent for a list of broadcast messages to listen for.
Messages are marked "Broadcast Action" in the documentation.

Listening for phone events

The android.telephony package overview page describes how to
register to listen for phone events.

Setting Alarms

Android provides an AlarmManager service that
will let you specify an Intent to send at a designated time. This intent is typically
used to start an application at a preset time. (Note: If you want to send
a notification to a sleeping or running application, use Handler instead.)

Displaying Alerts

There are two major kinds of alerts that you may display to the user:
(1) Normal alerts are displayed in response to a user action, such as
trying to perform an action that is not allowed. (2) Out-of-band alerts,
called notifications, are
displayed as a result of something happening in the background, such as the
user receiving new e-mail.

Normal Alerts

Android provides a number of ways for you to show popup notifications to your
user as they interact with your application.

A dialog box used to indicate progress of an operation with a known progress
value or an indeterminate length (setProgress(bool)). See Views > Progress Bar in
ApiDemos for examples.

Activity

By setting the theme of an activity to
android:theme="@android:style/Theme.Dialog",
your activity will take on
the appearance of a normal dialog, floating on top of whatever was
underneath it. You usually set the theme through the
android:theme attribute in your AndroidManifest.xml.
The advantage of this
over Dialog and AlertDialog is that Application has a much better managed
life cycle than dialogs: if a dialog goes to the background and is killed,
you cannot recapture state, whereas Application exposes a Bundle of saved values in onCreate() to help you maintain state.

AlertDialog

This is a basic warning dialog box that lets you configure a message, button text,
and callback. You can create one by calling using the AlertDialog.Builder class, as shown here.

Notifications

Out-of-band alerts should always be displayed using the
NotificationManager, which allows you to tell the user
about something they may be interested in without disrupting what they are
currently doing. A notification can be anything from a brief pop-up box
informing the user of the new information, through displaying a persistent
icon in the status bar, to vibrating, playing sounds, or flashing lights to
get the user's attention. In all cases, the user must explicitly shift their
focus to the notification before they can interact with it.

The following code demonstrates using NotificationManager to display a basic text
popup when a new SMS message arrives in a listening service, and provides the
current message count. You can see several more examples in the ApiDemos application,
under app/ (named notification*.java).

static void setNewMessageIndicator(Context context, int messageCount){
// Get the static global NotificationManager object.
NotificationManager nm = NotificationManager.getDefault();
// If we're being called because a new message has been received,
// then display an icon and a count. Otherwise, delete the persistent
// message.
if (messageCount > 0) {
nm.notifyWithText(myApp.NOTIFICATION_GUID, // ID for this notification.
messageCount + " new message" + messageCount > 1 ? "s":"", // Text to display.
NotificationManager.LENGTH_SHORT); // Show it for a short time only.
}
}

To display a notification in the status bar and have it launch an intent when
the user selects it (such as the new text message notification does), call NotificationManager.notify(),
and pass in vibration patterns, status bar icons, or Intents to associate with
the notification.

Adding Items to the Screen Menu

Display a Web Page

Binding to Data

You can bind a ListView to a set of underlying data by using a shim class called
ListAdapter (or a subclass). ListAdapter subclasses
bind to a variety of data sources, and expose a common set of methods such as
getItem() and getView(), and uses them to pick View items to display in its list.
You can extend ListAdapter and override getView() to create your own custom list
items. There are essentially only two steps you need to perform to bind to data:

Create a ListAdapter object and specify its data source

Give the ListAdapter to your ListView object.

That's it!

Here's an example of binding a ListActivity screen to the results from a cursor
query. (Note that the setListAdapter() method shown is a convenience method that
gets the page's ListView object and calls setAdapter() on it.)

// Run a query and get a Cursor pointing to the results.
Cursor c = People.query(this.getContentResolver(), null);
startManagingCursor(c);
// Create the ListAdapter. A SimpleCursorAdapter lets you specify two interesting things:
// an XML template for your list item, and
// The column to map to a specific item, by ID, in your template.
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, // Use a template that displays a text view
c, // Give the cursor to the list adapter
new String[] {People.NAME} , // Map the NAME column in the people database to...
new String[] {"text1"}); // The "text1" view defined in the XML template
setListAdapter(adapter);

See view/List4 in the ApiDemos project for an example of extending ListAdapter
for a new data type.

Getting a Handle to a Screen Element

You can get a handle to a screen element by calling Activity.findViewById. You can then use
the handle to set or retrieve any values exposed by the object.

Capture Images from the Phone Camera

You can hook into the device's camera onto your own Canvas object by using the
Camera class. See that class's documentation,
and the ApiDemos project's Camera Preview application (Graphics/Camera Preview)
for example code.

Handling Expensive Operations in the UI Thread

Avoid performing long-running operations (such as network I/O) directly in the UI thread —
the main thread of an application where the UI is run — or your application may be blocked
and become unresponsive. Here is a brief summary of the recommended approach for handling expensive operations:

Create a Handler object in your UI thread

Spawn off worker threads to perform any required expensive operations

Post results from a worker thread back to the UI thread's handler either through a Runnable or a Message

Selecting, Highlighting, or Styling Portions of Text

You can highlight or style the formatting of strings or substrings of text in
a TextView object. There are two ways to do this:

If you use a string resource,
you can add some simple styling, such as bold or italic using HTML notation.
The currently supported tags are: B (bold),
I (italic), U (underline),
TT (monospace), BIG, SMALL,
SUP (superscript), SUB (subscript),
and STRIKE (strikethrough).
So, for example, in res/values/strings.xml you could declare this:<resource>
<string id="@+id/styled_welcome_message">We
are <b><i>so</i></b> glad to see you.</string>
</resources>

To style text on the fly, or to add highlighting or more complex styling,
you must use the Spannable object as described next.

This context information is used to center the search result in a particular area, and is equivalent to adjusting the Map activity to the described location and zoom level before issuing the query.

If the latitudeSpan, longitudeSpan, and zoomLevel attributes are not consistent, then it is undefined which one takes precedence.

List of Files for an Android Application

The following list describes the structure and files of an Android application.
Many of these files can be built for you (or stubbed out) by the android tool
shipped in the tools/ menu of the SDK.

MyApp/

AndroidManifest.xml

(required) Advertises the screens that this application provides,
where they can be launched (from the main program menu or elsewhere),
any content providers it implements and what kind of data they handle,
where the implementation classes are, and other application-wide
information. Syntax details for this file are described in The AndroidManifest.xml File.

(required) This folder holds all the resources for
your application. Resources are external data files or description files
that are compiled into your code at build time. Files in different folders
are compiled differently, so you must put the proper resource into the
proper folder. (See Resources for details.)

anim/animation1.xml...

(optional) Holds any animation XML description files that the
application uses. The format of these files is described in Resources.

(optional) Zero or more files that will be compiled to android.graphics.drawable resources. Files
can be image files (png, gif, or other) or XML files describing other
graphics such as bitmaps, stretchable bitmaps, or gradients. Supported
bitmap file formats are PNG (preferred), JPG, and GIF (discouraged),
as well as the custom 9-patch stretchable bitmap format. These formats
are described in Resources.

layout/screen_1_layout.xml
...

(optional) Holds all the XML files describing screens or parts
of screens. Although you could create a screen in Java, defining them
in XML files is typically easier. A layout file is similar in concept
to an HTML file that describes the screen layout and components. See User Interface for more information about designing screens, and Available Resource Types for the syntax of these files.

(optional) XML files describing additional resources
such as strings, colors, and styles. The naming, quantity, and number
of these files are not enforced--any XML file is compiled, but these
are the standard names given to these files. However, the syntax
of these files is prescribed by Android, and described in Resources.

From the DDMS application, select the emulator
(e.g., "emulator-5554") and click Device > Run logcat...
to view all the log data.

Note: If you are running Eclipse and
encounter a warning about the VM debug port when opening DDMS, you can ignore it
if you're only interested in logs. However, if you want to further inspect and
control your processes from DDMS, then you should close Eclipse before launching DDMS so that
it may use the VM debugging port.