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