1 page.title=Services 2 @jd:body 3 4 <div id="qv-wrapper"> 5 <ol id="qv"> 6 <h2>Quickview</h2> 7 <ul> 8 <li>A service can run in the background to perform work even while the user is in a different 9 application</li> 10 <li>A service can allow other components to bind to it, in order to interact with it and 11 perform interprocess communication</li> 12 <li>A service runs in the main thread of the application that hosts it, by default</li> 13 </ul> 14 <h2>In this document</h2> 15 <ol> 16 <li><a href="#Basics">The Basics</a></li> 17 <ol> 18 <li><a href="#Declaring">Declaring a service in the manifest</a></li> 19 </ol> 20 <li><a href="#CreatingAService">Creating a Started Service</a> 21 <ol> 22 <li><a href="#ExtendingIntentService">Extending the IntentService class</a></li> 23 <li><a href="#ExtendingService">Extending the Service class</a></li> 24 <li><a href="#StartingAService">Starting a service</a></li> 25 <li><a href="#Stopping">Stopping a service</a></li> 26 </ol> 27 </li> 28 <li><a href="#CreatingBoundService">Creating a Bound Service</a></li> 29 <li><a href="#Notifications">Sending Notifications to the User</a></li> 30 <li><a href="#Foreground">Running a Service in the Foreground</a></li> 31 <li><a href="#Lifecycle">Managing the Lifecycle of a Service</a> 32 <ol> 33 <li><a href="#LifecycleCallbacks">Implementing the lifecycle callbacks</a></li> 34 </ol> 35 </li> 36 </ol> 37 38 <h2>Key classes</h2> 39 <ol> 40 <li>{@link android.app.Service}</li> 41 <li>{@link android.app.IntentService}</li> 42 </ol> 43 44 <h2>Samples</h2> 45 <ol> 46 <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/ServiceStartArguments.html">{@code 47 ServiceStartArguments}</a></li> 48 <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html">{@code 49 LocalService}</a></li> 50 </ol> 51 52 <h2>Articles</h2> 53 <ol> 54 <li><a href="{@docRoot}resources/articles/multitasking-android-way.html">Multitasking the Android Way</a></li> 55 <li><a href="{@docRoot}resources/articles/service-api-changes-starting-with.html">Service API changes starting 56 with Android 2.0</a></li> 57 </ol> 58 59 <h2>See also</h2> 60 <ol> 61 <li><a href="{@docRoot}guide/topics/fundamentals/bound-services.html">Bound Services</a></li> 62 </ol> 63 64 </div> 65 66 67 <p>A {@link android.app.Service} is an application component that can perform 68 long-running operations in the background and does not provide a user interface. Another 69 application component can start a service and it will continue to run in the background even if the 70 user switches to another application. Additionally, a component can bind to a service to 71 interact with it and even perform interprocess communication (IPC). For example, a service might 72 handle network transactions, play music, perform file I/O, or interact with a content provider, all 73 from the background.</p> 74 75 <p>A service can essentially take two forms:</p> 76 77 <dl> 78 <dt>Started</dt> 79 <dd>A service is "started" when an application component (such as an activity) starts it by 80 calling {@link android.content.Context#startService startService()}. Once started, a service 81 can run in the background indefinitely, even if the component that started it is destroyed. Usually, 82 a started service performs a single operation and does not return a result to the caller. 83 For example, it might download or upload a file over the network. When the operation is done, the 84 service should stop itself.</dd> 85 <dt>Bound</dt> 86 <dd>A service is "bound" when an application component binds to it by calling {@link 87 android.content.Context#bindService bindService()}. A bound service offers a client-server 88 interface that allows components to interact with the service, send requests, get results, and even 89 do so across processes with interprocess communication (IPC). A bound service runs only as long as 90 another application component is bound to it. Multiple components can bind to the service at once, 91 but when all of them unbind, the service is destroyed.</dd> 92 </dl> 93 94 <p>Although this documentation generally discusses these two types of services separately, your 95 service can work both ways—it can be started (to run indefinitely) and also allow binding. 96 It's simply a matter of whether you implement a couple callback methods: {@link 97 android.app.Service#onStartCommand onStartCommand()} to allow components to start it and {@link 98 android.app.Service#onBind onBind()} to allow binding.</p> 99 100 <p>Regardless of whether your application is started, bound, or both, any application component 101 can use the service (even from a separate application), in the same way that any component can use 102 an activity—by starting it with an {@link android.content.Intent}. However, you can declare 103 the service as private, in the manifest file, and block access from other applications. This is 104 discussed more in the section about <a href="#Declaring">Declaring the service in the 105 manifest</a>.</p> 106 107 <p class="caution"><strong>Caution:</strong> A service runs in the 108 main thread of its hosting process—the service does <strong>not</strong> create its own thread 109 and does <strong>not</strong> run in a separate process (unless you specify otherwise). This means 110 that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 111 playback or networking), you should create a new thread within the service to do that work. By using 112 a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the 113 application's main thread can remain dedicated to user interaction with your activities.</p> 114 115 116 <h2 id="Basics">The Basics</h2> 117 118 <div class="sidebox-wrapper"> 119 <div class="sidebox"> 120 <h3>Should you use a service or a thread?</h3> 121 <p>A service is simply a component that can run in the background even when the user is not 122 interacting with your application. Thus, you should create a service only if that is what you 123 need.</p> 124 <p>If you need to perform work outside your main thread, but only while the user is interacting 125 with your application, then you should probably instead create a new thread and not a service. For 126 example, if you want to play some music, but only while your activity is running, you might create 127 a thread in {@link android.app.Activity#onCreate onCreate()}, start running it in {@link 128 android.app.Activity#onStart onStart()}, then stop it in {@link android.app.Activity#onStop 129 onStop()}. Also consider using {@link android.os.AsyncTask} or {@link android.os.HandlerThread}, 130 instead of the traditional {@link java.lang.Thread} class. See the <a 131 href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes and 132 Threading</a> document for more information about threads.</p> 133 <p>Remember that if you do use a service, it still runs in your application's main thread by 134 default, so you should still create a new thread within the service if it performs intensive or 135 blocking operations.</p> 136 </div> 137 </div> 138 139 <p>To create a service, you must create a subclass of {@link android.app.Service} (or one 140 of its existing subclasses). In your implementation, you need to override some callback methods that 141 handle key aspects of the service lifecycle and provide a mechanism for components to bind to 142 the service, if appropriate. The most important callback methods you should override are:</p> 143 144 <dl> 145 <dt>{@link android.app.Service#onStartCommand onStartCommand()}</dt> 146 <dd>The system calls this method when another component, such as an activity, 147 requests that the service be started, by calling {@link android.content.Context#startService 148 startService()}. Once this method executes, the service is started and can run in the 149 background indefinitely. If you implement this, it is your responsibility to stop the service when 150 its work is done, by calling {@link android.app.Service#stopSelf stopSelf()} or {@link 151 android.content.Context#stopService stopService()}. (If you only want to provide binding, you don't 152 need to implement this method.)</dd> 153 <dt>{@link android.app.Service#onBind onBind()}</dt> 154 <dd>The system calls this method when another component wants to bind with the 155 service (such as to perform RPC), by calling {@link android.content.Context#bindService 156 bindService()}. In your implementation of this method, you must provide an interface that clients 157 use to communicate with the service, by returning an {@link android.os.IBinder}. You must always 158 implement this method, but if you don't want to allow binding, then you should return null.</dd> 159 <dt>{@link android.app.Service#onCreate()}</dt> 160 <dd>The system calls this method when the service is first created, to perform one-time setup 161 procedures (before it calls either {@link android.app.Service#onStartCommand onStartCommand()} or 162 {@link android.app.Service#onBind onBind()}). If the service is already running, this method is not 163 called.</dd> 164 <dt>{@link android.app.Service#onDestroy()}</dt> 165 <dd>The system calls this method when the service is no longer used and is being destroyed. 166 Your service should implement this to clean up any resources such as threads, registered 167 listeners, receivers, etc. This is the last call the service receives.</dd> 168 </dl> 169 170 <p>If a component starts the service by calling {@link 171 android.content.Context#startService startService()} (which results in a call to {@link 172 android.app.Service#onStartCommand onStartCommand()}), then the service 173 remains running until it stops itself with {@link android.app.Service#stopSelf()} or another 174 component stops it by calling {@link android.content.Context#stopService stopService()}.</p> 175 176 <p>If a component calls 177 {@link android.content.Context#bindService bindService()} to create the service (and {@link 178 android.app.Service#onStartCommand onStartCommand()} is <em>not</em> called), then the service runs 179 only as long as the component is bound to it. Once the service is unbound from all clients, the 180 system destroys it.</p> 181 182 <p>The Android system will force-stop a service only when memory is low and it must recover system 183 resources for the activity that has user focus. If the service is bound to an activity that has user 184 focus, then it's less likely to be killed, and if the service is declared to <a 185 href="#Foreground">run in the foreground</a> (discussed later), then it will almost never be killed. 186 Otherwise, if the service was started and is long-running, then the system will lower its position 187 in the list of background tasks over time and the service will become highly susceptible to 188 killing—if your service is started, then you must design it to gracefully handle restarts 189 by the system. If the system kills your service, it restarts it as soon as resources become 190 available again (though this also depends on the value you return from {@link 191 android.app.Service#onStartCommand onStartCommand()}, as discussed later). For more information 192 about when the system might destroy a service, see the <a 193 href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and Threading</a> 194 document.</p> 195 196 <p>In the following sections, you'll see how you can create each type of service and how to use 197 it from other application components.</p> 198 199 200 201 <h3 id="Declaring">Declaring a service in the manifest</h3> 202 203 <p>Like activities (and other components), you must declare all services in your application's 204 manifest file.</p> 205 206 <p>To declare your service, add a <a 207 href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a> element 208 as a child of the <a 209 href="{@docRoot}guide/topics/manifest/application-element.html">{@code <application>}</a> 210 element. For example:</p> 211 212 <pre> 213 <manifest ... > 214 ... 215 <application ... > 216 <service android:name=".ExampleService" /> 217 ... 218 </application> 219 </manifest> 220 </pre> 221 222 <p>There are other attributes you can include in the <a 223 href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a> element to 224 define properties such as permissions required to start the service and the process in 225 which the service should run. The <a 226 href="{@docRoot}guide/topics/manifest/service-element.html#nm">{@code android:name}</a> 227 attribute is the only required attribute—it specifies the class name of the service. Once 228 you publish your application, you should not change this name, because if you do, you might break 229 some functionality where explicit intents are used to reference your service (read the blog post, <a 230 href="http://android-developers.blogspot.com/2011/06/things-that-cannot-change.html">Things 231 That Cannot Change</a>). 232 233 <p>See the <a 234 href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a> element 235 reference for more information about declaring your service in the manifest.</p> 236 237 <p>Just like an activity, a service can define intent filters that allow other components to 238 invoke the service using implicit intents. By declaring intent filters, components 239 from any application installed on the user's device can potentially start your service if your 240 service declares an intent filter that matches the intent another application passes to {@link 241 android.content.Context#startService startService()}.</p> 242 243 <p>If you plan on using your service only locally (other applications do not use it), then you 244 don't need to (and should not) supply any intent filters. Without any intent filters, you must 245 start the service using an intent that explicitly names the service class. More information 246 about <a href="#StartingAService">starting a service</a> is discussed below.</p> 247 248 <p>Additionally, you can ensure that your service is private to your application only if 249 you include the <a 250 href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code android:exported}</a> 251 attribute and set it to {@code "false"}. This is effective even if your service supplies intent 252 filters.</p> 253 254 <p>For more information about creating intent filters for your service, see the <a 255 href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and Intent Filters</a> 256 document.</p> 257 258 259 260 <h2 id="CreatingStartedService">Creating a Started Service</h2> 261 262 <div class="sidebox-wrapper"> 263 <div class="sidebox"> 264 <h2>Targeting Android 1.6 or lower</h2> 265 <p>If you're building an application for Android 1.6 or lower, you need 266 to implement {@link android.app.Service#onStart onStart()}, instead of {@link 267 android.app.Service#onStartCommand onStartCommand()} (in Android 2.0, 268 {@link android.app.Service#onStart onStart()} was deprecated in favor of {@link 269 android.app.Service#onStartCommand onStartCommand()}).</p> 270 <p>For more information about providing compatibility with versions of Android older than 2.0, see 271 the {@link android.app.Service#onStartCommand onStartCommand()} documentation.</p> 272 </div> 273 </div> 274 275 <p>A started service is one that another component starts by calling {@link 276 android.content.Context#startService startService()}, resulting in a call to the service's 277 {@link android.app.Service#onStartCommand onStartCommand()} method.</p> 278 279 <p>When a service is started, it has a lifecycle that's independent of the 280 component that started it and the service can run in the background indefinitely, even if 281 the component that started it is destroyed. As such, the service should stop itself when its job 282 is done by calling {@link android.app.Service#stopSelf stopSelf()}, or another component can stop it 283 by calling {@link android.content.Context#stopService stopService()}.</p> 284 285 <p>An application component such as an activity can start the service by calling {@link 286 android.content.Context#startService startService()} and passing an {@link android.content.Intent} 287 that specifies the service and includes any data for the service to use. The service receives 288 this {@link android.content.Intent} in the {@link android.app.Service#onStartCommand 289 onStartCommand()} method.</p> 290 291 <p>For instance, suppose an activity needs to save some data to an online database. The activity can 292 start a companion service and deliver it the data to save by passing an intent to {@link 293 android.content.Context#startService startService()}. The service receives the intent in {@link 294 android.app.Service#onStartCommand onStartCommand()}, connects to the Internet and performs the 295 database transaction. When the transaction is done, the service stops itself and it is 296 destroyed.</p> 297 298 <p class="caution"><strong>Caution:</strong> A services runs in the same process as the application 299 in which it is declared and in the main thread of that application, by default. So, if your service 300 performs intensive or blocking operations while the user interacts with an activity from the same 301 application, the service will slow down activity performance. To avoid impacting application 302 performance, you should start a new thread inside the service.</p> 303 304 <p>Traditionally, there are two classes you can extend to create a started service:</p> 305 <dl> 306 <dt>{@link android.app.Service}</dt> 307 <dd>This is the base class for all services. When you extend this class, it's important that 308 you create a new thread in which to do all the service's work, because the service uses your 309 application's main thread, by default, which could slow the performance of any activity your 310 application is running.</dd> 311 <dt>{@link android.app.IntentService}</dt> 312 <dd>This is a subclass of {@link android.app.Service} that uses a worker thread to handle all 313 start requests, one at a time. This is the best option if you don't require that your service 314 handle multiple requests simultaneously. All you need to do is implement {@link 315 android.app.IntentService#onHandleIntent onHandleIntent()}, which receives the intent for each 316 start request so you can do the background work.</dd> 317 </dl> 318 319 <p>The following sections describe how you can implement your service using either one for these 320 classes.</p> 321 322 323 <h3 id="ExtendingIntentService">Extending the IntentService class</h3> 324 325 <p>Because most started services don't need to handle multiple requests simultaneously 326 (which can actually be a dangerous multi-threading scenario), it's probably best if you 327 implement your service using the {@link android.app.IntentService} class.</p> 328 329 <p>The {@link android.app.IntentService} does the following:</p> 330 331 <ul> 332 <li>Creates a default worker thread that executes all intents delivered to {@link 333 android.app.Service#onStartCommand onStartCommand()} separate from your application's main 334 thread.</li> 335 <li>Creates a work queue that passes one intent at a time to your {@link 336 android.app.IntentService#onHandleIntent onHandleIntent()} implementation, so you never have to 337 worry about multi-threading.</li> 338 <li>Stops the service after all start requests have been handled, so you never have to call 339 {@link android.app.Service#stopSelf}.</li> 340 <li>Provides default implementation of {@link android.app.IntentService#onBind onBind()} that 341 returns null.</li> 342 <li>Provides a default implementation of {@link android.app.IntentService#onStartCommand 343 onStartCommand()} that sends the intent to the work queue and then to your {@link 344 android.app.IntentService#onHandleIntent onHandleIntent()} implementation.</li> 345 </ul> 346 347 <p>All this adds up to the fact that all you need to do is implement {@link 348 android.app.IntentService#onHandleIntent onHandleIntent()} to do the work provided by the 349 client. (Though, you also need to provide a small constructor for the service.)</p> 350 351 <p>Here's an example implementation of {@link android.app.IntentService}:</p> 352 353 <pre> 354 public class HelloIntentService extends IntentService { 355 356 /** 357 * A constructor is required, and must call the super {@link android.app.IntentService#IntentService} 358 * constructor with a name for the worker thread. 359 */ 360 public HelloIntentService() { 361 super("HelloIntentService"); 362 } 363 364 /** 365 * The IntentService calls this method from the default worker thread with 366 * the intent that started the service. When this method returns, IntentService 367 * stops the service, as appropriate. 368 */ 369 @Override 370 protected void onHandleIntent(Intent intent) { 371 // Normally we would do some work here, like download a file. 372 // For our sample, we just sleep for 5 seconds. 373 long endTime = System.currentTimeMillis() + 5*1000; 374 while (System.currentTimeMillis() < endTime) { 375 synchronized (this) { 376 try { 377 wait(endTime - System.currentTimeMillis()); 378 } catch (Exception e) { 379 } 380 } 381 } 382 } 383 } 384 </pre> 385 386 <p>That's all you need: a constructor and an implementation of {@link 387 android.app.IntentService#onHandleIntent onHandleIntent()}.</p> 388 389 <p>If you decide to also override other callback methods, such as {@link 390 android.app.IntentService#onCreate onCreate()}, {@link 391 android.app.IntentService#onStartCommand onStartCommand()}, or {@link 392 android.app.IntentService#onDestroy onDestroy()}, be sure to call the super implementation, so 393 that the {@link android.app.IntentService} can properly handle the life of the worker thread.</p> 394 395 <p>For example, {@link android.app.IntentService#onStartCommand onStartCommand()} must return 396 the default implementation (which is how the intent gets delivered to {@link 397 android.app.IntentService#onHandleIntent onHandleIntent()}):</p> 398 399 <pre> 400 @Override 401 public int onStartCommand(Intent intent, int flags, int startId) { 402 Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); 403 return super.onStartCommand(intent,flags,startId); 404 } 405 </pre> 406 407 <p>Besides {@link android.app.IntentService#onHandleIntent onHandleIntent()}, the only method 408 from which you don't need to call the super class is {@link android.app.IntentService#onBind 409 onBind()} (but you only need to implement that if your service allows binding).</p> 410 411 <p>In the next section, you'll see how the same kind of service is implemented when extending 412 the base {@link android.app.Service} class, which is a lot more code, but which might be 413 appropriate if you need to handle simultaneous start requests.</p> 414 415 416 <h3 id="ExtendingService">Extending the Service class</h3> 417 418 <p>As you saw in the previous section, using {@link android.app.IntentService} makes your 419 implementation of a started service very simple. If, however, you require your service to 420 perform multi-threading (instead of processing start requests through a work queue), then you 421 can extend the {@link android.app.Service} class to handle each intent.</p> 422 423 <p>For comparison, the following example code is an implementation of the {@link 424 android.app.Service} class that performs the exact same work as the example above using {@link 425 android.app.IntentService}. That is, for each start request, it uses a worker thread to perform the 426 job and processes only one request at a time.</p> 427 428 <pre> 429 public class HelloService extends Service { 430 private Looper mServiceLooper; 431 private ServiceHandler mServiceHandler; 432 433 // Handler that receives messages from the thread 434 private final class ServiceHandler extends Handler { 435 public ServiceHandler(Looper looper) { 436 super(looper); 437 } 438 @Override 439 public void handleMessage(Message msg) { 440 // Normally we would do some work here, like download a file. 441 // For our sample, we just sleep for 5 seconds. 442 long endTime = System.currentTimeMillis() + 5*1000; 443 while (System.currentTimeMillis() < endTime) { 444 synchronized (this) { 445 try { 446 wait(endTime - System.currentTimeMillis()); 447 } catch (Exception e) { 448 } 449 } 450 } 451 // Stop the service using the startId, so that we don't stop 452 // the service in the middle of handling another job 453 stopSelf(msg.arg1); 454 } 455 } 456 457 @Override 458 public void onCreate() { 459 // Start up the thread running the service. Note that we create a 460 // separate thread because the service normally runs in the process's 461 // main thread, which we don't want to block. We also make it 462 // background priority so CPU-intensive work will not disrupt our UI. 463 HandlerThread thread = new HandlerThread("ServiceStartArguments", 464 Process.THREAD_PRIORITY_BACKGROUND); 465 thread.start(); 466 467 // Get the HandlerThread's Looper and use it for our Handler 468 mServiceLooper = thread.getLooper(); 469 mServiceHandler = new ServiceHandler(mServiceLooper); 470 } 471 472 @Override 473 public int onStartCommand(Intent intent, int flags, int startId) { 474 Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); 475 476 // For each start request, send a message to start a job and deliver the 477 // start ID so we know which request we're stopping when we finish the job 478 Message msg = mServiceHandler.obtainMessage(); 479 msg.arg1 = startId; 480 mServiceHandler.sendMessage(msg); 481 482 // If we get killed, after returning from here, restart 483 return START_STICKY; 484 } 485 486 @Override 487 public IBinder onBind(Intent intent) { 488 // We don't provide binding, so return null 489 return null; 490 } 491 492 @Override 493 public void onDestroy() { 494 Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show(); 495 } 496 } 497 </pre> 498 499 <p>As you can see, it's a lot more work than using {@link android.app.IntentService}.</p> 500 501 <p>However, because you handle each call to {@link android.app.Service#onStartCommand 502 onStartCommand()} yourself, you can perform multiple requests simultaneously. That's not what 503 this example does, but if that's what you want, then you can create a new thread for each 504 request and run them right away (instead of waiting for the previous request to finish).</p> 505 506 <p>Notice that the {@link android.app.Service#onStartCommand onStartCommand()} method must return an 507 integer. The integer is a value that describes how the system should continue the service in the 508 event that the system kills it (as discussed above, the default implementation for {@link 509 android.app.IntentService} handles this for you, though you are able to modify it). The return value 510 from {@link android.app.Service#onStartCommand onStartCommand()} must be one of the following 511 constants:</p> 512 513 <dl> 514 <dt>{@link android.app.Service#START_NOT_STICKY}</dt> 515 <dd>If the system kills the service after {@link android.app.Service#onStartCommand 516 onStartCommand()} returns, <em>do not</em> recreate the service, unless there are pending 517 intents to deliver. This is the safest option to avoid running your service when not necessary 518 and when your application can simply restart any unfinished jobs.</dd> 519 <dt>{@link android.app.Service#START_STICKY}</dt> 520 <dd>If the system kills the service after {@link android.app.Service#onStartCommand 521 onStartCommand()} returns, recreate the service and call {@link 522 android.app.Service#onStartCommand onStartCommand()}, but <em>do not</em> redeliver the last intent. 523 Instead, the system calls {@link android.app.Service#onStartCommand onStartCommand()} with a 524 null intent, unless there were pending intents to start the service, in which case, 525 those intents are delivered. This is suitable for media players (or similar services) that are not 526 executing commands, but running indefinitely and waiting for a job.</dd> 527 <dt>{@link android.app.Service#START_REDELIVER_INTENT}</dt> 528 <dd>If the system kills the service after {@link android.app.Service#onStartCommand 529 onStartCommand()} returns, recreate the service and call {@link 530 android.app.Service#onStartCommand onStartCommand()} with the last intent that was delivered to the 531 service. Any pending intents are delivered in turn. This is suitable for services that are 532 actively performing a job that should be immediately resumed, such as downloading a file.</dd> 533 </dl> 534 <p>For more details about these return values, see the linked reference documentation for each 535 constant.</p> 536 537 538 539 <h3 id="StartingAService">Starting a Service</h3> 540 541 <p>You can start a service from an activity or other application component by passing an 542 {@link android.content.Intent} (specifying the service to start) to {@link 543 android.content.Context#startService startService()}. The Android system calls the service's {@link 544 android.app.Service#onStartCommand onStartCommand()} method and passes it the {@link 545 android.content.Intent}. (You should never call {@link android.app.Service#onStartCommand 546 onStartCommand()} directly.)</p> 547 548 <p>For example, an activity can start the example service in the previous section ({@code 549 HelloSevice}) using an explicit intent with {@link android.content.Context#startService 550 startService()}:</p> 551 552 <pre> 553 Intent intent = new Intent(this, HelloService.class); 554 startService(intent); 555 </pre> 556 557 <p>The {@link android.content.Context#startService startService()} method returns immediately and 558 the Android system calls the service's {@link android.app.Service#onStartCommand 559 onStartCommand()} method. If the service is not already running, the system first calls {@link 560 android.app.Service#onCreate onCreate()}, then calls {@link android.app.Service#onStartCommand 561 onStartCommand()}.</p> 562 563 <p>If the service does not also provide binding, the intent delivered with {@link 564 android.content.Context#startService startService()} is the only mode of communication between the 565 application component and the service. However, if you want the service to send a result back, then 566 the client that starts the service can create a {@link android.app.PendingIntent} for a broadcast 567 (with {@link android.app.PendingIntent#getBroadcast getBroadcast()}) and deliver it to the service 568 in the {@link android.content.Intent} that starts the service. The service can then use the 569 broadcast to deliver a result.</p> 570 571 <p>Multiple requests to start the service result in multiple corresponding calls to the service's 572 {@link android.app.Service#onStartCommand onStartCommand()}. However, only one request to stop 573 the service (with {@link android.app.Service#stopSelf stopSelf()} or {@link 574 android.content.Context#stopService stopService()}) is required to stop it.</p> 575 576 577 <h3 id="Stopping">Stopping a service</h3> 578 579 <p>A started service must manage its own lifecycle. That is, the system does not stop or 580 destroy the service unless it must recover system memory and the service 581 continues to run after {@link android.app.Service#onStartCommand onStartCommand()} returns. So, 582 the service must stop itself by calling {@link android.app.Service#stopSelf stopSelf()} or another 583 component can stop it by calling {@link android.content.Context#stopService stopService()}.</p> 584 585 <p>Once requested to stop with {@link android.app.Service#stopSelf stopSelf()} or {@link 586 android.content.Context#stopService stopService()}, the system destroys the service as soon as 587 possible.</p> 588 589 <p>However, if your service handles multiple requests to {@link 590 android.app.Service#onStartCommand onStartCommand()} concurrently, then you shouldn't stop the 591 service when you're done processing a start request, because you might have since received a new 592 start request (stopping at the end of the first request would terminate the second one). To avoid 593 this problem, you can use {@link android.app.Service#stopSelf(int)} to ensure that your request to 594 stop the service is always based on the most recent start request. That is, when you call {@link 595 android.app.Service#stopSelf(int)}, you pass the ID of the start request (the <code>startId</code> 596 delivered to {@link android.app.Service#onStartCommand onStartCommand()}) to which your stop request 597 corresponds. Then if the service received a new start request before you were able to call {@link 598 android.app.Service#stopSelf(int)}, then the ID will not match and the service will not stop.</p> 599 600 <p class="caution"><strong>Caution:</strong> It's important that your application stops its services 601 when it's done working, to avoid wasting system resources and consuming battery power. If necessary, 602 other components can stop the service by calling {@link 603 android.content.Context#stopService stopService()}. Even if you enable binding for the service, 604 you must always stop the service yourself if it ever received a call to {@link 605 android.app.Service#onStartCommand onStartCommand()}.</p> 606 607 <p>For more information about the lifecycle of a service, see the section below about <a 608 href="#Lifecycle">Managing the Lifecycle of a Service</a>.</p> 609 610 611 612 <h2 id="CreatingBoundService">Creating a Bound Service</h2> 613 614 <p>A bound service is one that allows application components to bind to it by calling {@link 615 android.content.Context#bindService bindService()} in order to create a long-standing connection 616 (and generally does not allow components to <em>start</em> it by calling {@link 617 android.content.Context#startService startService()}).</p> 618 619 <p>You should create a bound service when you want to interact with the service from activities 620 and other components in your application or to expose some of your application's functionality to 621 other applications, through interprocess communication (IPC).</p> 622 623 <p>To create a bound service, you must implement the {@link 624 android.app.Service#onBind onBind()} callback method to return an {@link android.os.IBinder} that 625 defines the interface for communication with the service. Other application components can then call 626 {@link android.content.Context#bindService bindService()} to retrieve the interface and 627 begin calling methods on the service. The service lives only to serve the application component that 628 is bound to it, so when there are no components bound to the service, the system destroys it 629 (you do <em>not</em> need to stop a bound service in the way you must when the service is started 630 through {@link android.app.Service#onStartCommand onStartCommand()}).</p> 631 632 <p>To create a bound service, the first thing you must do is define the interface that specifies 633 how a client can communicate with the service. This interface between the service 634 and a client must be an implementation of {@link android.os.IBinder} and is what your service must 635 return from the {@link android.app.Service#onBind 636 onBind()} callback method. Once the client receives the {@link android.os.IBinder}, it can begin 637 interacting with the service through that interface.</p> 638 639 <p>Multiple clients can bind to the service at once. When a client is done interacting with the 640 service, it calls {@link android.content.Context#unbindService unbindService()} to unbind. Once 641 there are no clients bound to the service, the system destroys the service.</p> 642 643 <p>There are multiple ways to implement a bound service and the implementation is more 644 complicated than a started service, so the bound service discussion appears in a separate 645 document about <a 646 href="{@docRoot}guide/topics/fundamentals/bound-services.html">Bound Services</a>.</p> 647 648 649 650 <h2 id="Notifications">Sending Notifications to the User</h2> 651 652 <p>Once running, a service can notify the user of events using <a 653 href="{@docRoot}guide/topics/ui/notifiers/toasts.html">Toast Notifications</a> or <a 654 href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>.</p> 655 656 <p>A toast notification is a message that appears on the surface of the current window for a 657 moment then disappears, while a status bar notification provides an icon in the status bar with a 658 message, which the user can select in order to take an action (such as start an activity).</p> 659 660 <p>Usually, a status bar notification is the best technique when some background work has completed 661 (such as a file completed 662 downloading) and the user can now act on it. When the user selects the notification from the 663 expanded view, the notification can start an activity (such as to view the downloaded file).</p> 664 665 <p>See the <a 666 href="{@docRoot}guide/topics/ui/notifiers/toasts.html">Toast Notifications</a> or <a 667 href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a> 668 developer guides for more information.</p> 669 670 671 672 <h2 id="Foreground">Running a Service in the Foreground</h2> 673 674 <p>A foreground service is a service that's considered to be something the 675 user is actively aware of and thus not a candidate for the system to kill when low on memory. A 676 foreground service must provide a notification for the status bar, which is placed under the 677 "Ongoing" heading, which means that the notification cannot be dismissed unless the service is 678 either stopped or removed from the foreground.</p> 679 680 <p>For example, a music player that plays music from a service should be set to run in the 681 foreground, because the user is explicitly aware 682 of its operation. The notification in the status bar might indicate the current song and allow 683 the user to launch an activity to interact with the music player.</p> 684 685 <p>To request that your service run in the foreground, call {@link 686 android.app.Service#startForeground startForeground()}. This method takes two parameters: an integer 687 that uniquely identifies the notification and the {@link 688 android.app.Notification} for the status bar. For example:</p> 689 690 <pre> 691 Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text), 692 System.currentTimeMillis()); 693 Intent notificationIntent = new Intent(this, ExampleActivity.class); 694 PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 695 notification.setLatestEventInfo(this, getText(R.string.notification_title), 696 getText(R.string.notification_message), pendingIntent); 697 startForeground(ONGOING_NOTIFICATION, notification); 698 </pre> 699 700 701 <p>To remove the service from the foreground, call {@link 702 android.app.Service#stopForeground stopForeground()}. This method takes a boolean, indicating 703 whether to remove the status bar notification as well. This method does <em>not</em> stop the 704 service. However, if you stop the service while it's still running in the foreground, then the 705 notification is also removed.</p> 706 707 <p class="note"><strong>Note:</strong> The methods {@link 708 android.app.Service#startForeground startForeground()} and {@link 709 android.app.Service#stopForeground stopForeground()} were introduced in Android 2.0 (API Level 710 5). In order to run your service in the foreground on older versions of the platform, you must 711 use the previous {@code setForeground()} method—see the {@link 712 android.app.Service#startForeground startForeground()} documentation for information about how 713 to provide backward compatibility.</p> 714 715 <p>For more information about notifications, see <a 716 href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Creating Status Bar 717 Notifications</a>.</p> 718 719 720 721 <h2 id="Lifecycle">Managing the Lifecycle of a Service</h2> 722 723 <p>The lifecycle of a service is much simpler than that of an activity. However, it's even more important 724 that you pay close attention to how your service is created and destroyed, because a service 725 can run in the background without the user being aware.</p> 726 727 <p>The service lifecycle—from when it's created to when it's destroyed—can follow two 728 different paths:</p> 729 730 <ul> 731 <li>A started service 732 <p>The service is created when another component calls {@link 733 android.content.Context#startService startService()}. The service then runs indefinitely and must 734 stop itself by calling {@link 735 android.app.Service#stopSelf() stopSelf()}. Another component can also stop the 736 service by calling {@link android.content.Context#stopService 737 stopService()}. When the service is stopped, the system destroys it..</p></li> 738 739 <li>A bound service 740 <p>The service is created when another component (a client) calls {@link 741 android.content.Context#bindService bindService()}. The client then communicates with the service 742 through an {@link android.os.IBinder} interface. The client can close the connection by calling 743 {@link android.content.Context#unbindService unbindService()}. Multiple clients can bind to 744 the same service and when all of them unbind, the system destroys the service. (The service 745 does <em>not</em> need to stop itself.)</p></li> 746 </ul> 747 748 <p>These two paths are not entirely separate. That is, you can bind to a service that was already 749 started with {@link android.content.Context#startService startService()}. For example, a background 750 music service could be started by calling {@link android.content.Context#startService 751 startService()} with an {@link android.content.Intent} that identifies the music to play. Later, 752 possibly when the user wants to exercise some control over the player or get information about the 753 current song, an activity can bind to the service by calling {@link 754 android.content.Context#bindService bindService()}. In cases like this, {@link 755 android.content.Context#stopService stopService()} or {@link android.app.Service#stopSelf 756 stopSelf()} does not actually stop the service until all clients unbind. </p> 757 758 759 <h3 id="LifecycleCallbacks">Implementing the lifecycle callbacks</h3> 760 761 <p>Like an activity, a service has lifecycle callback methods that you can implement to monitor 762 changes in the service's state and perform work at the appropriate times. The following skeleton 763 service demonstrates each of the lifecycle methods:</p> 764 765 766 <div class="figure" style="width:432px"> 767 <img src="{@docRoot}images/service_lifecycle.png" alt="" /> 768 <p class="img-caption"><strong>Figure 2.</strong> The service lifecycle. The diagram on the left 769 shows the lifecycle when the service is created with {@link android.content.Context#startService 770 startService()} and the diagram on the right shows the lifecycle when the service is created 771 with {@link android.content.Context#bindService bindService()}.</p> 772 </div> 773 774 <pre> 775 public class ExampleService extends Service { 776 int mStartMode; // indicates how to behave if the service is killed 777 IBinder mBinder; // interface for clients that bind 778 boolean mAllowRebind; // indicates whether onRebind should be used 779 780 @Override 781 public void {@link android.app.Service#onCreate onCreate}() { 782 // The service is being created 783 } 784 @Override 785 public int {@link android.app.Service#onStartCommand onStartCommand}(Intent intent, int flags, int startId) { 786 // The service is starting, due to a call to {@link android.content.Context#startService startService()} 787 return <em>mStartMode</em>; 788 } 789 @Override 790 public IBinder {@link android.app.Service#onBind onBind}(Intent intent) { 791 // A client is binding to the service with {@link android.content.Context#bindService bindService()} 792 return <em>mBinder</em>; 793 } 794 @Override 795 public boolean {@link android.app.Service#onUnbind onUnbind}(Intent intent) { 796 // All clients have unbound with {@link android.content.Context#unbindService unbindService()} 797 return <em>mAllowRebind</em>; 798 } 799 @Override 800 public void {@link android.app.Service#onRebind onRebind}(Intent intent) { 801 // A client is binding to the service with {@link android.content.Context#bindService bindService()}, 802 // after onUnbind() has already been called 803 } 804 @Override 805 public void {@link android.app.Service#onDestroy onDestroy}() { 806 // The service is no longer used and is being destroyed 807 } 808 } 809 </pre> 810 811 <p class="note"><strong>Note:</strong> Unlike the activity lifecycle callback methods, you are 812 <em>not</em> required to call the superclass implementation of these callback methods.</p> 813 814 <p>By implementing these methods, you can monitor two nested loops of the service's lifecycle: </p> 815 816 <ul> 817 <li>The <strong>entire lifetime</strong> of a service happens between the time {@link 818 android.app.Service#onCreate onCreate()} is called and the time {@link 819 android.app.Service#onDestroy} returns. Like an activity, a service does its initial setup in 820 {@link android.app.Service#onCreate onCreate()} and releases all remaining resources in {@link 821 android.app.Service#onDestroy onDestroy()}. For example, a 822 music playback service could create the thread where the music will be played in {@link 823 android.app.Service#onCreate onCreate()}, then stop the thread in {@link 824 android.app.Service#onDestroy onDestroy()}. 825 826 <p>The {@link android.app.Service#onCreate onCreate()} and {@link android.app.Service#onDestroy 827 onDestroy()} methods are called for all services, whether 828 they're created by {@link android.content.Context#startService startService()} or {@link 829 android.content.Context#bindService bindService()}.</p></li> 830 831 <li>The <strong>active lifetime</strong> of a service begins with a call to either {@link 832 android.app.Service#onStartCommand onStartCommand()} or {@link android.app.Service#onBind onBind()}. 833 Each method is handed the {@link 834 android.content.Intent} that was passed to either {@link android.content.Context#startService 835 startService()} or {@link android.content.Context#bindService bindService()}, respectively. 836 <p>If the service is started, the active lifetime ends the same time that the entire lifetime 837 ends (the service is still active even after {@link android.app.Service#onStartCommand 838 onStartCommand()} returns). If the service is bound, the active lifetime ends when {@link 839 android.app.Service#onUnbind onUnbind()} returns.</p> 840 </li> 841 </ul> 842 843 <p class="note"><strong>Note:</strong> Although a started service is stopped by a call to 844 either {@link android.app.Service#stopSelf stopSelf()} or {@link 845 android.content.Context#stopService stopService()}, there is not a respective callback for the 846 service (there's no {@code onStop()} callback). So, unless the service is bound to a client, 847 the system destroys it when the service is stopped—{@link 848 android.app.Service#onDestroy onDestroy()} is the only callback received.</p> 849 850 <p>Figure 2 illustrates the typical callback methods for a service. Although the figure separates 851 services that are created by {@link android.content.Context#startService startService()} from those 852 created by {@link android.content.Context#bindService bindService()}, keep 853 in mind that any service, no matter how it's started, can potentially allow clients to bind to it. 854 So, a service that was initially started with {@link android.app.Service#onStartCommand 855 onStartCommand()} (by a client calling {@link android.content.Context#startService startService()}) 856 can still receive a call to {@link android.app.Service#onBind onBind()} (when a client calls 857 {@link android.content.Context#bindService bindService()}).</p> 858 859 <p>For more information about creating a service that provides binding, see the <a 860 href="{@docRoot}guide/topics/fundamentals/bound-services.html">Bound Services</a> document, 861 which includes more information about the {@link android.app.Service#onRebind onRebind()} 862 callback method in the section about <a 863 href="{@docRoot}guide/topics/fundamentals/bound-services.html#Lifecycle">Managing the Lifecycle of 864 a Bound Service</a>.</p> 865 866 867 <!-- 868 <h2>Beginner's Path</h2> 869 870 <p>To learn how to query data from the system or other applications (such as contacts or media 871 stored on the device), continue with the <b><a 872 href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a></b> 873 document.</p> 874 --> 875