Home | History | Annotate | Download | only in components

Lines Matching full:service

8   <li>A service can run in the background to perform work even while the user is in a different
10 <li>A service can allow other components to bind to it, in order to interact with it and
12 <li>A service runs in the main thread of the application that hosts it, by default</li>
18 <li><a href="#Declaring">Declaring a service in the manifest</a></li>
20 <li><a href="#CreatingAService">Creating a Started Service</a>
23 <li><a href="#ExtendingService">Extending the Service class</a></li>
24 <li><a href="#StartingAService">Starting a service</a></li>
25 <li><a href="#Stopping">Stopping a service</a></li>
28 <li><a href="#CreatingBoundService">Creating a Bound Service</a></li>
30 <li><a href="#Foreground">Running a Service in the Foreground</a></li>
31 <li><a href="#Lifecycle">Managing the Lifecycle of a Service</a>
40 <li>{@link android.app.Service}</li>
60 <p>A {@link android.app.Service} is an application component that can perform
62 application component can start a service and it will continue to run in the background even if the
63 user switches to another application. Additionally, a component can bind to a service to
64 interact with it and even perform interprocess communication (IPC). For example, a service might
68 <p>A service can essentially take two forms:</p>
72 <dd>A service is "started" when an application component (such as an activity) starts it by
73 calling {@link android.content.Context#startService startService()}. Once started, a service
75 a started service performs a single operation and does not return a result to the caller.
77 service should stop itself.</dd>
79 <dd>A service is "bound" when an application component binds to it by calling {@link
80 android.content.Context#bindService bindService()}. A bound service offers a client-server
81 interface that allows components to interact with the service, send requests, get results, and even
82 do so across processes with interprocess communication (IPC). A bound service runs only as long as
83 another application component is bound to it. Multiple components can bind to the service at once,
84 but when all of them unbind, the service is destroyed.</dd>
88 service can work both ways&mdash;it can be started (to run indefinitely) and also allow binding.
90 android.app.Service#onStartCommand onStartCommand()} to allow components to start it and {@link
91 android.app.Service#onBind onBind()} to allow binding.</p>
94 can use the service (even from a separate application), in the same way that any component can use
96 the service as private, in the manifest file, and block access from other applications. This is
97 discussed more in the section about <a href="#Declaring">Declaring the service in the
100 <p class="caution"><strong>Caution:</strong> A service runs in the
101 main thread of its hosting process&mdash;the service does <strong>not</strong> create its own thread
103 that, if your service is going to do any CPU intensive work or blocking operations (such as MP3
104 playback or networking), you should create a new thread within the service to do that work. By using
113 <h3>Should you use a service or a thread?</h3>
114 <p>A service is simply a component that can run in the background even when the user is not
115 interacting with your application. Thus, you should create a service only if that is what you
118 with your application, then you should probably instead create a new thread and not a service. For
126 <p>Remember that if you do use a service, it still runs in your application's main thread by
127 default, so you should still create a new thread within the service if it performs intensive or
132 <p>To create a service, you must create a subclass of {@link android.app.Service} (or one
134 handle key aspects of the service lifecycle and provide a mechanism for components to bind to
135 the service, if appropriate. The most important callback methods you should override are:</p>
138 <dt>{@link android.app.Service#onStartCommand onStartCommand()}</dt>
140 requests that the service be started, by calling {@link android.content.Context#startService
141 startService()}. Once this method executes, the service is started and can run in the
142 background indefinitely. If you implement this, it is your responsibility to stop the service when
143 its work is done, by calling {@link android.app.Service#stopSelf stopSelf()} or {@link
146 <dt>{@link android.app.Service#onBind onBind()}</dt>
148 service (such as to perform RPC), by calling {@link android.content.Context#bindService
150 use to communicate with the service, by returning an {@link android.os.IBinder}. You must always
152 <dt>{@link android.app.Service#onCreate()}</dt>
153 <dd>The system calls this method when the service is first created, to perform one-time setup
154 procedures (before it calls either {@link android.app.Service#onStartCommand onStartCommand()} or
155 {@link android.app.Service#onBind onBind()}). If the service is already running, this method is not
157 <dt>{@link android.app.Service#onDestroy()}</dt>
158 <dd>The system calls this method when the service is no longer used and is being destroyed.
159 Your service should implement this to clean up any resources such as threads, registered
160 listeners, receivers, etc. This is the last call the service receives.</dd>
163 <p>If a component starts the service by calling {@link
165 android.app.Service#onStartCommand onStartCommand()}), then the service
166 remains running until it stops itself with {@link android.app.Service#stopSelf()} or another
170 {@link android.content.Context#bindService bindService()} to create the service (and {@link
171 android.app.Service#onStartCommand onStartCommand()} is <em>not</em> called), then the service runs
172 only as long as the component is bound to it. Once the service is unbound from all clients, the
175 <p>The Android system will force-stop a service only when memory is low and it must recover system
176 resources for the activity that has user focus. If the service is bound to an activity that has user
177 focus, then it's less likely to be killed, and if the service is declared to <a
179 Otherwise, if the service was started and is long-running, then the system will lower its position
180 in the list of background tasks over time and the service will become highly susceptible to
181 killing&mdash;if your service is started, then you must design it to gracefully handle restarts
182 by the system. If the system kills your service, it restarts it as soon as resources become
184 android.app.Service#onStartCommand onStartCommand()}, as discussed later). For more information
185 about when the system might destroy a service, see the <a
189 <p>In the following sections, you'll see how you can create each type of service and how to use
194 <h3 id="Declaring">Declaring a service in the manifest</h3>
199 <p>To declare your service, add a <a
200 href="{@docRoot}guide/topics/manifest/service-element.html">{@code &lt;service&gt;}</a> element
209 &lt;service android:name=".ExampleService" /&gt;
216 href="{@docRoot}guide/topics/manifest/service-element.html">{@code &lt;service&gt;}</a> element to
217 define properties such as permissions required to start the service and the process in
218 which the service should run. The <a
219 href="{@docRoot}guide/topics/manifest/service-element.html#nm">{@code android:name}</a>
220 attribute is the only required attribute&mdash;it specifies the class name of the service. Once
222 some functionality where explicit intents are used to reference your service (read the blog post, <a
227 href="{@docRoot}guide/topics/manifest/service-element.html">{@code &lt;service&gt;}</a> element
228 reference for more information about declaring your service in the manifest.</p>
230 <p>Just like an activity, a service can define intent filters that allow other components to
231 invoke the service using implicit intents. By declaring intent filters, components
232 from any application installed on the user's device can potentially start your service if your
233 service declares an intent filter that matches the intent another application passes to {@link
236 <p>If you plan on using your service only locally (other applications do not use it), then you
238 start the service using an intent that explicitly names the service class. More information
239 about <a href="#StartingAService">starting a service</a> is discussed below.</p>
241 <p>Additionally, you can ensure that your service is private to your application only if
243 href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code android:exported}</a>
244 attribute and set it to {@code "false"}. This is effective even if your service supplies intent
247 <p>For more information about creating intent filters for your service, see the <a
253 <h2 id="CreatingStartedService">Creating a Started Service</h2>
259 to implement {@link android.app.Service#onStart onStart()}, instead of {@link
260 android.app.Service#onStartCommand onStartCommand()} (in Android 2.0,
261 {@link android.app.Service#onStart onStart()} was deprecated in favor of {@link
262 android.app.Service#onStartCommand onStartCommand()}).</p>
264 the {@link android.app.Service#onStartCommand onStartCommand()} documentation.</p>
268 <p>A started service is one that another component starts by calling {@link
269 android.content.Context#startService startService()}, resulting in a call to the service's
270 {@link android.app.Service#onStartCommand onStartCommand()} method.</p>
272 <p>When a service is started, it has a lifecycle that's independent of the
273 component that started it and the service can run in the background indefinitely, even if
274 the component that started it is destroyed. As such, the service should stop itself when its job
275 is done by calling {@link android.app.Service#stopSelf stopSelf()}, or another component can stop it
278 <p>An application component such as an activity can start the service by calling {@link
280 that specifies the service and includes any data for the service to use. The service receives
281 this {@link android.content.Intent} in the {@link android.app.Service#onStartCommand
285 start a companion service and deliver it the data to save by passing an intent to {@link
286 android.content.Context#startService startService()}. The service receives the intent in {@link
287 android.app.Service#onStartCommand onStartCommand()}, connects to the Internet and performs the
288 database transaction. When the transaction is done, the service stops itself and it is
292 in which it is declared and in the main thread of that application, by default. So, if your service
294 application, the service will slow down activity performance. To avoid impacting application
295 service.</p>
297 <p>Traditionally, there are two classes you can extend to create a started service:</p>
299 <dt>{@link android.app.Service}</dt>
301 you create a new thread in which to do all the service's work, because the service uses your
305 <dd>This is a subclass of {@link android.app.Service} that uses a worker thread to handle all
306 start requests, one at a time. This is the best option if you don't require that your service
312 <p>The following sections describe how you can implement your service using either one for these
320 implement your service using the {@link android.app.IntentService} class.</p>
326 android.app.Service#onStartCommand onStartCommand()} separate from your application's main
331 <li>Stops the service after all start requests have been handled, so you never have to call
332 {@link android.app.Service#stopSelf}.</li>
342 client. (Though, you also need to provide a small constructor for the service.)</p>
359 * the intent that started the service. When this method returns, IntentService
360 * stops the service, as appropriate.
395 Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
402 onBind()} (but you only need to implement that if your service allows binding).</p>
404 <p>In the next section, you'll see how the same kind of service is implemented when extending
405 the base {@link android.app.Service} class, which is a lot more code, but which might be
409 <h3 id="ExtendingService">Extending the Service class</h3>
412 implementation of a started service very simple. If, however, you require your service to
414 can extend the {@link android.app.Service} class to handle each intent.</p>
417 android.app.Service} class that performs the exact same work as the example above using {@link
422 public class HelloService extends Service {
444 // Stop the service using the startId, so that we don't stop
445 // the service in the middle of handling another job
452 // Start up the thread running the service. Note that we create a
453 // separate thread because the service normally runs in the process's
467 Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
487 Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
494 <p>However, because you handle each call to {@link android.app.Service#onStartCommand
499 <p>Notice that the {@link android.app.Service#onStartCommand onStartCommand()} method must return an
500 integer. The integer is a value that describes how the system should continue the service in the
503 from {@link android.app.Service#onStartCommand onStartCommand()} must be one of the following
507 <dt>{@link android.app.Service#START_NOT_STICKY}</dt>
508 <dd>If the system kills the service after {@link android.app.Service#onStartCommand
509 onStartCommand()} returns, <em>do not</em> recreate the service, unless there are pending
510 intents to deliver. This is the safest option to avoid running your service when not necessary
512 <dt>{@link android.app.Service#START_STICKY}</dt>
513 <dd>If the system kills the service after {@link android.app.Service#onStartCommand
514 onStartCommand()} returns, recreate the service and call {@link
515 android.app.Service#onStartCommand onStartCommand()}, but <em>do not</em> redeliver the last intent.
516 Instead, the system calls {@link android.app.Service#onStartCommand onStartCommand()} with a
517 null intent, unless there were pending intents to start the service, in which case,
520 <dt>{@link android.app.Service#START_REDELIVER_INTENT}</dt>
521 <dd>If the system kills the service after {@link android.app.Service#onStartCommand
522 onStartCommand()} returns, recreate the service and call {@link
523 android.app.Service#onStartCommand onStartCommand()} with the last intent that was delivered to the
524 service. Any pending intents are delivered in turn. This is suitable for services that are
532 <h3 id="StartingAService">Starting a Service</h3>
534 <p>You can start a service from an activity or other application component by passing an
535 {@link android.content.Intent} (specifying the service to start) to {@link
536 android.content.Context#startService startService()}. The Android system calls the service's {@link
537 android.app.Service#onStartCommand onStartCommand()} method and passes it the {@link
538 android.content.Intent}. (You should never call {@link android.app.Service#onStartCommand
541 <p>For example, an activity can start the example service in the previous section ({@code
551 the Android system calls the service's {@link android.app.Service#onStartCommand
552 onStartCommand()} method. If the service is not already running, the system first calls {@link
553 android.app.Service#onCreate onCreate()}, then calls {@link android.app.Service#onStartCommand
556 <p>If the service does not also provide binding, the intent delivered with {@link
558 application component and the service. However, if you want the service to send a result back, then
559 the client that starts the service can create a {@link android.app.PendingIntent} for a broadcast
560 (with {@link android.app.PendingIntent#getBroadcast getBroadcast()}) and deliver it to the service
561 in the {@link android.content.Intent} that starts the service. The service can then use the
564 <p>Multiple requests to start the service result in multiple corresponding calls to the service's
565 {@link android.app.Service#onStartCommand onStartCommand()}. However, only one request to stop
566 the service (with {@link android.app.Service#stopSelf stopSelf()} or {@link
570 <h3 id="Stopping">Stopping a service</h3>
572 <p>A started service must manage its own lifecycle. That is, the system does not stop or
573 destroy the service unless it must recover system memory and the service
574 continues to run after {@link android.app.Service#onStartCommand onStartCommand()} returns. So,
575 the service must stop itself by calling {@link android.app.Service#stopSelf stopSelf()} or another
578 <p>Once requested to stop with {@link android.app.Service#stopSelf stopSelf()} or {@link
579 android.content.Context#stopService stopService()}, the system destroys the service as soon as
582 <p>However, if your service handles multiple requests to {@link
583 android.app.Service#onStartCommand onStartCommand()} concurrently, then you shouldn't stop the
584 service when you're done processing a start request, because you might have since received a new
586 this problem, you can use {@link android.app.Service#stopSelf(int)} to ensure that your request to
587 stop the service is always based on the most recent start request. That is, when you call {@link
588 android.app.Service#stopSelf(int)}, you pass the ID of the start request (the <code>startId</code>
589 delivered to {@link android.app.Service#onStartCommand onStartCommand()}) to which your stop request
590 corresponds. Then if the service received a new start request before you were able to call {@link
591 android.app.Service#stopSelf(int)}, then the ID will not match and the service will not stop.</p>
595 other components can stop the service by calling {@link
596 android.content.Context#stopService stopService()}. Even if you enable binding for the service,
597 you must always stop the service yourself if it ever received a call to {@link
598 android.app.Service#onStartCommand onStartCommand()}.</p>
600 <p>For more information about the lifecycle of a service, see the section below about <a
601 href="#Lifecycle">Managing the Lifecycle of a Service</a>.</p>
605 <h2 id="CreatingBoundService">Creating a Bound Service</h2>
607 <p>A bound service is one that allows application components to bind to it by calling {@link
612 <p>You should create a bound service when you want to interact with the service from activities
616 <p>To create a bound service, you must implement the {@link
617 android.app.Service#onBind onBind()} callback method to return an {@link android.os.IBinder} that
618 defines the interface for communication with the service
620 begin calling methods on the service. The service lives only to serve the application component that
621 is bound to it, so when there are no components bound to the service, the system destroys it
622 (you do <em>not</em> need to stop a bound service in the way you must when the service is started
623 through {@link android.app.Service#onStartCommand onStartCommand()}).</p>
625 <p>To create a bound service, the first thing you must do is define the interface that specifies
626 how a client can communicate with the service. This interface between the service
627 and a client must be an implementation of {@link android.os.IBinder} and is what your service must
628 return from the {@link android.app.Service#onBind
630 interacting with the service through that interface.</p>
632 <p>Multiple clients can bind to the service at once. When a client is done interacting with the
633 service, it calls {@link android.content.Context#unbindService unbindService()} to unbind. Once
634 there are no clients bound to the service, the system destroys the service.</p>
636 <p>There are multiple ways to implement a bound service and the implementation is more
637 complicated than a started service, so the bound service discussion appears in a separate
645 <p>Once running, a service can notify the user of events using <a
665 <h2 id="Foreground">Running a Service in the Foreground</h2>
667 <p>A foreground service is a service that's considered to be something the
669 foreground service must provide a notification for the status bar, which is placed under the
670 "Ongoing" heading, which means that the notification cannot be dismissed unless the service is
673 <p>For example, a music player that plays music from a service should be set to run in the
678 <p>To request that your service run in the foreground, call {@link
679 android.app.Service#startForeground startForeground()}. This method takes two parameters: an integer
694 <p>To remove the service from the foreground, call {@link
695 android.app.Service#stopForeground stopForeground()}. This method takes a boolean, indicating
697 service. However, if you stop the service while it's still running in the foreground, then the
701 android.app.Service#startForeground startForeground()} and {@link
702 android.app.Service#stopForeground stopForeground()} were introduced in Android 2.0 (API Level
703 5). In order to run your service in the foreground on older versions of the platform, you must
705 android.app.Service#startForeground startForeground()} documentation for information about how
714 <h2 id="Lifecycle">Managing the Lifecycle of a Service</h2>
716 <p>The lifecycle of a service is much simpler than that of an activity. However, it's even more important
717 that you pay close attention to how your service is created and destroyed, because a service
720 <p>The service lifecycle&mdash;from when it's created to when it's destroyed&mdash;can follow two
724 <li>A started service
725 <p>The service is created when another component calls {@link
726 android.content.Context#startService startService()}. The service then runs indefinitely and must
728 android.app.Service#stopSelf() stopSelf()}. Another component can also stop the
729 service by calling {@link android.content.Context#stopService
730 stopService()}. When the service is stopped, the system destroys it..</p></li>
732 <li>A bound service
733 <p>The service is created when another component (a client) calls {@link
734 android.content.Context#bindService bindService()}. The client then communicates with the service
737 the same service and when all of them unbind, the system destroys the service. (The service
741 <p>These two paths are not entirely separate. That is, you can bind to a service that was already
743 music service could be started by calling {@link android.content.Context#startService
746 current song, an activity can bind to the service by calling {@link
748 android.content.Context#stopService stopService()} or {@link android.app.Service#stopSelf
749 stopSelf()} does not actually stop the service until all clients unbind. </p>
754 <p>Like an activity, a service has lifecycle callback methods that you can implement to monitor
755 changes in the service's state and perform work at the appropriate times. The following skeleton
756 service demonstrates each of the lifecycle methods:</p>
759 public class ExampleService extends Service {
760 int mStartMode; // indicates how to behave if the service is killed
765 public void {@link android.app.Service#onCreate onCreate}() {
766 // The service is being created
769 public int {@link android.app.Service#onStartCommand onStartCommand}(Intent intent, int flags, int startId) {
770 // The service is starting, due to a call to {@link android.content.Context#startService startService()}
774 public IBinder {@link android.app.Service#onBind onBind}(Intent intent) {
775 // A client is binding to the service with {@link android.content.Context#bindService bindService()}
779 public boolean {@link android.app.Service#onUnbind onUnbind}(Intent intent) {
784 public void {@link android.app.Service#onRebind onRebind}(Intent intent) {
785 // A client is binding to the service with {@link android.content.Context#bindService bindService()},
789 public void {@link android.app.Service#onDestroy onDestroy}() {
790 // The service is no longer used and is being destroyed
799 <p class="img-caption"><strong>Figure 2.</strong> The service lifecycle. The diagram on the left
800 shows the lifecycle when the service is created with {@link android.content.Context#startService
801 startService()} and the diagram on the right shows the lifecycle when the service is created
804 <p>By implementing these methods, you can monitor two nested loops of the service's lifecycle: </p>
807 <li>The <strong>entire lifetime</strong> of a service happens between the time {@link
808 android.app.Service#onCreate onCreate()} is called and the time {@link
809 android.app.Service#onDestroy} returns. Like an activity, a service does its initial setup in
810 {@link android.app.Service#onCreate onCreate()} and releases all remaining resources in {@link
811 android.app.Service#onDestroy onDestroy()}. For example, a
812 music playback service could create the thread where the music will be played in {@link
813 android.app.Service#onCreate onCreate()}, then stop the thread in {@link
814 android.app.Service#onDestroy onDestroy()}.
816 <p>The {@link android.app.Service#onCreate onCreate()} and {@link android.app.Service#onDestroy
821 <li>The <strong>active lifetime</strong> of a service begins with a call to either {@link
822 android.app.Service#onStartCommand onStartCommand()} or {@link android.app.Service#onBind onBind()}.
826 <p>If the service is started, the active lifetime ends the same time that the entire lifetime
827 ends (the service is still active even after {@link android.app.Service#onStartCommand
828 onStartCommand()} returns). If the service is bound, the active lifetime ends when {@link
829 android.app.Service#onUnbind onUnbind()} returns.</p>
833 <p class="note"><strong>Note:</strong> Although a started service is stopped by a call to
834 either {@link android.app.Service#stopSelf stopSelf()} or {@link
836 service (there's no {@code onStop()} callback). So, unless the service is bound to a client,
837 the system destroys it when the service is stopped&mdash;{@link
838 android.app.Service#onDestroy onDestroy()} is the only callback received.</p>
840 <p>Figure 2 illustrates the typical callback methods for a service. Although the figure separates
843 in mind that any service, no matter how it's started, can potentially allow clients to bind to it.
844 So, a service that was initially started with {@link android.app.Service#onStartCommand
846 can still receive a call to {@link android.app.Service#onBind onBind()} (when a client calls
849 <p>For more information about creating a service that provides binding, see the <a
851 which includes more information about the {@link android.app.Service#onRebind onRebind()}
854 a Bound Service</a>.</p>