• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Common Tasks and How to Do Them in Android
2excludeFromSuggestions=true
3@jd:body
4
5<ul>
6    <li><a href="#neweclipseandroidproject">Creating an Android Application using
7    the Eclipse plugin</a></li>
8    <li><a href="#newandroidprojectnoeclipse">Creating an Android Application without
9    the Eclipse plugin</a></li>
10    <li><a href="#addexternallibrary">Adding an External Library (.jar) using Eclipse</a></li>
11    <li><a href="#implementcallbacks">Implementing Activity callbacks</a> (Android
12        calls your activity at various key moments in its life cycle. You must know
13        how to handle each of these to draw your screen, initialize class members,
14        and acquire data.)</li>
15    <li><a href="#opennewscreen">Opening a new screen</a></li>
16    <li><a href="#listening">Listening for button clicks </a></li>
17    <li><a href="#configurewindowproperties">Configuring general window properties </a></li>
18    <li><a href="#localhostalias">Referring to localhost from the emulated environment</a></li>
19    <li><a href="#appstate">Storing and retrieving state</a></li>
20    <li><a href="{@docRoot}guide/topics/data/data-storage.html#preferences">Storing and retrieving preferences</a></li>
21    <li><a href="#storingandretrieving">Storing and retrieving larger or more complex
22            persistent data</a> (files and data) </li>
23    <li><a href="#playback">Playing audio, video, still, or other media files</a></li>
24    <li><a href="#broadcastreceivers">Listening for and broadcasting global messages
25        and setting alarms</a></li>
26    <li><a href="#alerts">Displaying alerts </a></li>
27    <li><a href="#progressbar">Displaying a progress bar</a> </li>
28    <li><a href="#addmenuitems">Adding items to the screen menu</a> </li>
29    <li><a href="#webpage">Display a web page</a> </li>
30    <li><a href="#binding">Binding to data</a></li>
31    <li><a href="#handle">Getting a Handle to a Screen Element</a></li>
32    <li><a href="#captureimages">Capture images from the phone camera </a></li>
33    <li><a href="#threading">Handling expensive operations in the UI thread</a></li>
34    <li><a href="#selectingtext">Selecting, highlighting, or styling portions of
35            text</a></li>
36    <li><a href="#querymap">Utilizing attributes in a Map query</a></li>
37    <li><a href="#filelist">List of files for an Android application</a></li>
38    <li><a href="#logging">Print messages to a log file</a></li>
39</ul>
40<p>The ApiDemos sample application includes many, many examples of common
41tasks and UI features. See the code inside
42<code>&lt;sdk&gt;samples/ApiDemos</code> and the other sample applications
43under the <code>samples/</code> folder in the SDK.</p>
44
45
46<h2 id="neweclipseandroidproject">Creating an Android Application using the Eclipse Plugin</h2>
47
48<p>Using the Android Eclipse plugin is the fastest and easiest way
49to start creating a new Android application. The plugin automatically generates
50the correct project structure for your application, and keeps the resources
51compiled for you automatically.</p>
52
53<p>It is still a good idea to know what is going on though. Take a look at <a
54href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>
55to understand the basics of how an Android application works.</p>
56
57<p>You should also take a look at the ApiDemos application and the other sample
58applications included in the SDK, in the <code>&lt;sdk&gt;/samples/</code>
59folder in the SDK.</p>
60
61<p>Finally, a great way to started with Android development in Eclipse is to
62follow both the <a href="{@docRoot}resources/tutorials/hello-world.html">Hello,
63World</a> and <a
64href="{@docRoot}training/notepad/index.html">Notepad</a> code
65tutorials. In particular, the start of the Hello Android tutorial is an
66excellent introduction to creating a new Android application in Eclipse.</p>
67
68<h2 id="newandroidprojectnoeclipse">Creating an Android Application without the Eclipse Plugin</h2>
69
70<p>This topic describes the manual steps in creating an Android application.
71Before reading this, you should read <a
72href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>
73to understand the basics of how an Android application works. You might also
74want to look at the sample code included with the Android SDK, in the
75<code>&lt;sdk&gt;/samples/</code> directory. </p>
76
77<p>Here is a list of the basic steps in building an application.</p>
78<ol>
79    <li><strong>Create your required resource files</strong> &nbsp;&nbsp;This includes
80        the AndroidManifest.xml global description file, string files that your application
81        needs, and layout files describing your user interface. A full list of optional
82        and required files and syntax details for each is given in <a href="#filelist">File
83        List for an Android Application</a>. </li>
84    <li><strong>Design your user interface</strong> &nbsp;&nbsp;See <a
85    href="{@docRoot}guide/topics/ui/index.html">User Interface</a> for
86    details on elements of the Android screen. </li>
87    <li><strong>Implement your Activity </strong>(this page)<strong>&nbsp;&nbsp; </strong> You
88        will create one class/file for each screen in your application. Screens will
89        inherit from an {@link android.app android.app} class, typically {@link android.app.Activity
90        android.app.Activity} for basic screens, {@link android.app.ListActivity
91        android.app.ListActivity} for list screens, or {@link android.app.Dialog
92        android.app.Dialog} for dialog boxes. You will implement the required callbacks
93        that let you draw your screen, query data, and commit changes, and also perform
94        any required tasks such as opening additional screens or reading data from
95        the device. Common tasks, such as opening a new screen or reading data from
96        the device, are described below.
97        The list of files you'll need for your application are described in <a href="#filelist">List
98        of Files for an Android Application</a>. </li>
99    <li><strong><a href="{@docRoot}guide/developing/building/building-cmdline.html">Build and install your
100                package</a>.</strong> The Android SDK has some nice tools for generating
101                projects and debugging code. </li>
102</ol>
103
104<h2 id="addexternallibrary">Adding an External Library (.jar) using Eclipse</h2>
105<p>
106You can use a third party JAR in your application by adding it to your Eclipse project as follows:
107</p>
108<ol>
109<li>
110In the <strong>Package Explorer</strong> panel, right-click on your project and select <strong>Properties</strong>.
111<li>
112Select <strong>Java Build Path</strong>, then the tab <strong>Libraries</strong>.
113<li>
114Press the <strong>Add External JARs...</strong> button and select the JAR file.
115</ol>
116<p>
117Alternatively, if you want to include third party JARs with your package, create a new directory for them within your project and select <strong>Add Library...</strong> instead.</p>
118<p>
119It is not necessary to put external JARs in the assets folder.
120</p>
121
122<a name="implementcallbacks" id="implementcallbacks"></a>
123<h2>Implementing Activity Callbacks</h2>
124<p>Android calls a number of callbacks to let you draw your screen, store data before
125    pausing, and refresh data after closing. You must implement at least some of
126    these methods. Read the <a
127href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activities</a>
128    document to learn when and in what order these methods
129    are called. Here are some of the standard types of screen classes that Android provides:</p>
130<ul>
131    <li>{@link android.app.Activity android.app.Activity} - This is a standard screen,
132        with no specialization.</li>
133    <li>{@link android.app.ListActivity android.app.ListActivity} - This is a screen
134        that is used to display a list of something. It hosts a ListView object,
135        and exposes methods to let you identify the selected item, receive callbacks
136        when the selected item changes, and perform other list-related actions. </li>
137    <li>{@link android.app.Dialog android.app.Dialog} - This is a small, popup dialog-style
138        window that isn't intended to remain in the history stack. (It is not resizeable
139        or moveable by the user.)</li>
140</ul>
141
142<a name="opennewscreen" id="opennewscreen"></a><h2>Opening a New Screen</h2>
143<p>Your Activity will often need to open another Activity screen as it progresses.
144    This new screen can be part of the same application or part of another application,
145    the new screen can be floating or full screen, it can return a result, and you
146    can decide whether to close this screen and remove it from the history stack
147    when you are done with it, or to keep the screen open in history. These next
148    sections describe all these options. </p>
149<h3>Floating or full?<a name="floatingorfull" id="floatingorfull"></a></h3>
150<p>When you open a new screen you can decide whether to make it transparent or floating,
151    or full-screen. The choice of new screen affects the event sequence of events
152    in the old screen (if the new screen obscures the old screen, a different
153    series of events is called in the old screen). See the <a
154    href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activities</a> document for
155details. </p>
156<p>Transparent or floating windows are implemented in three
157    standard ways: </p>
158<ul>
159    <li>Create an {@link android.app.Dialog app.Dialog} class </li>
160    <li>Create an {@link android.app.AlertDialog app.AlertDialog} class </li>
161    <li>Set the {@link android.R.style#Theme_Dialog} <em>theme</em> attribute to <code>&#64;android:style/Theme.Dialog</code>
162        in your AndroidManifest.xml file. For example:
163    <pre>&lt;activity class=&quot;AddRssItem&quot; android:label=&quot;Add an item&quot; android:theme=&quot;&#064;android:style/Theme.Dialog&quot;/&gt;</pre></li>
164</ul>
165
166<p>Calling startActivity() or startActivityForResult() will open a new screen in whatever
167    way it defines itself (if it uses a floating theme it will be floating,
168    otherwise it will be full screen). </p>
169<h3>Opening a Screen </h3>
170<p>When you want to open a new screen, you can either explicitly specify the activity
171    class to open, or you can let the operating system decide which screen to open,
172    based upon the data and various parameters you pass in. A screen is opened by
173    calling {@link android.app.Activity#startActivity(android.content.Intent) startActivity}
174    and passing in an {@link android.content.Intent Intent} object, which specifies
175    the criteria for the handling screen. To specify a specific screen, call Intent.setClass
176    or setClassName with the exact activity class to open. Otherwise, set a variety
177    of values and data, and let Android decide which screen is appropriate to open.
178    Android will find one or zero Activities that match the specified requirements;
179    it will never open multiple activities for a single request. More information
180    on Intents and how Android resolves them to a specific class is given in the
181    {@link android.content.Intent Intent} topic. </p>
182<a name="intentexamples" id="intentexamples"></a><h3>Some Intent examples </h3>
183<p>The following snippet loads the com.android.samples.Animation1 class, and
184    passes it some arbitrary data.:</p>
185<pre>Intent myIntent = new Intent();
186myIntent.setClassName(&quot;com.android.samples&quot;, &quot;com.android.samples.Animation1&quot;);
187myIntent.putExtra(&quot;com.android.samples.SpecialValue&quot;, &quot;Hello, Joe!&quot;); // key/value pair, where key needs current package prefix.
188startActivity(myIntent);    </pre>
189<p>The next snippet requests that a Web page be opened by specifying the VIEW action,
190    and a URI data string starting with &quot;http://&quot; schema:</p>
191<pre>Intent myIntent = new Intent(Intent.VIEW_ACTION, Uri.parse(&quot;http://www.google.com&quot;));</pre>
192<p>Here is the intent filter from the AndroidManifest.xml file for com.android.browser:</p>
193<pre>&lt;intent-filter&gt;
194    &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;
195    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;
196    &lt;scheme android:name=&quot;http&quot; /&gt;
197    &lt;scheme android:name=&quot;https&quot; /&gt;
198    &lt;scheme android:name=&quot;file&quot; /&gt;
199&lt;/intent-filter&gt; </pre>
200<p>Android defines a number of standard values, for instance the action constants
201    defined by {@link android.content.Intent}. You can define custom values, but
202    both the caller and handler must use them. See the &lt;intent-filter&gt;
203    tag description in <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">The AndroidManifest.xml
204    File</a> for more information on the manifest syntax for the handling
205    application. </p>
206<a name="returningaresult" id="returningaresult"></a><h3>Returning a Result from a Screen</h3>
207<p>A window can return a result after it closes. This result will be passed back
208    into the calling Activity's {@link android.app.Activity#onActivityResult(int,int,android.content.Intent)
209    onActivityResult()} method, which can supply an Intent containing arbitrary data, along with
210    the request code passed to startActivityForResult(). Note that you must call the {@link
211    android.app.Activity#startActivityForResult(android.content.Intent,int) startActivityForResult()}
212    method that accepts a request code parameter to get this callback. The following
213    code demonstrates opening a new screen and retrieving a result. </p>
214<pre>// Open the new screen.
215public void onClick(View v){
216    // Start the activity whose result we want to retrieve.  The
217    // result will come back with request code GET_CODE.
218    Intent intent = new Intent(this, com.example.app.ChooseYourBoxer.class);
219    startActivityForResult(intent, CHOOSE_FIGHTER);
220}
221
222// Listen for results.
223protected void onActivityResult(int requestCode, int resultCode, Intent data){
224    // See which child activity is calling us back.
225    switch (requestCode) {
226        case CHOOSE_FIGHTER:
227            // This is the standard resultCode that is sent back if the
228            // activity crashed or didn't doesn't supply an explicit result.
229            if (resultCode == RESULT_CANCELED){
230                myMessageboxFunction("Fight cancelled");
231            }
232            else {
233                myFightFunction(data);
234            }
235        default:
236            break;
237    }
238}
239
240// Class SentResult
241// Temporary screen to let the user choose something.
242    private OnClickListener mLincolnListener = new OnClickListener(){
243        public void onClick(View v) {
244            Bundle stats = new Bundle();
245            stats.putString("height","6\'4\"");
246            stats.putString("weight", "190 lbs");
247            stats.putString("reach", "74\"");
248            setResult(RESULT_OK, "Lincoln", stats);
249            finish();
250        }
251    };
252
253    private OnClickListener mWashingtonListener = new OnClickListener() {
254        public void onClick(View v){
255            Bundle stats = new Bundle();
256            stats.putString("height","6\'2\"");
257            stats.putString("weight", "190 lbs");
258            stats.putString("reach", "73\"");
259            setResult(RESULT_OK, "Washington", stats);
260            finish();
261        }
262    };
263	</pre>
264<h3>Lifetime of the new screen </h3>
265<p>An activity can remove itself from the history stack by calling {@link android.app.Activity#finish()
266    Activity.finish()} on itself, or the activity that opened the screen can call
267    {@link android.app.Activity#finishActivity(int) Activity.finishActivity()}
268    on any screens that it opens to close them. </p>
269<a name="listening" id="listening"></a><h2>Listening for Button Clicks</h2>
270<p>Button click and other UI event capturing are covered in <a
271href="{@docRoot}guide/topics/ui/ui-events.html">Input Events</a>.</p>
272<a name="configurewindowproperties" id="configurewindowproperties"></a><h2>Configuring General Window Properties</h2>
273<p>You can set a number of general window properties, such as whether to display
274    a title, whether the window is floating, and whether it displays an icon, by
275    calling methods on the {@link android.view.Window Window} member
276    of the underlying View object for the window. Examples include calling {@link
277    android.app.Activity#getWindow() getWindow().requestFeature()} (or the convenience
278    method {@link android.app.Activity#requestWindowFeature(int) requestWindowFeature(<em>some_feature</em>)})
279    to hide the title. Here is an example of hiding the title bar:</p>
280<pre>//Hide the title bar
281requestWindowFeature(Window.FEATURE_NO_TITLE);
282</pre>
283<p>A better way to achieve the same end is to specify a theme in your Android
284Manifest file:</p>
285<pre>&lt;application android:icon="@drawable/icon" android:theme="@android:style/Theme.NoTitleBar"&gt;
286</pre>
287<p>This is preferable because it tells the system not to show a title bar while
288your application is starting up. With the explicit method call, your application
289will have a title bar visible to the user until <code>onCreate</code> runs.</p>
290<p>(Note that this can be applied to either the <code>&lt;application&gt;</code>
291tag or to individual <code>&lt;activity&gt;</code> tags.)</p>
292<p class="caution"><strong>Caution:</strong> This theme will also hide the Action Bar on Android
2933.0 and higher. If you want to keep the Action Bar, but hide the title bar, see how you can <a
294href="{@docRoot}guide/topics/ui/themes.html#SelectATheme">select a theme based on platform
295version</a>.</p>
296<a name="localhostalias" id="localhostalias"></a><h2>Referring to localhost from the emulated
297environment</h2>
298<p>
299If you need to refer to your host computer's <em>localhost</em>, such as when you
300want the emulator client to contact a server running on the same host, use the alias
301<code>10.0.2.2</code> to refer to the host computer's loopback interface.
302From the emulator's perspective, localhost (<code>127.0.0.1</code>) refers to its own
303loopback interface.
304</p>
305<a name="appstate" id="appstate"></a><h2>Storing and Retrieving State</h2>
306<p>If your application is dumped from memory because of space concerns, it will lose
307    all user interface state information such as checkbox state and text box values
308    as well as class member values. Android calls {@link android.app.Activity#onSaveInstanceState(android.os.Bundle)
309    Activity.onSaveInstanceState} before it pauses the application. This method hands in a {@link
310    android.os.Bundle Bundle} that can be used to store name/value pairs that will
311    persist and be handed back to the application even if it is dropped from memory.
312    Android will pass this Bundle back to you when it calls {@link android.app.Activity#onCreate(android.os.Bundle)
313    onCreate()}. This Bundle only exists while the application is still in the history
314    stack (whether or not it has been removed from memory) and will be lost when
315    the application is finalized. See the topics for {@link android.app.Activity#onSaveInstanceState} and
316    {@link android.app.Activity#onCreate} for
317    examples of storing and retrieving state.</p>
318<p>Read more about the lifecycle of an activity in <a
319href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a> document.</p>
320<h3>Storing and Retrieving Larger or More Complex Persistent Data<a name="storingandretrieving" id="storingandretrieving"></a></h3>
321<p>Your application can store files or complex collection objects, and reserve them
322    for private use by itself or other activities in the application, or it can expose
323    its data to all other applications on the device. See <a href="{@docRoot}guide/topics/data/data-storage.html">Storing,
324    Retrieving, and Exposing Data</a> to learn how to store and retrieve private data,
325    how to store and retrieve common data from the device, and how to expose your
326    private data to other applications.</p>
327<a name="playback" id="playback"></a><h2>Playing Media Files</h2>
328<p>Please see the document <a href="{@docRoot}guide/topics/media/index.html">Audio and Video</a> for more details.</p>
329<a name="broadcastreceivers" id="broadcastreceivers"></a><h2>Listening For and Broadcasting Global Messages, and Setting Alarms</h2>
330<p>You can create a listening class that can be notified or even instantiated whenever
331    a specific type of system message is sent.
332</p>
333<p>The listening classes, called broadcast receivers, extend {@link android.content.BroadcastReceiver
334    BroadcastReceiver}. If you want Android to instantiate the object whenever an appropriate
335    intent notification is sent, define the receiver with a <code>&lt;receiver&gt;</code> element
336    in the AndroidManifext.xml file. If the caller is expected to instantiate the
337    object in preparation to receive a message, this is not required. The receiver
338    will get a call to their {@link android.content.BroadcastReceiver#onReceive(android.content.Context,android.content.Intent)
339    BroadcastReceiver.onReceive()} method. A receiver can define an <code>&lt;intent-filter&gt;</code> tag
340    that describes the types of messages it will receive. Just as Android's IntentResolver
341    will look for appropriate Activity matches for a startActivity() call, it will
342    look for any matching Receivers (but it will send the message to all matching
343    receivers, not to the &quot;best&quot; match). </p>
344<p>To send a notification, the caller creates an {@link android.content.Intent Intent}
345    object and calls {@link android.app.Activity#sendBroadcast(android.content.Intent)
346    Context.sendBroadcast()} with that Intent. Multiple recipients can receive
347    the same message. You can broadcast an Intent message to an intent receiver in
348    any application, not only your own. If the receiving class is not registered
349    using <code>&lt;receiver&gt;</code> in its manifest, you can dynamically instantiate
350    and register a receiver by calling {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,android.content.IntentFilter)
351    Context.registerReceiver()}. </p>
352<p>Receivers can include intent filters to specify what kinds of intents they are
353    listening for. Alternatively, if you expect a single known caller to contact
354    a single known receiver, the receiver does not specify an intent filter, and
355    the caller specifies the receiver's class name in the Intent by calling {@link
356    android.content.Intent#setClassName(java.lang.String, java.lang.String) Intent.setClassName()}
357    with the recipient's class name. The recipient receives a {@link android.content.Context
358    Context} object that refers to its own package, not to the package of the sender.</p>
359<p><em><strong>Note:</strong></em>&nbsp;&nbsp;&nbsp;If a receiver or broadcaster
360    enforces permissions, your application might need to request permission
361    to send or receive messages from that object. You can request permission by using
362    the &lt;uses-permission&gt; tag in the manifest. </p>
363<p>Here is a code snippet of a sender and receiver. This example does not demonstrate
364    registering receivers dynamically. For a full code example, see the AlarmService
365    class in the ApiDemos project.</p>
366<h3>Sending the message</h3>
367<pre>// We are sending this to a specific recipient, so we will
368// only specify the recipient class name.
369Intent intent = new Intent(this, AlarmReceiver.class);
370intent.putExtra(&quot;message&quot;,&quot;Wake up.&quot;);
371sendBroadcast(intent);
372</pre>
373<h3>Receiving the message</h3>
374<p><strong>Receiver AndroidManifest.xml </strong>(because there is no intent filter
375    child, this class will only receive a broadcast when the receiver class is specified
376    by name, as is done in this example):</p>
377<pre>
378&lt;receiver class=".AlarmReceiver" /&gt;</pre>
379<p><strong>Receiver Java code: </strong></p>
380<pre>
381public class AlarmReceiver extends BroadcastReceiver{
382    // Display an alert that we've received a message.
383    &#064;Override
384    public void onReceive(Context context, Intent intent){
385	    // Send a text notification to the screen.
386        NotificationManager nm = (NotificationManager)
387        context.getSystemService(Context.NOTIFICATION_SERVICE);
388        nm.notifyWithText(R.id.alarm,
389                          &quot;Alarm!!!&quot;,
390                          NotificationManager.LENGTH_SHORT,
391                          null);
392   }
393}   </pre>
394<h3>Other system messages</h3>
395<p>You can listen for other system messages sent by Android as well, such as USB
396    connection/removal messages, SMS arrival messages, and timezone changes. See
397    {@link android.content.Intent} for a list of broadcast messages to listen for.
398    Messages are marked &quot;Broadcast Action&quot; in the documentation. </p>
399<h3>Listening for phone events<a name="phoneevents" id="phoneevents"></a></h3>
400<p>The {@link android.telephony android.telephony} package overview page describes how to
401    register to listen for phone events. </p>
402<a name="alarms" id="alarms"></a><h3>Setting Alarms </h3>
403<p>Android provides an {@link android.app.AlarmManager AlarmManager} service that
404    will let you specify an Intent to send at a designated time. This intent is typically
405    used to start an application at a preset time. (Note: If you want to send
406    a notification to a sleeping or running application, use {@link android.os.Handler
407    Handler} instead.)</p>
408<a name="alerts" id="alerts"></a><h2>Displaying Alerts</h2>
409<p>There are two major kinds of alerts that you may display to the user:
410(1) Normal alerts are displayed in response to a user action, such as
411trying to perform an action that is not allowed.  (2) Out-of-band alerts,
412called notifications, are
413displayed as a result of something happening in the background, such as the
414user receiving new e-mail.</p>
415
416<a name="dialogsandalerts" id="dialogsandalerts"></a><h3>Normal Alerts</h3>
417
418<p>Android provides a number of ways for you to show popup notifications to your
419    user as they interact with your application. </p>
420<table width="100%" border="1">
421    <tr>
422        <th scope="col">Class</th>
423        <th scope="col">Description</th>
424    </tr>
425    <tr>
426        <td>{@link android.app.Dialog app.Dialog}</td>
427        <td>A generic floating dialog box with a layout that you design. </td>
428    </tr>
429    <tr>
430        <td><p>{@link android.app.AlertDialog app.AlertDialog}</p></td>
431        <td>A popup alert dialog with two buttons (typically OK and Cancel) that
432            take callback handlers. See the section after this table for more details. </td>
433    </tr>
434    <tr>
435        <td>{@link android.app.ProgressDialog ProgressDialog} </td>
436        <td>A dialog box used to indicate progress of an operation with a known progress
437            value or an indeterminate length (setProgress(bool)). See <strong>Views</strong> &gt; <strong>Progress Bar</strong> in
438            ApiDemos for examples. </td>
439    </tr>
440    <tr>
441        <td>Activity</td>
442        <td>By setting the theme of an activity to
443            {@link android.R.style#Theme_Dialog
444            android:theme=&quot;&#064;android:style/Theme.Dialog&quot;},
445            your activity will take on
446            the appearance of a normal dialog, floating on top of whatever was
447            underneath it.  You usually set the theme through the
448            {@link android.R.attr#theme android:theme} attribute in your AndroidManifest.xml.
449            The advantage of this
450            over Dialog and AlertDialog is that Application has a much better managed
451            life cycle than dialogs: if a dialog goes to the background and is killed,
452            you cannot recapture state, whereas Application exposes a {@link android.os.Bundle
453            Bundle} of saved values in <code>onCreate()</code> to help you maintain state.</td>
454    </tr>
455</table>
456<h3>AlertDialog</h3>
457<p>This is a basic warning dialog box that lets you configure a message, button text,
458    and callback. You can create one by calling using the {@link
459    android.app.AlertDialog.Builder} class, as shown here. </p>
460<pre>private Handler mHandler = new Handler() {
461    public void handleMessage(Message msg) {
462        switch (msg.what) {
463            case ACCEPT_CALL:
464            answer(msg.obj);
465            break;
466
467            case BOUNCE_TO_VOICEMAIL:
468            voicemail(msg.obj);
469            break;
470
471        }
472    }
473};
474
475
476private void IncomingMotherInlawCall(Connection c) {
477    String Text;
478
479    // &quot;Answer&quot; callback.
480    Message acceptMsg = Message.obtain();
481    acceptMsg.target = mHandler;
482    acceptMsg.what = ACCEPT_CALL;
483    acceptMsg.obj = c.getCall();
484
485    // &quot;Cancel&quot; callback.
486    final Message rejectMsg = Message.obtain();
487    rejectMsg.target = mHandler;
488    rejectMsg.what = BOUNCE_TO_VOICEMAIL;
489    rejectMsg.obj = c.getCall();
490
491    new AlertDialog.Builder(this)
492      .setMessage("Phyllis is calling")
493      .setPositiveButton("Answer", acceptMsg)
494      .setOnCanceListener(new OnCancelListener() {
495        public void onCancel(DialogInterface dialog) {
496          rejectMsg.sendToTarget();
497        }});
498      .show();
499}    </pre>
500
501<h3>Notifications</h3>
502
503<p>Out-of-band alerts should always be displayed using the
504{@link android.app.NotificationManager}, which allows you to tell the user
505about something they may be interested in without disrupting what they are
506currently doing.  A notification can be anything from a brief pop-up box
507informing the user of the new information, through displaying a persistent
508icon in the status bar, to vibrating, playing sounds, or flashing lights to
509get the user's attention.  In all cases, the user must explicitly shift their
510focus to the notification before they can interact with it.</p>
511
512<p>The following code demonstrates using NotificationManager to display a basic text
513    popup when a new SMS message arrives in a listening service, and provides the
514    current message count. You can see several more examples in the ApiDemos application,
515    under app/ (named <em>notification</em>*.java).</p>
516<pre>static void setNewMessageIndicator(Context context, int messageCount){
517   // Get the static global NotificationManager object.
518   NotificationManager nm = NotificationManager.getDefault();</p>
519
520   // If we're being called because a new message has been received,
521   // then display an icon and a count. Otherwise, delete the persistent
522   // message.
523   if (messageCount &gt; 0) {
524      nm.notifyWithText(myApp.NOTIFICATION_GUID,      // ID for this notification.
525                messageCount + &quot; new message&quot; + messageCount &gt; 1 ? &quot;s&quot;:&quot;&quot;, // Text to display.
526                NotificationManager.LENGTH_SHORT); // Show it for a short time only.
527   }
528}</pre>
529<p>To display a notification in the status bar and have it launch an intent when
530    the user selects it (such as the new text message notification does), call {@link
531    android.app.NotificationManager#notify(int, android.app.Notification) NotificationManager.notify()},
532    and pass in vibration patterns, status bar icons, or Intents to associate with
533    the notification. </p>
534<a name="progressbar" id="progressbar"></a><h2>Displaying a Progress Bar</h2>
535<p>An activity can display a progress bar to notify the user that something is happening.
536    To display a progress bar in a screen, call {@link android.app.Activity#requestWindowFeature(int)
537    Activity.requestWindowFeature(Window.FEATURE_PROGRESS)}. To set the value
538    of the progress bar, call {@link android.view.Window#setFeatureInt(int,int)
539    Activity.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, <em>level</em>)}.
540    Progress bar values are from 0 to 9,999, or set the value to 10,000 to make the
541    progress bar invisible. </p>
542<p>You can also use the {@link android.app.ProgressDialog ProgressDialog} class,
543    which enables a  dialog box with an embedded progress bar to send a &quot;I'm working
544    on it&quot; notification to the user. </p>
545<a name="addmenuitems" id="addmenuitems"></a><h2>Adding Items to the Screen Menu</h2>
546<p>See <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a>.</p>
547
548<a name="webpage" id="webpage"></a><h2>Display a Web Page</h2>
549<p>Use the {@link android.webkit.WebView webkit.WebView} object. </p>
550<a name="binding" id="binding"></a><h2>Binding to Data</h2>
551<p>You can bind a ListView to a set of underlying data by using a shim class called
552    {@link android.widget.ListAdapter ListAdapter} (or a subclass). ListAdapter subclasses
553    bind to a variety of data sources, and expose a common set of methods such as
554    getItem() and getView(), and uses them to pick View items to display in its list.
555    You can extend ListAdapter and override getView() to create your own custom list
556    items. There are essentially only two steps you need to perform to bind to data: </p>
557<ol>
558    <li>Create a ListAdapter object and specify its data source</li>
559    <li>Give the ListAdapter to your ListView object.</li>
560</ol>
561<p>That's it!</p>
562<p>Here's an example of binding a ListActivity screen to the results from a cursor
563    query. (Note that the setListAdapter() method shown is a convenience method that
564    gets the page's ListView object and calls setAdapter() on it.)</p>
565<pre>// Run a query and get a Cursor pointing to the results.
566Cursor c = People.query(this.getContentResolver(), null);
567startManagingCursor(c);
568
569// Create the ListAdapter. A SimpleCursorAdapter lets you specify two interesting things:
570// an XML template for your list item, and
571// The column to map to a specific item, by ID, in your template.
572ListAdapter adapter = new SimpleCursorAdapter(this,
573                android.R.layout.simple_list_item_1,  // Use a template that displays a text view
574                c,                                    // Give the cursor to the list adapter
575                new String[] {People.NAME} ,          // Map the NAME column in the people database to...
576                new String[] {"text1"});              // The "text1" view defined in the XML template
577setListAdapter(adapter);</pre>
578<p>See view/List4 in the ApiDemos project for an example of extending ListAdapter
579    for a new data type. </p>
580
581<a name="handle"></a>
582
583<h2>Getting a Handle to a Screen Element</h2>
584<p>You can get a handle to a screen element by calling {@link
585android.app.Activity#findViewById(int) Activity.findViewById}. You can then use
586the handle to set or retrieve any values exposed by the object. </p>
587<a name="captureimages" id="captureimages"></a><h2>Capture Images from the Phone Camera</h2>
588<p>You can hook into the device's camera onto your own Canvas object by using the
589    {@link android.hardware.Camera Camera} class. See that class's documentation,
590    and the ApiDemos project's Camera Preview application (Graphics/Camera Preview)
591    for example code. </p>
592
593
594<a name="threading" id="threading"></a><h2>Handling Expensive Operations in the UI Thread</h2>
595<p>Avoid performing long-running operations (such as network I/O) directly in the UI thread &mdash;
596the main thread of an application where the UI is run &mdash; or your application may be blocked
597and become unresponsive. Here is a brief summary of the recommended approach for handling expensive operations:</p>
598<ol>
599<li>Create a Handler object in your UI thread</li>
600<li>Spawn off worker threads to perform any required expensive operations</li>
601<li>Post results from a worker thread back to the UI thread's handler either through a Runnable or a {@link android.os.Message}</li>
602<li>Update the views on the UI thread as needed</li>
603</ol>
604
605<p>The following outline illustrates a typical implementation:</p>
606
607<pre>
608public class MyActivity extends Activity {
609
610    [ . . . ]
611    // Need handler for callbacks to the UI thread
612    final Handler mHandler = new Handler();
613
614    // Create runnable for posting
615    final Runnable mUpdateResults = new Runnable() {
616        public void run() {
617            updateResultsInUi();
618        }
619    };
620
621    &#64;Override
622    protected void onCreate(Bundle savedInstanceState) {
623        super.onCreate(savedInstanceState);
624
625        [ . . . ]
626    }
627
628    protected void startLongRunningOperation() {
629
630        // Fire off a thread to do some work that we shouldn't do directly in the UI thread
631        Thread t = new Thread() {
632            public void run() {
633                mResults = doSomethingExpensive();
634                mHandler.post(mUpdateResults);
635            }
636        };
637        t.start();
638    }
639
640    private void updateResultsInUi() {
641
642        // Back in the UI thread -- update our UI elements based on the data in mResults
643        [ . . . ]
644    }
645}
646</pre>
647
648<p>For further discussions on this topic, see
649<a href="{@docRoot}guide/practices/design/responsiveness.html">Designing for Responsiveness</a>
650and the {@link android.os.Handler} documentation.</p>
651
652<a name="selectingtext" id="selectingtext"></a><h2>Selecting, Highlighting, or Styling Portions of Text</h2>
653<p>You can highlight or style the formatting of strings or substrings of text in
654    a TextView object. There are two ways to do this:</p>
655<ul>
656    <li>If you use a <a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources">string resource</a>,
657        you can add some simple styling, such as bold or italic using HTML notation.
658        The currently supported tags are: <code>B</code> (bold),
659        <code>I</code> (italic), <code>U</code> (underline),
660        <code>TT</code> (monospace), <code>BIG</code>, <code>SMALL</code>,
661        <code>SUP</code> (superscript), <code>SUB</code> (subscript),
662        and <code>STRIKE</code> (strikethrough).
663        So, for example, in res/values/strings.xml you could declare this:<br />
664        <code>&lt;resource&gt;<br />
665        &nbsp;&nbsp;&nbsp;&nbsp;&lt;string&nbsp;id=&quot;@+id/styled_welcome_message&quot;&gt;We
666        are &lt;b&gt;&lt;i&gt;so&lt;/i&gt;&lt;/b&gt; glad to see you.&lt;/string&gt;<br />
667        &lt;/resources&gt;</code></li>
668    <li>To style text on the fly, or to add highlighting or more complex styling,
669        you must use the Spannable object as described next. </li>
670</ul>
671<p>To style text on the fly, you must make sure the TextView is using {@link android.text.Spannable}
672    storage for the text (this will always be true if the TextView is an EditText),
673    retrieve its text with {@link android.widget.TextView#getText}, and call {@link
674    android.text.Spannable#setSpan}, passing in a new style class from the {@link
675    android.text.style} package and the selection range. </p>
676<p>The following code snippet demonstrates creating a string with a highlighted section,
677    italic section, and bold section, and adding it to an EditText object. </p>
678<pre>// Get our EditText object.
679EditText vw = (EditText)findViewById(R.id.text);
680
681// Set the EditText's text.
682vw.setText("Italic, highlighted, bold.");
683
684// If this were just a TextView, we could do:
685// vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE);
686// to force it to use Spannable storage so styles can be attached.
687// Or we could specify that in the XML.
688
689// Get the EditText's internal text storage
690Spannable str = vw.getText();
691
692// Create our span sections, and assign a format to each.
693str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
694str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
695str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
696</pre>
697
698<a name="querymap" id="querymap"></a><h2>Utilizing attributes in a Map query</h2>
699<p>
700When using a search intent to ask the Maps activity to search for something, the Maps activity responds to the following attributes in the optional context bundle:
701</p>
702<pre>
703               float "centerLatitude" default 0.0f
704               float "centerLongitude" default 0.0f
705               float "latitudeSpan" default 0.0f
706               float "longitudeSpan" default 0.0f
707               int "zoomLevel" default 10
708</pre>
709<p>
710This 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.
711</p>
712<p>
713If the latitudeSpan, longitudeSpan, and zoomLevel attributes are not consistent, then it is undefined which one takes precedence.
714</p>
715
716<a name="filelist" id="filelist"></a><h2>List of Files for an Android Application</h2>
717<p>The following list describes the structure and files of an Android application.
718    Many of these files can be built for you (or stubbed out) by the android tool
719    shipped in the tools/ menu of the SDK. </p>
720<table width="100%" border="0">
721    <tr>
722        <td width="28%" valign="top">MyApp/<br /></td>
723        <td width="72%" valign="top">&nbsp;</td>
724    </tr>
725    <tr>
726        <td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;AndroidManifest.xml</td>
727        <td valign="top">(<em>required</em>) Advertises the screens that this application provides,
728            where they can be launched (from the main program menu or elsewhere),
729            any content providers it implements and what kind of data they handle,
730            where the implementation classes are, and other application-wide
731            information. Syntax details for this file are described in <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">The AndroidManifest.xml File</a>.</td>
732    </tr>
733    <tr>
734        <td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;src/<br />
735        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/<em>myPackagePath</em>/.../<em>MyClass</em>.java</td>
736        <td valign="top">(<em>required</em>) This folder holds all the source code files for your
737            application, inside the appropriate package subfolders. </td>
738    </tr>
739    <tr>
740        <td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;res/</td>
741        <td valign="top">(<em>required</em>) This folder holds all the <em>resources</em> for
742            your application. Resources are external data files or description files
743            that are compiled into your code at build time. Files in different folders
744            are compiled differently, so you must put the proper resource into the
745            proper folder. (See <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources</a> for details.)</td>
746    </tr>
747    <tr>
748        <td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;anim/<br />
749            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>animation1</em>.xml<br />
750        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>...</em></td>
751        <td valign="top">(<em>optional</em>) Holds any animation XML description files that the
752            application uses. The format of these files is described in <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources</a>. </td>
753    </tr>
754    <tr>
755        <td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;drawable/<br />
756            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>some_picture</em>.png<br />
757            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>some_stretchable</em>.9.png<br />
758            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>some_background</em>.xml<br />
759        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;...</td>
760        <td valign="top">(<em>optional</em>) Zero or more files that will be compiled to {@link
761            android.graphics.drawable android.graphics.drawable} resources. Files
762            can be image files (png, gif, or other) or XML files describing other
763            graphics such as bitmaps, stretchable bitmaps, or gradients. Supported
764            bitmap file formats are PNG (preferred), JPG, and GIF (discouraged),
765            as well as the custom 9-patch stretchable bitmap format. These formats
766            are described in <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources</a>. </td>
767    </tr>
768    <tr>
769        <td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;layout/<br />
770            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>screen_1_layout</em>.xml<br />
771        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;...<br /></td>
772        <td valign="top">(<em>optional</em>) Holds all the XML files describing screens or parts
773            of screens. Although you could create a screen in Java, defining them
774            in XML files is typically easier. A layout file is similar in concept
775            to an HTML file that describes the screen layout and components. See <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> for more information about designing screens, and <a href="{@docRoot}guide/topics/resources/available-resources.html#layoutresources">Available Resource Types</a> for the syntax of these files.</td>
776    </tr>
777    <tr>
778        <td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;values/<br />
779            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;arrays<br />
780  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;          &nbsp;classes.xml<br />
781            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;colors.xml<br />
782            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dimens.xml<br />
783&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;            strings.xml<br />
784        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;styles.xml<br />
785        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;values.xml<br /></td>
786        <td valign="top"><p>(<em>optional</em>) XML files describing additional resources
787                such as strings, colors, and styles. The naming, quantity, and number
788                of these files are not enforced--any XML file is compiled, but these
789                are the standard names given to these files. However, the syntax
790                of these files is prescribed by Android, and described in <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources</a>. </p>
791        </td>
792    </tr>
793    <tr>
794        <td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;xml/</td>
795        <td valign="top">(<em>optional</em>) XML files that can be read at run time on the device. </td>
796    </tr>
797    <tr>
798        <td valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;raw/</td>
799        <td valign="top">(<em>optional</em>) Any files to be copied directly to the device. </td>
800    </tr>
801</table>
802
803
804<a name="logging" ></a>
805<h2>Print Messages to a Log File</h2>
806
807<p>To write log messages from your application:</p>
808<ol><li>Import <code>android.util.Log</code>.</li>
809    <li>Use <code>Log.v()</code>, <code>Log.d()</code>, <code>Log.i()</code>,
810    <code>Log.w()</code>, or <code>Log.e()</code> to log messages.
811    (See the {@link android.util.Log} class.)<br/> E.g.,
812    <code>Log.e(this.toString(), "error: " + err.toString())</code></li>
813    <li>Launch <a href="{@docRoot}guide/developing/tools/ddms.html">DDMS</a> from a terminal
814    by executing <code>ddms</code> in your Android SDK <code>/tools</code> path.</li>
815    <li>Run your application in the Android emulator.</li>
816    <li>From the DDMS application, select the emulator
817    (e.g., "emulator-5554") and click <b>Device > Run logcat...</b>
818    to view all the log data.</li>
819</ol>
820<p class="note"><strong>Note:</strong> If you are running Eclipse and
821encounter a warning about the VM debug port when opening DDMS, you can ignore it
822if you're only interested in logs. However, if you want to further inspect and
823control your processes from DDMS, then you should close Eclipse before launching DDMS so that
824it may use the VM debugging port.</p>
825
826
827