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