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