• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Bound Services
2parent.title=Services
3parent.link=services.html
4@jd:body
5
6
7<div id="qv-wrapper">
8<ol id="qv">
9<h2>In this document</h2>
10<ol>
11  <li><a href="#Basics">The Basics</a></li>
12  <li><a href="#Creating">Creating a Bound Service</a>
13    <ol>
14      <li><a href="#Binder">Extending the Binder class</a></li>
15      <li><a href="#Messenger">Using a Messenger</a></li>
16    </ol>
17  </li>
18  <li><a href="#Binding">Binding to a Service</a>
19    <ol>
20      <li><a href="#Additional_Notes">Additional notes</a></li>
21    </ol>
22  </li>
23  <li><a href="#Lifecycle">Managing the Lifecycle of a Bound Service</a></li>
24</ol>
25
26<h2>Key classes</h2>
27<ol>
28  <li>{@link android.app.Service}</li>
29  <li>{@link android.content.ServiceConnection}</li>
30  <li>{@link android.os.IBinder}</li>
31</ol>
32
33<h2>Samples</h2>
34<ol>
35  <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html">{@code
36      RemoteService}</a></li>
37  <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html">{@code
38      LocalService}</a></li>
39</ol>
40
41<h2>See also</h2>
42<ol>
43  <li><a href="{@docRoot}guide/components/services.html">Services</a></li>
44</ol>
45</div>
46
47
48<p>A bound service is the server in a client-server interface. A bound service allows components
49(such as activities) to bind to the service, send requests, receive responses, and even perform
50interprocess communication (IPC). A bound service typically lives only while it serves another
51application component and does not run in the background indefinitely.</p>
52
53<p>This document shows you how to create a bound service, including how to bind
54to the service from other application components. However, you should also refer to the <a
55href="{@docRoot}guide/components/services.html">Services</a> document for additional
56information about services in general, such as how to deliver notifications from a service, set
57the service to run in the foreground, and more.</p>
58
59
60<h2 id="Basics">The Basics</h2>
61
62<p>A bound service is an implementation of the {@link android.app.Service} class that allows
63other applications to bind to it and interact with it. To provide binding for a
64service, you must implement the {@link android.app.Service#onBind onBind()} callback method. This
65method returns an {@link android.os.IBinder} object that defines the programming interface that
66clients can use to interact with the service.</p>
67
68<div class="sidebox-wrapper">
69<div class="sidebox">
70  <h3>Binding to a Started Service</h3>
71
72<p>As discussed in the <a href="{@docRoot}guide/components/services.html">Services</a>
73document, you can create a service that is both started and bound. That is, the service can be
74started by calling {@link android.content.Context#startService startService()}, which allows the
75service to run indefinitely, and also allow a client to bind to the service by calling {@link
76android.content.Context#bindService bindService()}.
77  <p>If you do allow your service to be started and bound, then when the service has been
78started, the system does <em>not</em> destroy the service when all clients unbind. Instead, you must
79explicitly stop the service, by calling {@link android.app.Service#stopSelf stopSelf()} or {@link
80android.content.Context#stopService stopService()}.</p>
81
82<p>Although you should usually implement either {@link android.app.Service#onBind onBind()}
83<em>or</em> {@link android.app.Service#onStartCommand onStartCommand()}, it's sometimes necessary to
84implement both. For example, a music player might find it useful to allow its service to run
85indefinitely and also provide binding. This way, an activity can start the service to play some
86music and the music continues to play even if the user leaves the application. Then, when the user
87returns to the application, the activity can bind to the service to regain control of playback.</p>
88
89<p>Be sure to read the section about <a href="#Lifecycle">Managing the Lifecycle of a Bound
90Service</a>, for more information about the service lifecycle when adding binding to a
91started service.</p>
92</div>
93</div>
94
95<p>A client can bind to the service by calling {@link android.content.Context#bindService
96bindService()}. When it does, it must provide an implementation of {@link
97android.content.ServiceConnection}, which monitors the connection with the service. The {@link
98android.content.Context#bindService bindService()} method returns immediately without a value, but
99when the Android system creates the connection between the
100client and service, it calls {@link
101android.content.ServiceConnection#onServiceConnected onServiceConnected()} on the {@link
102android.content.ServiceConnection}, to deliver the {@link android.os.IBinder} that
103the client can use to communicate with the service.</p>
104
105<p>Multiple clients can connect to the service at once. However, the system calls your service's
106{@link android.app.Service#onBind onBind()} method to retrieve the {@link android.os.IBinder} only
107when the first client binds. The system then delivers the same {@link android.os.IBinder} to any
108additional clients that bind, without calling {@link android.app.Service#onBind onBind()} again.</p>
109
110<p>When the last client unbinds from the service, the system destroys the service (unless the
111service was also started by {@link android.content.Context#startService startService()}).</p>
112
113<p>When you implement your bound service, the most important part is defining the interface
114that your {@link android.app.Service#onBind onBind()} callback method returns. There are a few
115different ways you can define your service's {@link android.os.IBinder} interface and the following
116section discusses each technique.</p>
117
118
119
120<h2 id="Creating">Creating a Bound Service</h2>
121
122<p>When creating a service that provides binding, you must provide an {@link android.os.IBinder}
123that provides the programming interface that clients can use to interact with the service. There
124are three ways you can define the interface:</p>
125
126<dl>
127  <dt><a href="#Binder">Extending the Binder class</a></dt>
128  <dd>If your service is private to your own application and runs in the same process as the client
129(which is common), you should create your interface by extending the {@link android.os.Binder} class
130and returning an instance of it from
131{@link android.app.Service#onBind onBind()}. The client receives the {@link android.os.Binder} and
132can use it to directly access public methods available in either the {@link android.os.Binder}
133implementation or even the {@link android.app.Service}.
134  <p>This is the preferred technique when your service is merely a background worker for your own
135application. The only reason you would not create your interface this way is because
136your service is used by other applications or across separate processes.</dd>
137
138  <dt><a href="#Messenger">Using a Messenger</a></dt>
139  <dd>If you need your interface to work across different processes, you can create
140an interface for the service with a {@link android.os.Messenger}. In this manner, the service
141defines a {@link android.os.Handler} that responds to different types of {@link
142android.os.Message} objects. This {@link android.os.Handler}
143is the basis for a {@link android.os.Messenger} that can then share an {@link android.os.IBinder}
144with the client, allowing the client to send commands to the service using {@link
145android.os.Message} objects. Additionally, the client can define a {@link android.os.Messenger} of
146its own so the service can send messages back.
147  <p>This is the simplest way to perform interprocess communication (IPC), because the {@link
148android.os.Messenger} queues all requests into a single thread so that you don't have to design
149your service to be thread-safe.</p>
150  </dd>
151
152  <dt>Using AIDL</dt>
153  <dd>AIDL (Android Interface Definition Language) performs all the work to decompose objects into
154primitives that the operating system can understand and marshall them across processes to perform
155IPC. The previous technique, using a {@link android.os.Messenger}, is actually based on AIDL as
156its underlying structure. As mentioned above, the {@link android.os.Messenger} creates a queue of
157all the client requests in a single thread, so the service receives requests one at a time. If,
158however, you want your service to handle multiple requests simultaneously, then you can use AIDL
159directly. In this case, your service must be capable of multi-threading and be built thread-safe.
160  <p>To use AIDL directly, you must
161create an {@code .aidl} file that defines the programming interface. The Android SDK tools use
162this file to generate an abstract class that implements the interface and handles IPC, which you
163can then extend within your service.</p>
164  </dd>
165</dl>
166
167  <p class="note"><strong>Note:</strong> Most applications <strong>should not</strong> use AIDL to
168create a bound service, because it may require multithreading capabilities and
169can result in a more complicated implementation. As such, AIDL is not suitable for most applications
170and this document does not discuss how to use it for your service. If you're certain that you need
171to use AIDL directly, see the <a href="{@docRoot}guide/components/aidl.html">AIDL</a>
172document.</p>
173
174
175
176
177<h3 id="Binder">Extending the Binder class</h3>
178
179<p>If your service is used only by the local application and does not need to work across processes,
180then you can implement your own {@link android.os.Binder} class that provides your client direct
181access to public methods in the service.</p>
182
183<p class="note"><strong>Note:</strong> This works only if the client and service are in the same
184application and process, which is most common. For example, this would work well for a music
185application that needs to bind an activity to its own service that's playing music in the
186background.</p>
187
188<p>Here's how to set it up:</p>
189<ol>
190  <li>In your service, create an instance of {@link android.os.Binder} that either:
191    <ul>
192      <li>contains public methods that the client can call</li>
193      <li>returns the current {@link android.app.Service} instance, which has public methods the
194client can call</li>
195      <li>or, returns an instance of another class hosted by the service with public methods the
196client can call</li>
197    </ul>
198  <li>Return this instance of {@link android.os.Binder} from the {@link
199android.app.Service#onBind onBind()} callback method.</li>
200  <li>In the client, receive the {@link android.os.Binder} from the {@link
201android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback method and
202make calls to the bound service using the methods provided.</li>
203</ol>
204
205<p class="note"><strong>Note:</strong> The reason the service and client must be in the same
206application is so the client can cast the returned object and properly call its APIs. The service
207and client must also be in the same process, because this technique does not perform any
208marshalling across processes.</p>
209
210<p>For example, here's a service that provides clients access to methods in the service through
211a {@link android.os.Binder} implementation:</p>
212
213<pre>
214public class LocalService extends Service {
215    // Binder given to clients
216    private final IBinder mBinder = new LocalBinder();
217    // Random number generator
218    private final Random mGenerator = new Random();
219
220    /**
221     * Class used for the client Binder.  Because we know this service always
222     * runs in the same process as its clients, we don't need to deal with IPC.
223     */
224    public class LocalBinder extends Binder {
225        LocalService getService() {
226            // Return this instance of LocalService so clients can call public methods
227            return LocalService.this;
228        }
229    }
230
231    &#64;Override
232    public IBinder onBind(Intent intent) {
233        return mBinder;
234    }
235
236    /** method for clients */
237    public int getRandomNumber() {
238      return mGenerator.nextInt(100);
239    }
240}
241</pre>
242
243<p>The {@code LocalBinder} provides the {@code getService()} method for clients to retrieve the
244current instance of {@code LocalService}. This allows clients to call public methods in the
245service. For example, clients can call {@code getRandomNumber()} from the service.</p>
246
247<p>Here's an activity that binds to {@code LocalService} and calls {@code getRandomNumber()}
248when a button is clicked:</p>
249
250<pre>
251public class BindingActivity extends Activity {
252    LocalService mService;
253    boolean mBound = false;
254
255    &#64;Override
256    protected void onCreate(Bundle savedInstanceState) {
257        super.onCreate(savedInstanceState);
258        setContentView(R.layout.main);
259    }
260
261    &#64;Override
262    protected void onStart() {
263        super.onStart();
264        // Bind to LocalService
265        Intent intent = new Intent(this, LocalService.class);
266        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
267    }
268
269    &#64;Override
270    protected void onStop() {
271        super.onStop();
272        // Unbind from the service
273        if (mBound) {
274            unbindService(mConnection);
275            mBound = false;
276        }
277    }
278
279    /** Called when a button is clicked (the button in the layout file attaches to
280      * this method with the android:onClick attribute) */
281    public void onButtonClick(View v) {
282        if (mBound) {
283            // Call a method from the LocalService.
284            // However, if this call were something that might hang, then this request should
285            // occur in a separate thread to avoid slowing down the activity performance.
286            int num = mService.getRandomNumber();
287            Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
288        }
289    }
290
291    /** Defines callbacks for service binding, passed to bindService() */
292    private ServiceConnection mConnection = new ServiceConnection() {
293
294        &#64;Override
295        public void onServiceConnected(ComponentName className,
296                IBinder service) {
297            // We've bound to LocalService, cast the IBinder and get LocalService instance
298            LocalBinder binder = (LocalBinder) service;
299            mService = binder.getService();
300            mBound = true;
301        }
302
303        &#64;Override
304        public void onServiceDisconnected(ComponentName arg0) {
305            mBound = false;
306        }
307    };
308}
309</pre>
310
311<p>The above sample shows how the client binds to the service using an implementation of
312{@link android.content.ServiceConnection} and the {@link
313android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback. The next
314section provides more information about this process of binding to the service.</p>
315
316<p class="note"><strong>Note:</strong> In the example above, the
317{@link android.app.Activity#onStop onStop()} method unbinds the client from the service. Clients
318should unbind from services at appropriate times, as discussed in
319<a href="#Additional_Notes">Additional Notes</a>.
320</p>
321
322<p>For more sample code, see the <a
323href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html">{@code
324LocalService.java}</a> class and the <a
325href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceActivities.html">{@code
326LocalServiceActivities.java}</a> class in <a
327href="{@docRoot}resources/samples/ApiDemos/index.html">ApiDemos</a>.</p>
328
329
330
331
332
333<h3 id="Messenger">Using a Messenger</h3>
334
335<div class="sidebox-wrapper">
336<div class="sidebox">
337  <h4>Compared to AIDL</h4>
338  <p>When you need to perform IPC, using a {@link android.os.Messenger} for your interface is
339simpler than implementing it with AIDL, because {@link android.os.Messenger} queues
340all calls to the service, whereas, a pure AIDL interface sends simultaneous requests to the
341service, which must then handle multi-threading.</p>
342  <p>For most applications, the service doesn't need to perform multi-threading, so using a {@link
343android.os.Messenger} allows the service to handle one call at a time. If it's important
344that your service be multi-threaded, then you should use <a
345href="{@docRoot}guide/components/aidl.html">AIDL</a> to define your interface.</p>
346</div>
347</div>
348
349<p>If you need your service to communicate with remote processes, then you can use a
350{@link android.os.Messenger} to provide the interface for your service. This technique allows
351you to perform interprocess communication (IPC) without the need to use AIDL.</p>
352
353<p>Here's a summary of how to use a {@link android.os.Messenger}:</p>
354
355<ul>
356  <li>The service implements a {@link android.os.Handler} that receives a callback for each
357call from a client.</li>
358  <li>The {@link android.os.Handler} is used to create a {@link android.os.Messenger} object
359(which is a reference to the {@link android.os.Handler}).</li>
360  <li>The {@link android.os.Messenger} creates an {@link android.os.IBinder} that the service
361returns to clients from {@link android.app.Service#onBind onBind()}.</li>
362  <li>Clients use the {@link android.os.IBinder} to instantiate the {@link android.os.Messenger}
363(that references the service's {@link android.os.Handler}), which the client uses to send
364{@link android.os.Message} objects to the service.</li>
365  <li>The service receives each {@link android.os.Message} in its {@link
366android.os.Handler}&mdash;specifically, in the {@link android.os.Handler#handleMessage
367handleMessage()} method.</li>
368</ul>
369
370
371<p>In this way, there are no "methods" for the client to call on the service. Instead, the
372client delivers "messages" ({@link android.os.Message} objects) that the service receives in
373its {@link android.os.Handler}.</p>
374
375<p>Here's a simple example service that uses a {@link android.os.Messenger} interface:</p>
376
377<pre>
378public class MessengerService extends Service {
379    /** Command to the service to display a message */
380    static final int MSG_SAY_HELLO = 1;
381
382    /**
383     * Handler of incoming messages from clients.
384     */
385    class IncomingHandler extends Handler {
386        &#64;Override
387        public void handleMessage(Message msg) {
388            switch (msg.what) {
389                case MSG_SAY_HELLO:
390                    Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
391                    break;
392                default:
393                    super.handleMessage(msg);
394            }
395        }
396    }
397
398    /**
399     * Target we publish for clients to send messages to IncomingHandler.
400     */
401    final Messenger mMessenger = new Messenger(new IncomingHandler());
402
403    /**
404     * When binding to the service, we return an interface to our messenger
405     * for sending messages to the service.
406     */
407    &#64;Override
408    public IBinder onBind(Intent intent) {
409        Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
410        return mMessenger.getBinder();
411    }
412}
413</pre>
414
415<p>Notice that the {@link android.os.Handler#handleMessage handleMessage()} method in the
416{@link android.os.Handler} is where the service receives the incoming {@link android.os.Message}
417and decides what to do, based on the {@link android.os.Message#what} member.</p>
418
419<p>All that a client needs to do is create a {@link android.os.Messenger} based on the {@link
420android.os.IBinder} returned by the service and send a message using {@link
421android.os.Messenger#send send()}. For example, here's a simple activity that binds to the
422service and delivers the {@code MSG_SAY_HELLO} message to the service:</p>
423
424<pre>
425public class ActivityMessenger extends Activity {
426    /** Messenger for communicating with the service. */
427    Messenger mService = null;
428
429    /** Flag indicating whether we have called bind on the service. */
430    boolean mBound;
431
432    /**
433     * Class for interacting with the main interface of the service.
434     */
435    private ServiceConnection mConnection = new ServiceConnection() {
436        public void onServiceConnected(ComponentName className, IBinder service) {
437            // This is called when the connection with the service has been
438            // established, giving us the object we can use to
439            // interact with the service.  We are communicating with the
440            // service using a Messenger, so here we get a client-side
441            // representation of that from the raw IBinder object.
442            mService = new Messenger(service);
443            mBound = true;
444        }
445
446        public void onServiceDisconnected(ComponentName className) {
447            // This is called when the connection with the service has been
448            // unexpectedly disconnected -- that is, its process crashed.
449            mService = null;
450            mBound = false;
451        }
452    };
453
454    public void sayHello(View v) {
455        if (!mBound) return;
456        // Create and send a message to the service, using a supported 'what' value
457        Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
458        try {
459            mService.send(msg);
460        } catch (RemoteException e) {
461            e.printStackTrace();
462        }
463    }
464
465    &#64;Override
466    protected void onCreate(Bundle savedInstanceState) {
467        super.onCreate(savedInstanceState);
468        setContentView(R.layout.main);
469    }
470
471    &#64;Override
472    protected void onStart() {
473        super.onStart();
474        // Bind to the service
475        bindService(new Intent(this, MessengerService.class), mConnection,
476            Context.BIND_AUTO_CREATE);
477    }
478
479    &#64;Override
480    protected void onStop() {
481        super.onStop();
482        // Unbind from the service
483        if (mBound) {
484            unbindService(mConnection);
485            mBound = false;
486        }
487    }
488}
489</pre>
490
491<p>Notice that this example does not show how the service can respond to the client. If you want the
492service to respond, then you need to also create a {@link android.os.Messenger} in the client. Then
493when the client receives the {@link android.content.ServiceConnection#onServiceConnected
494onServiceConnected()} callback, it sends a {@link android.os.Message} to the service that includes
495the client's {@link android.os.Messenger} in the {@link android.os.Message#replyTo} parameter
496of the {@link android.os.Messenger#send send()} method.</p>
497
498<p>You can see an example of how to provide two-way messaging in the <a
499href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.html">{@code
500MessengerService.java}</a> (service) and <a
501href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerServiceActivities.html">{@code
502MessengerServiceActivities.java}</a> (client) samples.</p>
503
504
505
506
507
508<h2 id="Binding">Binding to a Service</h2>
509
510<p>Application components (clients) can bind to a service by calling
511{@link android.content.Context#bindService bindService()}. The Android
512system then calls the service's {@link android.app.Service#onBind
513onBind()} method, which returns an {@link android.os.IBinder} for interacting with the service.</p>
514
515<p>The binding is asynchronous. {@link android.content.Context#bindService
516bindService()} returns immediately and does <em>not</em> return the {@link android.os.IBinder} to
517the client. To receive the {@link android.os.IBinder}, the client must create an instance of {@link
518android.content.ServiceConnection} and pass it to {@link android.content.Context#bindService
519bindService()}. The {@link android.content.ServiceConnection} includes a callback method that the
520system calls to deliver the {@link android.os.IBinder}.</p>
521
522<p class="note"><strong>Note:</strong> Only activities, services, and content providers can bind
523to a service&mdash;you <strong>cannot</strong> bind to a service from a broadcast receiver.</p>
524
525<p>So, to bind to a service from your client, you must: </p>
526<ol>
527  <li>Implement {@link android.content.ServiceConnection}.
528    <p>Your implementation must override two callback methods:</p>
529    <dl>
530      <dt>{@link android.content.ServiceConnection#onServiceConnected onServiceConnected()}</dt>
531        <dd>The system calls this to deliver the {@link android.os.IBinder} returned by
532the service's {@link android.app.Service#onBind onBind()} method.</dd>
533      <dt>{@link android.content.ServiceConnection#onServiceDisconnected
534onServiceDisconnected()}</dt>
535        <dd>The Android system calls this when the connection to the service is unexpectedly
536lost, such as when the service has crashed or has been killed. This is <em>not</em> called when the
537client unbinds.</dd>
538    </dl>
539  </li>
540  <li>Call {@link
541android.content.Context#bindService bindService()}, passing the {@link
542android.content.ServiceConnection} implementation. </li>
543  <li>When the system calls your {@link android.content.ServiceConnection#onServiceConnected
544onServiceConnected()} callback method, you can begin making calls to the service, using
545the methods defined by the interface.</li>
546  <li>To disconnect from the service, call {@link
547android.content.Context#unbindService unbindService()}.
548  <p>If your client is still bound to a service when your app destroys the client, destruction
549causes the client to unbind. It is better practice to unbind the client as soon as it is done
550interacting with the service. Doing so allows the idle service to shut down. For more information
551about appropriate times to bind and unbind, see <a href="#Additional_Notes">Additional Notes</a>.
552</p>
553  </li>
554</ol>
555
556<p>For example, the following snippet connects the client to the service created above by
557<a href="#Binder">extending the Binder class</a>, so all it must do is cast the returned
558{@link android.os.IBinder} to the {@code LocalService} class and request the {@code
559LocalService} instance:</p>
560
561<pre>
562LocalService mService;
563private ServiceConnection mConnection = new ServiceConnection() {
564    // Called when the connection with the service is established
565    public void onServiceConnected(ComponentName className, IBinder service) {
566        // Because we have bound to an explicit
567        // service that is running in our own process, we can
568        // cast its IBinder to a concrete class and directly access it.
569        LocalBinder binder = (LocalBinder) service;
570        mService = binder.getService();
571        mBound = true;
572    }
573
574    // Called when the connection with the service disconnects unexpectedly
575    public void onServiceDisconnected(ComponentName className) {
576        Log.e(TAG, "onServiceDisconnected");
577        mBound = false;
578    }
579};
580</pre>
581
582<p>With this {@link android.content.ServiceConnection}, the client can bind to a service by passing
583it to {@link android.content.Context#bindService bindService()}. For example:</p>
584
585<pre>
586Intent intent = new Intent(this, LocalService.class);
587bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
588</pre>
589
590<ul>
591  <li>The first parameter of {@link android.content.Context#bindService bindService()} is an
592{@link android.content.Intent} that explicitly names the service to bind (thought the intent
593could be implicit).</li>
594<li>The second parameter is the {@link android.content.ServiceConnection} object.</li>
595<li>The third parameter is a flag indicating options for the binding. It should usually be {@link
596android.content.Context#BIND_AUTO_CREATE} in order to create the service if its not already alive.
597Other possible values are {@link android.content.Context#BIND_DEBUG_UNBIND}
598and {@link android.content.Context#BIND_NOT_FOREGROUND}, or {@code 0} for none.</li>
599</ul>
600
601
602<h3 id="Additional_Notes">Additional notes</h3>
603
604<p>Here are some important notes about binding to a service:</p>
605<ul>
606  <li>You should always trap {@link android.os.DeadObjectException} exceptions, which are thrown
607when the connection has broken. This is the only exception thrown by remote methods.</li>
608  <li>Objects are reference counted across processes. </li>
609  <li>You should usually pair the binding and unbinding during
610matching bring-up and tear-down moments of the client's lifecycle. For example:
611    <ul>
612      <li>If you only need to interact with the service while your activity is visible, you
613should bind during {@link android.app.Activity#onStart onStart()} and unbind during {@link
614android.app.Activity#onStop onStop()}.</li>
615      <li>If you want your activity to receive responses even while it is stopped in the
616background, then you can bind during {@link android.app.Activity#onCreate onCreate()} and unbind
617during {@link android.app.Activity#onDestroy onDestroy()}. Beware that this implies that your
618activity needs to use the service the entire time it's running (even in the background), so if
619the service is in another process, then you increase the weight of the process and it becomes
620more likely that the system will kill it.</li>
621    </ul>
622    <p class="note"><strong>Note:</strong> You should usually <strong>not</strong> bind and unbind
623during your activity's {@link android.app.Activity#onResume onResume()} and {@link
624android.app.Activity#onPause onPause()}, because these callbacks occur at every lifecycle transition
625and you should keep the processing that occurs at these transitions to a minimum. Also, if
626multiple activities in your application bind to the same service and there is a transition between
627two of those activities, the service may be destroyed and recreated as the current activity unbinds
628(during pause) before the next one binds (during resume). (This activity transition for how
629activities coordinate their lifecycles is described in the <a
630href="{@docRoot}guide/components/activities.html#CoordinatingActivities">Activities</a>
631document.)</p>
632</ul>
633
634<p>For more sample code, showing how to bind to a service, see the <a
635href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html">{@code
636RemoteService.java}</a> class in <a
637href="{@docRoot}resources/samples/ApiDemos/index.html">ApiDemos</a>.</p>
638
639
640
641
642
643<h2 id="Lifecycle">Managing the Lifecycle of a Bound Service</h2>
644
645<p>When a service is unbound from all clients, the Android system destroys it (unless it was also
646started with {@link android.app.Service#onStartCommand onStartCommand()}). As such, you don't have
647to manage the lifecycle of your service if it's purely a bound
648service&mdash;the Android system manages it for you based on whether it is bound to any clients.</p>
649
650<p>However, if you choose to implement the {@link android.app.Service#onStartCommand
651onStartCommand()} callback method, then you must explicitly stop the service, because the
652service is now considered to be <em>started</em>. In this case, the service runs until the service
653stops itself with {@link android.app.Service#stopSelf()} or another component calls {@link
654android.content.Context#stopService stopService()}, regardless of whether it is bound to any
655clients.</p>
656
657<p>Additionally, if your service is started and accepts binding, then when the system calls
658your {@link android.app.Service#onUnbind onUnbind()} method, you can optionally return
659{@code true} if you would like to receive a call to {@link android.app.Service#onRebind
660onRebind()} the next time a client binds to the service. {@link android.app.Service#onRebind
661onRebind()} returns void, but the client still receives the {@link android.os.IBinder} in its
662{@link android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback.
663Below, figure 1 illustrates the logic for this kind of lifecycle.</p>
664
665
666<img src="{@docRoot}images/fundamentals/service_binding_tree_lifecycle.png" alt="" />
667<p class="img-caption"><strong>Figure 1.</strong> The lifecycle for a service that is started
668and also allows binding.</p>
669
670
671<p>For more information about the lifecycle of a started service, see the <a
672href="{@docRoot}guide/components/services.html#Lifecycle">Services</a> document.</p>
673
674
675
676
677