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