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/other-ide.html#buildingwithant">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. See <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">Lifecycles</a> 128 discussion in Application Fundamentals 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 <a 154 href="{@docRoot}guide/topics/fundamentals.html#lcycles">Lifecycles</a> discussion 155 in Application Fundamentals for details. </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>@android:style/Theme.Dialog</code> 162 in your AndroidManifest.xml file. For example: 163 <pre><activity class="AddRssItem" android:label="Add an item" android:theme="@android:style/Theme.Dialog"/> 164 </pre></li> 165 </ul> 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(); 186 myIntent.setClassName("com.android.samples", "com.android.samples.Animation1"); 187 myIntent.putExtra("com.android.samples.SpecialValue", "Hello, Joe!"); // key/value pair, where key needs current package prefix. 188 startActivity(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 "http://" schema:</p> 191 <pre>Intent myIntent = new Intent(Intent.VIEW_ACTION, Uri.parse("http://www.google.com"));</pre> 192 <p>Here is the intent filter from the AndroidManifest.xml file for com.android.browser:</p> 193 <pre><intent-filter> 194 <action android:name="android.intent.action.VIEW" /> 195 <category android:name="android.intent.category.DEFAULT" /> 196 <scheme android:name="http" /> 197 <scheme android:name="https" /> 198 <scheme android:name="file" /> 199 </intent-filter> </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 <intent-filter> 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. 215 public 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. 223 protected void onActivityResult(int requestCode, int resultCode, Intent data){ 224 // See which child activity is calling us back. 225 switch (resultCode) { 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", Bundle); 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 href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a> on the UI Design page.</p> 271 <a name="configurewindowproperties" id="configurewindowproperties"></a><h2>Configuring General Window Properties</h2> 272 <p>You can set a number of general window properties, such as whether to display 273 a title, whether the window is floating, and whether it displays an icon, by 274 calling methods on the {@link android.view.Window Window} member 275 of the underlying View object for the window. Examples include calling {@link 276 android.app.Activity#getWindow() getWindow().requestFeature()} (or the convenience 277 method {@link android.app.Activity#requestWindowFeature(int) requestWindowFeature(<em>some_feature</em>)}) 278 to hide the title. Here is an example of hiding the title bar:</p> 279 <pre>//Hide the title bar 280 requestWindowFeature(Window.FEATURE_NO_TITLE); 281 </pre> 282 <p>A better way to achieve the same end is to specify a theme in your Android 283 Manifest file:</p> 284 <pre><application android:icon="@drawable/icon" android:theme="@android:style/Theme.NoTitleBar"> 285 </pre> 286 <p>This is preferable because it tells the system not to show a title bar while 287 your application is starting up. With the explicit method call, your application 288 will have a title bar visible to the user until <code>onCreate</code> runs.</p> 289 <p>(Note that this can be applied to either the <code><application></code> 290 tag or to individual <code><activity></code> tags.)</p> 291 <a name="localhostalias" id="localhostalias"></a><h2>Referring to localhost from the emulated environment</h2> 292 <p> 293 If you need to refer to your host computer's <em>localhost</em>, such as when you 294 want the emulator client to contact a server running on the same host, use the alias 295 <code>10.0.2.2</code> to refer to the host computer's loopback interface. 296 From the emulator's perspective, localhost (<code>127.0.0.1</code>) refers to its own 297 loopback interface. 298 </p> 299 <a name="appstate" id="appstate"></a><h2>Storing and Retrieving State</h2> 300 <p>If your application is dumped from memory because of space concerns, it will lose 301 all user interface state information such as checkbox state and text box values 302 as well as class member values. Android calls {@link android.app.Activity#onSaveInstanceState(android.os.Bundle) 303 Activity.onSaveInstanceState} before it pauses the application. This method hands in a {@link 304 android.os.Bundle Bundle} that can be used to store name/value pairs that will 305 persist and be handed back to the application even if it is dropped from memory. 306 Android will pass this Bundle back to you when it calls {@link android.app.Activity#onCreate(android.os.Bundle) 307 onCreate()}. This Bundle only exists while the application is still in the history 308 stack (whether or not it has been removed from memory) and will be lost when 309 the application is finalized. See the topics for {@link android.app.Activity#onSaveInstanceState} and 310 {@link android.app.Activity#onCreate} for 311 examples of storing and retrieving state.</p> 312 <p>Read more about the lifecycle of an application in <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>.</p> 313 <h3>Storing and Retrieving Larger or More Complex Persistent Data<a name="storingandretrieving" id="storingandretrieving"></a></h3> 314 <p>Your application can store files or complex collection objects, and reserve them 315 for private use by itself or other activities in the application, or it can expose 316 its data to all other applications on the device. See <a href="{@docRoot}guide/topics/data/data-storage.html">Storing, 317 Retrieving, and Exposing Data</a> to learn how to store and retrieve private data, 318 how to store and retrieve common data from the device, and how to expose your 319 private data to other applications.</p> 320 <a name="playback" id="playback"></a><h2>Playing Media Files</h2> 321 <p>Please see the document <a href="{@docRoot}guide/topics/media/index.html">Audio and Video</a> for more details.</p> 322 <a name="broadcastreceivers" id="broadcastreceivers"></a><h2>Listening For and Broadcasting Global Messages, and Setting Alarms</h2> 323 <p>You can create a listening class that can be notified or even instantiated whenever 324 a specific type of system message is sent. 325 </p> 326 <p>The listening classes, called broadcast receivers, extend {@link android.content.BroadcastReceiver 327 BroadcastReceiver}. If you want Android to instantiate the object whenever an appropriate 328 intent notification is sent, define the receiver with a <code><receiver></code> element 329 in the AndroidManifest.xml file. If the caller is expected to instantiate the 330 object in preparation to receive a message, this is not required. The receiver 331 will get a call to their {@link android.content.BroadcastReceiver#onReceive(android.content.Context,android.content.Intent) 332 BroadcastReceiver.onReceive()} method. A receiver can define an <code><intent-filter></code> tag 333 that describes the types of messages it will receive. Just as Android's IntentResolver 334 will look for appropriate Activity matches for a startActivity() call, it will 335 look for any matching Receivers (but it will send the message to all matching 336 receivers, not to the "best" match). </p> 337 <p>To send a notification, the caller creates an {@link android.content.Intent Intent} 338 object and calls {@link android.app.Activity#sendBroadcast(android.content.Intent) 339 Context.sendBroadcast()} with that Intent. Multiple recipients can receive 340 the same message. You can broadcast an Intent message to an intent receiver in 341 any application, not only your own. If the receiving class is not registered 342 using <code><receiver></code> in its manifest, you can dynamically instantiate 343 and register a receiver by calling {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,android.content.IntentFilter) 344 Context.registerReceiver()}. </p> 345 <p>Receivers can include intent filters to specify what kinds of intents they are 346 listening for. Alternatively, if you expect a single known caller to contact 347 a single known receiver, the receiver does not specify an intent filter, and 348 the caller specifies the receiver's class name in the Intent by calling {@link 349 android.content.Intent#setClassName(java.lang.String, java.lang.String) Intent.setClassName()} 350 with the recipient's class name. The recipient receives a {@link android.content.Context 351 Context} object that refers to its own package, not to the package of the sender.</p> 352 <p><em><strong>Note:</strong></em> If a receiver or broadcaster 353 enforces permissions, your application might need to request permission 354 to send or receive messages from that object. You can request permission by using 355 the <uses-permission> tag in the manifest. </p> 356 <p>Here is a code snippet of a sender and receiver. This example does not demonstrate 357 registering receivers dynamically. For a full code example, see the AlarmService 358 class in the ApiDemos project.</p> 359 <h3>Sending the message</h3> 360 <pre>// We are sending this to a specific recipient, so we will 361 // only specify the recipient class name. 362 Intent intent = new Intent(this, AlarmReceiver.class); 363 intent.putExtra("message","Wake up."); 364 sendBroadcast(intent); 365 </pre> 366 <h3>Receiving the message</h3> 367 <p><strong>Receiver AndroidManifest.xml </strong>(because there is no intent filter 368 child, this class will only receive a broadcast when the receiver class is specified 369 by name, as is done in this example):</p> 370 <pre> 371 <receiver class=".AlarmReceiver" /></pre> 372 <p><strong>Receiver Java code: </strong></p> 373 <pre> 374 public class AlarmReceiver extends BroadcastReceiver{ 375 // Display an alert that we've received a message. 376 @Override 377 public void onReceive(Context context, Intent intent){ 378 // Send a text notification to the screen. 379 NotificationManager nm = (NotificationManager) 380 context.getSystemService(Context.NOTIFICATION_SERVICE); 381 nm.notifyWithText(R.id.alarm, 382 "Alarm!!!", 383 NotificationManager.LENGTH_SHORT, 384 null); 385 } 386 } </pre> 387 <h3>Other system messages</h3> 388 <p>You can listen for other system messages sent by Android as well, such as USB 389 connection/removal messages, SMS arrival messages, and timezone changes. See 390 {@link android.content.Intent} for a list of broadcast messages to listen for. 391 Messages are marked "Broadcast Action" in the documentation. </p> 392 <h3>Listening for phone events<a name="phoneevents" id="phoneevents"></a></h3> 393 <p>The {@link android.telephony android.telephony} package overview page describes how to 394 register to listen for phone events. </p> 395 <a name="alarms" id="alarms"></a><h3>Setting Alarms </h3> 396 <p>Android provides an {@link android.app.AlarmManager AlarmManager} service that 397 will let you specify an Intent to send at a designated time. This intent is typically 398 used to start an application at a preset time. (Note: If you want to send 399 a notification to a sleeping or running application, use {@link android.os.Handler 400 Handler} instead.)</p> 401 <a name="alerts" id="alerts"></a><h2>Displaying Alerts</h2> 402 <p>There are two major kinds of alerts that you may display to the user: 403 (1) Normal alerts are displayed in response to a user action, such as 404 trying to perform an action that is not allowed. (2) Out-of-band alerts, 405 called notifications, are 406 displayed as a result of something happening in the background, such as the 407 user receiving new e-mail.</p> 408 409 <a name="dialogsandalerts" id="dialogsandalerts"></a><h3>Normal Alerts</h3> 410 411 <p>Android provides a number of ways for you to show popup notifications to your 412 user as they interact with your application. </p> 413 <table width="100%" border="1"> 414 <tr> 415 <th scope="col">Class</th> 416 <th scope="col">Description</th> 417 </tr> 418 <tr> 419 <td>{@link android.app.Dialog app.Dialog}</td> 420 <td>A generic floating dialog box with a layout that you design. </td> 421 </tr> 422 <tr> 423 <td><p>{@link android.app.AlertDialog app.AlertDialog}</p></td> 424 <td>A popup alert dialog with two buttons (typically OK and Cancel) that 425 take callback handlers. See the section after this table for more details. </td> 426 </tr> 427 <tr> 428 <td>{@link android.app.ProgressDialog ProgressDialog} </td> 429 <td>A dialog box used to indicate progress of an operation with a known progress 430 value or an indeterminate length (setProgress(bool)). See <strong>Views</strong> > <strong>Progress Bar</strong> in 431 ApiDemos for examples. </td> 432 </tr> 433 <tr> 434 <td>Activity</td> 435 <td>By setting the theme of an activity to 436 {@link android.R.style#Theme_Dialog 437 android:theme="@android:style/Theme.Dialog"}, 438 your activity will take on 439 the appearance of a normal dialog, floating on top of whatever was 440 underneath it. You usually set the theme through the 441 {@link android.R.attr#theme android:theme} attribute in your AndroidManifest.xml. 442 The advantage of this 443 over Dialog and AlertDialog is that Application has a much better managed 444 life cycle than dialogs: if a dialog goes to the background and is killed, 445 you cannot recapture state, whereas Application exposes a {@link android.os.Bundle 446 Bundle} of saved values in <code>onCreate()</code> to help you maintain state.</td> 447 </tr> 448 </table> 449 <h3>AlertDialog</h3> 450 <p>This is a basic warning dialog box that lets you configure a message, button text, 451 and callback. You can create one by calling using the {@link 452 android.app.AlertDialog.Builder} class, as shown here. </p> 453 <pre>private Handler mHandler = new Handler() { 454 public void handleMessage(Message msg) { 455 switch (msg.what) { 456 case ACCEPT_CALL: 457 answer(msg.obj); 458 break; 459 460 case BOUNCE_TO_VOICEMAIL: 461 voicemail(msg.obj); 462 break; 463 464 } 465 } 466 }; 467 468 469 private void IncomingMotherInLawCall(Connection c) { 470 String Text; 471 472 // "Answer" callback. 473 Message acceptMsg = Message.obtain(); 474 acceptMsg.target = mHandler; 475 acceptMsg.what = ACCEPT_CALL; 476 acceptMsg.obj = c.getCall(); 477 478 // "Cancel" callback. 479 final Message rejectMsg = Message.obtain(); 480 rejectMsg.target = mHandler; 481 rejectMsg.what = BOUNCE_TO_VOICEMAIL; 482 rejectMsg.obj = c.getCall(); 483 484 new AlertDialog.Builder(this) 485 .setMessage("Phyllis is calling") 486 .setPositiveButton("Answer", acceptMsg) 487 .setOnCancelListener(new OnCancelListener() { 488 public void onCancel(DialogInterface dialog) { 489 rejectMsg.sendToTarget(); 490 }}); 491 .show(); 492 } </pre> 493 494 <h3>Notifications</h3> 495 496 <p>Out-of-band alerts should always be displayed using the 497 {@link android.app.NotificationManager}, which allows you to tell the user 498 about something they may be interested in without disrupting what they are 499 currently doing. A notification can be anything from a brief pop-up box 500 informing the user of the new information, through displaying a persistent 501 icon in the status bar, to vibrating, playing sounds, or flashing lights to 502 get the user's attention. In all cases, the user must explicitly shift their 503 focus to the notification before they can interact with it.</p> 504 505 <p>The following code demonstrates using NotificationManager to display a basic text 506 popup when a new SMS message arrives in a listening service, and provides the 507 current message count. You can see several more examples in the ApiDemos application, 508 under app/ (named <em>notification</em>*.java).</p> 509 <pre>static void setNewMessageIndicator(Context context, int messageCount){ 510 // Get the static global NotificationManager object. 511 NotificationManager nm = NotificationManager.getDefault();</p> 512 513 // If we're being called because a new message has been received, 514 // then display an icon and a count. Otherwise, delete the persistent 515 // message. 516 if (messageCount > 0) { 517 nm.notifyWithText(myApp.NOTIFICATION_GUID, // ID for this notification. 518 messageCount + " new message" + messageCount > 1 ? "s":"", // Text to display. 519 NotificationManager.LENGTH_SHORT); // Show it for a short time only. 520 } 521 }</pre> 522 <p>To display a notification in the status bar and have it launch an intent when 523 the user selects it (such as the new text message notification does), call {@link 524 android.app.NotificationManager#notify(int, android.app.Notification) NotificationManager.notify()}, 525 and pass in vibration patterns, status bar icons, or Intents to associate with 526 the notification. </p> 527 <a name="progressbar" id="progressbar"></a><h2>Displaying a Progress Bar</h2> 528 <p>An activity can display a progress bar to notify the user that something is happening. 529 To display a progress bar in a screen, call {@link android.app.Activity#requestWindowFeature(int) 530 Activity.requestWindowFeature(Window.FEATURE_PROGRESS)}. To set the value 531 of the progress bar, call {@link android.view.Window#setFeatureInt(int,int) 532 Activity.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, <em>level</em>)}. 533 Progress bar values are from 0 to 9,999, or set the value to 10,000 to make the 534 progress bar invisible. </p> 535 <p>You can also use the {@link android.app.ProgressDialog ProgressDialog} class, 536 which enables a dialog box with an embedded progress bar to send a "I'm working 537 on it" notification to the user. </p> 538 <a name="addmenuitems" id="addmenuitems"></a><h2>Adding Items to the Screen Menu</h2> 539 <p>See <a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>.</p> 540 541 <a name="webpage" id="webpage"></a><h2>Display a Web Page</h2> 542 <p>Use the {@link android.webkit.WebView webkit.WebView} object. </p> 543 <a name="binding" id="binding"></a><h2>Binding to Data</h2> 544 <p>You can bind a ListView to a set of underlying data by using a shim class called 545 {@link android.widget.ListAdapter ListAdapter} (or a subclass). ListAdapter subclasses 546 bind to a variety of data sources, and expose a common set of methods such as 547 getItem() and getView(), and uses them to pick View items to display in its list. 548 You can extend ListAdapter and override getView() to create your own custom list 549 items. There are essentially only two steps you need to perform to bind to data: </p> 550 <ol> 551 <li>Create a ListAdapter object and specify its data source</li> 552 <li>Give the ListAdapter to your ListView object.</li> 553 </ol> 554 <p>That's it!</p> 555 <p>Here's an example of binding a ListActivity screen to the results from a cursor 556 query. (Note that the setListAdapter() method shown is a convenience method that 557 gets the page's ListView object and calls setAdapter() on it.)</p> 558 <pre>// Run a query and get a Cursor pointing to the results. 559 Cursor c = People.query(this.getContentResolver(), null); 560 startManagingCursor(c); 561 562 // Create the ListAdapter. A SimpleCursorAdapter lets you specify two interesting things: 563 // an XML template for your list item, and 564 // The column to map to a specific item, by ID, in your template. 565 ListAdapter adapter = new SimpleCursorAdapter(this, 566 android.R.layout.simple_list_item_1, // Use a template that displays a text view 567 c, // Give the cursor to the list adapter 568 new String[] {People.NAME} , // Map the NAME column in the people database to... 569 new String[] {"text1"}); // The "text1" view defined in the XML template 570 setListAdapter(adapter);</pre> 571 <p>See view/List4 in the ApiDemos project for an example of extending ListAdapter 572 for a new data type. </p> 573 574 <a name="handle"></a> 575 576 <h2>Getting a Handle to a Screen Element</h2> 577 <p>You can get a handle to a screen element by calling {@link 578 android.app.Activity#findViewById(int) Activity.findViewById}. You can then use 579 the handle to set or retrieve any values exposed by the object. </p> 580 <a name="captureimages" id="captureimages"></a><h2>Capture Images from the Phone Camera</h2> 581 <p>You can hook into the device's camera onto your own Canvas object by using the 582 {@link android.hardware.Camera Camera} class. See that class's documentation, 583 and the ApiDemos project's Camera Preview application (Graphics/Camera Preview) 584 for example code. </p> 585 586 587 <a name="threading" id="threading"></a><h2>Handling Expensive Operations in the UI Thread</h2> 588 <p>Avoid performing long-running operations (such as network I/O) directly in the UI thread — 589 the main thread of an application where the UI is run — or your application may be blocked 590 and become unresponsive. Here is a brief summary of the recommended approach for handling expensive operations:</p> 591 <ol> 592 <li>Create a Handler object in your UI thread</li> 593 <li>Spawn off worker threads to perform any required expensive operations</li> 594 <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> 595 <li>Update the views on the UI thread as needed</li> 596 </ol> 597 598 <p>The following outline illustrates a typical implementation:</p> 599 600 <pre> 601 public class MyActivity extends Activity { 602 603 [ . . . ] 604 // Need handler for callbacks to the UI thread 605 final Handler mHandler = new Handler(); 606 607 // Create runnable for posting 608 final Runnable mUpdateResults = new Runnable() { 609 public void run() { 610 updateResultsInUi(); 611 } 612 }; 613 614 @Override 615 protected void onCreate(Bundle savedInstanceState) { 616 super.onCreate(savedInstanceState); 617 618 [ . . . ] 619 } 620 621 protected void startLongRunningOperation() { 622 623 // Fire off a thread to do some work that we shouldn't do directly in the UI thread 624 Thread t = new Thread() { 625 public void run() { 626 mResults = doSomethingExpensive(); 627 mHandler.post(mUpdateResults); 628 } 629 }; 630 t.start(); 631 } 632 633 private void updateResultsInUi() { 634 635 // Back in the UI thread -- update our UI elements based on the data in mResults 636 [ . . . ] 637 } 638 } 639 </pre> 640 641 <p>For further discussions on this topic, see 642 <a href="{@docRoot}guide/practices/design/responsiveness.html">Designing for Responsiveness</a> 643 and the {@link android.os.Handler} documentation.</p> 644 645 <a name="selectingtext" id="selectingtext"></a><h2>Selecting, Highlighting, or Styling Portions of Text</h2> 646 <p>You can highlight or style the formatting of strings or substrings of text in 647 a TextView object. There are two ways to do this:</p> 648 <ul> 649 <li>If you use a <a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources">string resource</a>, 650 you can add some simple styling, such as bold or italic using HTML notation. 651 The currently supported tags are: <code>B</code> (bold), 652 <code>I</code> (italic), <code>U</code> (underline), 653 <code>TT</code> (monospace), <code>BIG</code>, <code>SMALL</code>, 654 <code>SUP</code> (superscript), <code>SUB</code> (subscript), 655 and <code>STRIKE</code> (strikethrough). 656 So, for example, in res/values/strings.xml you could declare this:<br /> 657 <code><resource><br /> 658 <string id="@+id/styled_welcome_message">We 659 are <b><i>so</i></b> glad to see you.</string><br /> 660 </resources></code></li> 661 <li>To style text on the fly, or to add highlighting or more complex styling, 662 you must use the Spannable object as described next. </li> 663 </ul> 664 <p>To style text on the fly, you must make sure the TextView is using {@link android.text.Spannable} 665 storage for the text (this will always be true if the TextView is an EditText), 666 retrieve its text with {@link android.widget.TextView#getText}, and call {@link 667 android.text.Spannable#setSpan}, passing in a new style class from the {@link 668 android.text.style} package and the selection range. </p> 669 <p>The following code snippet demonstrates creating a string with a highlighted section, 670 italic section, and bold section, and adding it to an EditText object. </p> 671 <pre>// Get our EditText object. 672 EditText vw = (EditText)findViewById(R.id.text); 673 674 // Set the EditText's text. 675 vw.setText("Italic, highlighted, bold."); 676 677 // If this were just a TextView, we could do: 678 // vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE); 679 // to force it to use Spannable storage so styles can be attached. 680 // Or we could specify that in the XML. 681 682 // Get the EditText's internal text storage 683 Spannable str = vw.getText(); 684 685 // Create our span sections, and assign a format to each. 686 str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 687 str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 688 str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 689 </pre> 690 691 <a name="querymap" id="querymap"></a><h2>Utilizing attributes in a Map query</h2> 692 <p> 693 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: 694 </p> 695 <pre> 696 float "centerLatitude" default 0.0f 697 float "centerLongitude" default 0.0f 698 float "latitudeSpan" default 0.0f 699 float "longitudeSpan" default 0.0f 700 int "zoomLevel" default 10 701 </pre> 702 <p> 703 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. 704 </p> 705 <p> 706 If the latitudeSpan, longitudeSpan, and zoomLevel attributes are not consistent, then it is undefined which one takes precedence. 707 </p> 708 709 <a name="filelist" id="filelist"></a><h2>List of Files for an Android Application</h2> 710 <p>The following list describes the structure and files of an Android application. 711 Many of these files can be built for you (or stubbed out) by the android tool 712 shipped in the tools/ menu of the SDK. </p> 713 <table width="100%" border="0"> 714 <tr> 715 <td width="28%" valign="top">MyApp/<br /></td> 716 <td width="72%" valign="top"> </td> 717 </tr> 718 <tr> 719 <td valign="top"> AndroidManifest.xml</td> 720 <td valign="top">(<em>required</em>) Advertises the screens that this application provides, 721 where they can be launched (from the main program menu or elsewhere), 722 any content providers it implements and what kind of data they handle, 723 where the implementation classes are, and other application-wide 724 information. Syntax details for this file are described in <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">The AndroidManifest.xml File</a>.</td> 725 </tr> 726 <tr> 727 <td valign="top"> src/<br /> 728 /<em>myPackagePath</em>/.../<em>MyClass</em>.java</td> 729 <td valign="top">(<em>required</em>) This folder holds all the source code files for your 730 application, inside the appropriate package subfolders. </td> 731 </tr> 732 <tr> 733 <td valign="top"> res/</td> 734 <td valign="top">(<em>required</em>) This folder holds all the <em>resources</em> for 735 your application. Resources are external data files or description files 736 that are compiled into your code at build time. Files in different folders 737 are compiled differently, so you must put the proper resource into the 738 proper folder. (See <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources</a> for details.)</td> 739 </tr> 740 <tr> 741 <td valign="top"> anim/<br /> 742 <em>animation1</em>.xml<br /> 743 <em>...</em></td> 744 <td valign="top">(<em>optional</em>) Holds any animation XML description files that the 745 application uses. The format of these files is described in <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources</a>. </td> 746 </tr> 747 <tr> 748 <td valign="top"> drawable/<br /> 749 <em>some_picture</em>.png<br /> 750 <em>some_stretchable</em>.9.png<br /> 751 <em>some_background</em>.xml<br /> 752 ...</td> 753 <td valign="top">(<em>optional</em>) Zero or more files that will be compiled to {@link 754 android.graphics.drawable android.graphics.drawable} resources. Files 755 can be image files (png, gif, or other) or XML files describing other 756 graphics such as bitmaps, stretchable bitmaps, or gradients. Supported 757 bitmap file formats are PNG (preferred), JPG, and GIF (discouraged), 758 as well as the custom 9-patch stretchable bitmap format. These formats 759 are described in <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources</a>. </td> 760 </tr> 761 <tr> 762 <td valign="top"> layout/<br /> 763 <em>screen_1_layout</em>.xml<br /> 764 ...<br /></td> 765 <td valign="top">(<em>optional</em>) Holds all the XML files describing screens or parts 766 of screens. Although you could create a screen in Java, defining them 767 in XML files is typically easier. A layout file is similar in concept 768 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> 769 </tr> 770 <tr> 771 <td valign="top"> values/<br /> 772 arrays<br /> 773 classes.xml<br /> 774 colors.xml<br /> 775 dimens.xml<br /> 776 strings.xml<br /> 777 styles.xml<br /> 778 values.xml<br /></td> 779 <td valign="top"><p>(<em>optional</em>) XML files describing additional resources 780 such as strings, colors, and styles. The naming, quantity, and number 781 of these files are not enforced--any XML file is compiled, but these 782 are the standard names given to these files. However, the syntax 783 of these files is prescribed by Android, and described in <a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources</a>. </p> 784 </td> 785 </tr> 786 <tr> 787 <td valign="top"> xml/</td> 788 <td valign="top">(<em>optional</em>) XML files that can be read at run time on the device. </td> 789 </tr> 790 <tr> 791 <td valign="top"> raw/</td> 792 <td valign="top">(<em>optional</em>) Any files to be copied directly to the device. </td> 793 </tr> 794 </table> 795 796 797 <a name="logging" ></a> 798 <h2>Print Messages to a Log File</h2> 799 800 <p>To write log messages from your application:</p> 801 <ol><li>Import <code>android.util.Log</code>.</li> 802 <li>Use <code>Log.v()</code>, <code>Log.d()</code>, <code>Log.i()</code>, 803 <code>Log.w()</code>, or <code>Log.e()</code> to log messages. 804 (See the {@link android.util.Log} class.)<br/> E.g., 805 <code>Log.e(this.toString(), "error: " + err.toString())</code></li> 806 <li>Launch <a href="{@docRoot}guide/developing/tools/ddms.html">DDMS</a> from a terminal 807 by executing <code>ddms</code> in your Android SDK <code>/tools</code> path.</li> 808 <li>Run your application in the Android emulator.</li> 809 <li>From the DDMS application, select the emulator 810 (e.g., "emulator-5554") and click <b>Device > Run logcat...</b> 811 to view all the log data.</li> 812 </ol> 813 <p class="note"><strong>Note:</strong> If you are running Eclipse and 814 encounter a warning about the VM debug port when opening DDMS, you can ignore it 815 if you're only interested in logs. However, if you want to further inspect and 816 control your processes from DDMS, then you should close Eclipse before launching DDMS so that 817 it may use the VM debugging port.</p> 818 819 820