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