1 page.title=Dch v Gn kt 2 parent.title=Dch v 3 parent.link=services.html 4 @jd:body 5 6 7 <div id="qv-wrapper"> 8 <ol id="qv"> 9 <h2>Trong ti liu ny</h2> 10 <ol> 11 <li><a href="#Basics">Ni dung C bn</a></li> 12 <li><a href="#Creating">To mt Dch v Gn kt</a> 13 <ol> 14 <li><a href="#Binder">M rng lp Trnh gn kt</a></li> 15 <li><a href="#Messenger">S dng mt Hm nhn tin</a></li> 16 </ol> 17 </li> 18 <li><a href="#Binding">Gn kt vi mt Dch v</a></li> 19 <li><a href="#Lifecycle">Qun l Vng i ca mt Dch v Gn kt</a></li> 20 </ol> 21 22 <h2>Lp kha</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>Mu</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>Xem thm</h2> 38 <ol> 39 <li><a href="{@docRoot}guide/components/services.html">Dch v</a></li> 40 </ol> 41 </div> 42 43 44 <p>Dch v gn kt l my ch trong mt giao din my khch-my ch. Dch v gn kt cho php cc thnh phn 45 (chng hn nh cc hot ng) gn kt vi dch v, gi yu cu, nhn phn hi, v thm ch thc hin 46 truyn thng lin tin trnh (IPC). Dch v gn kt thng ch hot ng khi n phc v mt thnh phn 47 ng dng khc v khng chy ngm mi lin tc.</p> 48 49 <p>Ti liu ny cho bn bit cch to mt dch v gn kt, bao gm cch gn kt 50 vi dch v t cc thnh phn ng dng khc. Tuy nhin, bn cng nn tham kho ti liu <a href="{@docRoot}guide/components/services.html">Dch v</a> bit thm thng tin 51 v cc dch v ni chung, chng hn nh cch gi thng bo t mt dch v, t 52 dch v chy trong tin cnh, v nhiu ni dung khc.</p> 53 54 55 <h2 id="Basics">Ni dung C bn</h2> 56 57 <p>Dch v gn kt l mt s trin khai lp {@link android.app.Service} cho php 58 cc ng dng khc gn kt v tng tc vi n. thc hin gn kt cho mt 59 dch v, bn phi trin khai phng php gi li {@link android.app.Service#onBind onBind()}. Phng php ny 60 tr v mt i tng {@link android.os.IBinder} nh ngha giao din lp trnh m 61 cc my khch c th s dng tng tc vi dch v.</p> 62 63 <div class="sidebox-wrapper"> 64 <div class="sidebox"> 65 <h3>Gn kt vi mt Dch v c Bt u</h3> 66 67 <p>Nh cp trong ti liu <a href="{@docRoot}guide/components/services.html">Dch v</a> 68 , bn c th to mt dch v c bt u v gn kt. C th, dch v c th c 69 bt u bng cch gi {@link android.content.Context#startService startService()}, n cho php dch v 70 chy mi, v cng cho php mt my khch gn kt vi dch v bng cch gi {@link 71 android.content.Context#bindService bindService()}. 72 <p>Nu bn c cho php dch v ca mnh c bt u v gn kt, th khi dch v c 73 bt u, h thng s <em>khng</em> hy dch v khi tt c my khch b gn kt. Thay vo , bn phi 74 dng dch v mt cch r rng bng cch gi {@link android.app.Service#stopSelf stopSelf()} hoc {@link 75 android.content.Context#stopService stopService()}.</p> 76 77 <p>Mc d bn nn thng xuyn trin khai hoc {@link android.app.Service#onBind onBind()} 78 <em>hoc</em> {@link android.app.Service#onStartCommand onStartCommand()}, i khi cn phi 79 trin khai c hai. V d, mt trnh chi nhc c th cho rng nn cho php dch v ca n chy 80 mi v cng thc hin gn kt. Bng cch ny, mt hot ng c th bt u dch v chi vi 81 bn nhc v nhc tip tc chi ngay c khi ngi dng ri khi ng dng. Lc , khi ngi dng 82 tr li ng dng, hot ng c th gn kt vi dch v ginh li quyn kim sot pht li.</p> 83 84 <p>m bo c phn v <a href="#Lifecycle">Qun l Vng i ca mt Dch v 85 Gn kt</a> bit thm thng tin v vng i ca dch v khi thm gn kt vo mt 86 dch v c bt u.</p> 87 </div> 88 </div> 89 90 <p>Mt my khch c th gn kt vi dch v bng cch gi {@link android.content.Context#bindService 91 bindService()}. Khi lm vy, n phi cung cp vic trin khai {@link 92 android.content.ServiceConnection}, c chc nng theo di kt ni vi dch v. Phng php {@link 93 android.content.Context#bindService bindService()} tr v ngay lp tc m khng c gi tr, nhng 94 khi h thng Android to kt ni gia 95 my khch v dch v, n gi {@link 96 android.content.ServiceConnection#onServiceConnected onServiceConnected()} trn {@link 97 android.content.ServiceConnection}, giao {@link android.os.IBinder} m 98 my khch c th s dng giao tip vi dch v.</p> 99 100 <p>Nhiu my khch c th kt ni vi dch v ng thi. Tuy nhin, h thng s gi phng php 101 {@link android.app.Service#onBind onBind()} ca dch v ca bn truy xut {@link android.os.IBinder} ch 102 khi my khch u tin gn kt. Sau , h thng s giao cng mt {@link android.os.IBinder} cho bt k 103 my khch b sung no c gn kt m khng gi li {@link android.app.Service#onBind onBind()}.</p> 104 105 <p>Khi my khch cui cng b gn kt vi dch v, h thng s hy dch v (tr khi dch v 106 cng c bt u bi {@link android.content.Context#startService startService()}).</p> 107 108 <p>Khi bn trin khai dch v gn kt ca mnh, phn quan trng nht l nh ngha giao din 109 m phng php gi li {@link android.app.Service#onBind onBind()} ca bn s tr v. C mt vi 110 cch khc nhau m bn c th nh ngha giao din {@link android.os.IBinder} ca dch v ca mnh v phn 111 sau y s bn v tng k thut.</p> 112 113 114 115 <h2 id="Creating">To mt Dch v Gn kt</h2> 116 117 <p>Khi to mt dch v thc hin gn kt, bn phi nu mt {@link android.os.IBinder} 118 cung cp giao din lp trnh m cc my khch c th s dng tng tc vi dch v. C 119 ba cch bn c th nh ngha giao din:</p> 120 121 <dl> 122 <dt><a href="#Binder">M rng lp Trnh gn kt</a></dt> 123 <dd>Nu dch v ca bn ch ring cho ng dng ca chnh bn v chy trong cng tin trnh nh my khch 124 (iu ny thng hay gp), bn nn to giao din ca mnh bng cch m rng lp {@link android.os.Binder} 125 v tr v mt thc th ca n t 126 {@link android.app.Service#onBind onBind()}. My khch nhn c {@link android.os.Binder} v 127 c th s dng n trc tip truy cp cc phng php cng khai c sn trong trin khai {@link android.os.Binder} 128 hoc thm ch trong {@link android.app.Service}. 129 <p>Nn p dng k thut ny khi dch v ca bn ch l mt trnh thc hin chy ngm cho ng dng 130 ca chnh bn. L do duy nht bn khng nn to giao din ca mnh bng cch ny l 131 dch v ca bn c s dng bi cc ng dng khc hoc gia nhng tin trnh khc nhau.</dd> 132 133 <dt><a href="#Messenger">S dng mt Hm nhn tin</a></dt> 134 <dd>Nu bn cn giao din ca mnh thc hin cc tin trnh khc nhau, bn c th to 135 mt giao din cho dch v bng {@link android.os.Messenger}. Bng cch ny, dch v 136 nh ngha mt {@link android.os.Handler} phn hi cc loi i tng {@link 137 android.os.Message} khc nhau. {@link android.os.Handler} 138 ny l c s cho mt {@link android.os.Messenger} m sau c th chia s mt {@link android.os.IBinder} 139 vi my khch, cho php my khch gi lnh ti dch v bng cch s dng cc i tng {@link 140 android.os.Message}. Ngoi ra, my khch c th nh ngha {@link android.os.Messenger} ca 141 chnh n dch v c th gi li thng bo. 142 <p>y l cch n gin nht thc hin truyn thng lin tin trnh (IPC), v {@link 143 android.os.Messenger} xp hng tt c yu cu thnh mt lung duy nht sao cho bn khng phi thit k 144 dch v ca mnh an ton vi lung.</p> 145 </dd> 146 147 <dt>S dng AIDL</dt> 148 <dd>AIDL (Ngn ng nh ngha Giao din Android) thc hin tt c cng vic phn tch i tng thnh 149 cc phn t m h iu hnh c th hiu c v ghp ni chng qua cc tin trnh thc hin 150 IPC. Bng cch s dng {@link android.os.Messenger}, k thut trc thc t c da trn AIDL nh l 151 cu trc c bn ca n. Nh cp bn trn, {@link android.os.Messenger} to mt hng ch 152 gm tt c yu cu ca my khch trong mt lung duy nht, v th dch v nhn c tng yu cu mt. Tuy nhin, nu 153 bn mun dch v x l nhiu yu cu ng thi, bn c th s dng AIDL 154 trc tip. Trong trng hp ny, dch v ca bn phi c kh nng to a lung v c xy dng an ton vi lung. 155 <p> s dng AIDL trc tip, bn phi 156 to mt tp {@code .aidl} nh ngha giao din lp trnh. Cc cng c SDK Android s dng tp 157 ny khi to mt lp tm tt (abstract class) nhm trin khai giao din v x l IPC, m sau 158 bn c th m rng trong dch v ca mnh.</p> 159 </dd> 160 </dl> 161 162 <p class="note"><strong>Lu :</strong> Hu ht ng dng <strong>khng nn</strong> s dng AIDL 163 to mt dch v gn kt, v n c th yu cu kh nng to a lung v 164 c th dn n vic trin khai phc tp hn. Nh vy, AIDL khng ph hp vi hu ht ng dng 165 v ti liu ny khng bn v cch s dng n cho dch v ca bn. Nu bn chc chn rng mnh cn 166 s dng AIDL trc tip, hy xem ti liu <a href="{@docRoot}guide/components/aidl.html">AIDL</a> 167 .</p> 168 169 170 171 172 <h3 id="Binder">M rng lp Trnh gn kt</h3> 173 174 <p>Nu dch v ca bn ch c s dng bi ng dng cc b v khng cn lm vic qua nhiu tin trnh, 175 khi bn c th trin khai lp {@link android.os.Binder} ca chnh mnh cung cp quyn truy cp 176 trc tip cho my khch ca bn truy nhp cc phng php cng khai trong dch v.</p> 177 178 <p class="note"><strong>Lu :</strong> Cch ny ch c tc dng nu my khch v dch v nm trong cng 179 ng dng v tin trnh, l trng hp ph bin nht. V d, cch ny s hot ng tt i vi mt ng dng 180 nhc cn gn kt mt hot ng vi dch v ca chnh n ang pht nhc 181 chy ngm.</p> 182 183 <p>Sau y l cch thit lp:</p> 184 <ol> 185 <li>Trong dch v ca bn, hy to mt thc th {@link android.os.Binder} m hoc: 186 <ul> 187 <li>cha cc phng php cng khai m my khch c th gi</li> 188 <li>tr v thc th {@link android.app.Service} hin ti, trong c cc phng php cng khai m 189 my khch c th gi</li> 190 <li>hoc, tr v mt thc th ca mt lp khc c lu tr bi dch v bng cc phng php cng khai m 191 my khch c th gi</li> 192 </ul> 193 <li>Tr v thc th {@link android.os.Binder} ny t phng php gi li {@link 194 android.app.Service#onBind onBind()}.</li> 195 <li>Trong my khch, nhn {@link android.os.Binder} t phng php gi li {@link 196 android.content.ServiceConnection#onServiceConnected onServiceConnected()} v 197 thc hin gi ti dch v gn kt bng cch s dng cc phng php nu.</li> 198 </ol> 199 200 <p class="note"><strong>Lu :</strong> L do dch v v my khch phi trong cng 201 ng dng l my khch c th i kiu i tng c tr v v gi cc API ca n mt cch ph hp. Dch v 202 v my khch cng phi trong cng tin trnh, v k thut ny khng thc hin bt k thao tc 203 ghp ni qua cc tin trnh no.</p> 204 205 <p>V d, sau y l mt dch v cung cp cho my khch quyn truy cp cc phng php trong dch v thng qua 206 vic trin khai {@link android.os.Binder}:</p> 207 208 <pre> 209 public class LocalService extends Service { 210 // Binder given to clients 211 private final IBinder mBinder = new LocalBinder(); 212 // Random number generator 213 private final Random mGenerator = new Random(); 214 215 /** 216 * Class used for the client Binder. Because we know this service always 217 * runs in the same process as its clients, we don't need to deal with IPC. 218 */ 219 public class LocalBinder extends Binder { 220 LocalService getService() { 221 // Return this instance of LocalService so clients can call public methods 222 return LocalService.this; 223 } 224 } 225 226 @Override 227 public IBinder onBind(Intent intent) { 228 return mBinder; 229 } 230 231 /** method for clients */ 232 public int getRandomNumber() { 233 return mGenerator.nextInt(100); 234 } 235 } 236 </pre> 237 238 <p>{@code LocalBinder} cung cp phng php {@code getService()} cho my khch truy xut 239 thc th hin ti ca {@code LocalService}. iu ny cho php my khch gi cc phng php cng khai trong 240 dch v. V d, my khch c th gi {@code getRandomNumber()} t dch v.</p> 241 242 <p>Sau y l mt hot ng gn kt vi {@code LocalService} v s gi {@code getRandomNumber()} 243 khi nhp vo nt:</p> 244 245 <pre> 246 public class BindingActivity extends Activity { 247 LocalService mService; 248 boolean mBound = false; 249 250 @Override 251 protected void onCreate(Bundle savedInstanceState) { 252 super.onCreate(savedInstanceState); 253 setContentView(R.layout.main); 254 } 255 256 @Override 257 protected void onStart() { 258 super.onStart(); 259 // Bind to LocalService 260 Intent intent = new Intent(this, LocalService.class); 261 bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 262 } 263 264 @Override 265 protected void onStop() { 266 super.onStop(); 267 // Unbind from the service 268 if (mBound) { 269 unbindService(mConnection); 270 mBound = false; 271 } 272 } 273 274 /** Called when a button is clicked (the button in the layout file attaches to 275 * this method with the android:onClick attribute) */ 276 public void onButtonClick(View v) { 277 if (mBound) { 278 // Call a method from the LocalService. 279 // However, if this call were something that might hang, then this request should 280 // occur in a separate thread to avoid slowing down the activity performance. 281 int num = mService.getRandomNumber(); 282 Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show(); 283 } 284 } 285 286 /** Defines callbacks for service binding, passed to bindService() */ 287 private ServiceConnection mConnection = new ServiceConnection() { 288 289 @Override 290 public void onServiceConnected(ComponentName className, 291 IBinder service) { 292 // We've bound to LocalService, cast the IBinder and get LocalService instance 293 LocalBinder binder = (LocalBinder) service; 294 mService = binder.getService(); 295 mBound = true; 296 } 297 298 @Override 299 public void onServiceDisconnected(ComponentName arg0) { 300 mBound = false; 301 } 302 }; 303 } 304 </pre> 305 306 <p>Mu trn cho thy cch m my khch gn kt vi dch v bng cch s dng trin khai 307 {@link android.content.ServiceConnection} v gi li {@link 308 android.content.ServiceConnection#onServiceConnected onServiceConnected()}. Phn tip theo 309 cung cp thm thng tin v tin trnh gn kt ny vi dch v.</p> 310 311 <p class="note"><strong>Lu :</strong> V d trn khng cng khai b gn kt khi dch v, 312 nhng tt c my khch cn b gn kt ti mt thi im ph hp (chng hn nh khi hot ng tm dng).</p> 313 314 <p> bit thm m v d, hy xem lp <a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html">{@code 315 LocalService.java}</a> v lp <a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceActivities.html">{@code 316 LocalServiceActivities.java}</a> trong <a href="{@docRoot}resources/samples/ApiDemos/index.html">ApiDemos</a>.</p> 317 318 319 320 321 322 <h3 id="Messenger">S dng mt Hm nhn tin</h3> 323 324 <div class="sidebox-wrapper"> 325 <div class="sidebox"> 326 <h4>So snh vi AIDL</h4> 327 <p>Khi bn cn thc hin IPC, vic s dng mt {@link android.os.Messenger} cho giao din ca bn 328 s n gin hn so vi vic trin khai n bng AIDL, v {@link android.os.Messenger} xp hng 329 tt c lnh gi i vi dch v, trong khi , giao din AIDL thun ty s gi cc yu cu ng thi ti 330 dch v, sau dch v phi x l to a lung.</p> 331 <p>i vi hu ht ng dng, dch v khng cn thc hin to a lung, v vy s dng mt {@link 332 android.os.Messenger} s cho php dch v x l tng lnh gi ti mt thi im. Nu quan trng l 333 dch v ca bn phi c to a lung, khi bn nn s dng <a href="{@docRoot}guide/components/aidl.html">AIDL</a> nh ngha giao din ca mnh.</p> 334 </div> 335 </div> 336 337 <p>Nu bn cn dch v ca mnh giao tip vi cc tin trnh t xa, khi bn c th s dng mt 338 {@link android.os.Messenger} cung cp giao din cho dch v ca mnh. K thut ny cho php 339 bn thc hin truyn thng lin tin trnh (IPC) m khng cn s dng AIDL.</p> 340 341 <p>Sau y l tm tt cch s dng {@link android.os.Messenger}:</p> 342 343 <ul> 344 <li>Dch v trin khai {@link android.os.Handler} nhn lnh gi li cho mi 345 lnh gi t mt my khch.</li> 346 <li>{@link android.os.Handler} c s dng to mt i tng {@link android.os.Messenger} 347 (l mt tham chiu ti {@link android.os.Handler}).</li> 348 <li>{@link android.os.Messenger} to mt {@link android.os.IBinder} m dch v 349 tr v my khch t {@link android.app.Service#onBind onBind()}.</li> 350 <li>My khch s dng {@link android.os.IBinder} khi to {@link android.os.Messenger} 351 (tham chiu ti {@link android.os.Handler} ca dch v), m my khch s dng gi cc i tng 352 {@link android.os.Message} ti dch v.</li> 353 <li>Dch v nhn c tng {@link android.os.Message} trong {@link 354 android.os.Handler} ca mnh—c th l theo phng php {@link android.os.Handler#handleMessage 355 handleMessage()}.</li> 356 </ul> 357 358 359 <p>Theo cch ny, khng c "phng php" no my khch gi i vi dch v. Thay vo , my khch 360 gi thng bo (i tng {@link android.os.Message}) m dch v nhn c trong 361 {@link android.os.Handler} ca mnh.</p> 362 363 <p>Sau y l mt dch v v d n gin s dng mt giao din {@link android.os.Messenger}:</p> 364 365 <pre> 366 public class MessengerService extends Service { 367 /** Command to the service to display a message */ 368 static final int MSG_SAY_HELLO = 1; 369 370 /** 371 * Handler of incoming messages from clients. 372 */ 373 class IncomingHandler extends Handler { 374 @Override 375 public void handleMessage(Message msg) { 376 switch (msg.what) { 377 case MSG_SAY_HELLO: 378 Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show(); 379 break; 380 default: 381 super.handleMessage(msg); 382 } 383 } 384 } 385 386 /** 387 * Target we publish for clients to send messages to IncomingHandler. 388 */ 389 final Messenger mMessenger = new Messenger(new IncomingHandler()); 390 391 /** 392 * When binding to the service, we return an interface to our messenger 393 * for sending messages to the service. 394 */ 395 @Override 396 public IBinder onBind(Intent intent) { 397 Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show(); 398 return mMessenger.getBinder(); 399 } 400 } 401 </pre> 402 403 <p> rng phng php {@link android.os.Handler#handleMessage handleMessage()} trong 404 {@link android.os.Handler} l ni dch v nhn c {@link android.os.Message} 405 n v quyt nh vic cn lm da trn thnh vin {@link android.os.Message#what}.</p> 406 407 <p>Tt c vic m mt my khch cn lm l to mt {@link android.os.Messenger} da trn {@link 408 android.os.IBinder} c dch v tr v v gi mt thng bo bng cch s dng {@link 409 android.os.Messenger#send send()}. V d, sau y l mt hot ng n gin gn kt vi dch v 410 v gi tin nhn {@code MSG_SAY_HELLO} cho dch v:</p> 411 412 <pre> 413 public class ActivityMessenger extends Activity { 414 /** Messenger for communicating with the service. */ 415 Messenger mService = null; 416 417 /** Flag indicating whether we have called bind on the service. */ 418 boolean mBound; 419 420 /** 421 * Class for interacting with the main interface of the service. 422 */ 423 private ServiceConnection mConnection = new ServiceConnection() { 424 public void onServiceConnected(ComponentName className, IBinder service) { 425 // This is called when the connection with the service has been 426 // established, giving us the object we can use to 427 // interact with the service. We are communicating with the 428 // service using a Messenger, so here we get a client-side 429 // representation of that from the raw IBinder object. 430 mService = new Messenger(service); 431 mBound = true; 432 } 433 434 public void onServiceDisconnected(ComponentName className) { 435 // This is called when the connection with the service has been 436 // unexpectedly disconnected -- that is, its process crashed. 437 mService = null; 438 mBound = false; 439 } 440 }; 441 442 public void sayHello(View v) { 443 if (!mBound) return; 444 // Create and send a message to the service, using a supported 'what' value 445 Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0); 446 try { 447 mService.send(msg); 448 } catch (RemoteException e) { 449 e.printStackTrace(); 450 } 451 } 452 453 @Override 454 protected void onCreate(Bundle savedInstanceState) { 455 super.onCreate(savedInstanceState); 456 setContentView(R.layout.main); 457 } 458 459 @Override 460 protected void onStart() { 461 super.onStart(); 462 // Bind to the service 463 bindService(new Intent(this, MessengerService.class), mConnection, 464 Context.BIND_AUTO_CREATE); 465 } 466 467 @Override 468 protected void onStop() { 469 super.onStop(); 470 // Unbind from the service 471 if (mBound) { 472 unbindService(mConnection); 473 mBound = false; 474 } 475 } 476 } 477 </pre> 478 479 <p> rng v d ny khng cho bit cch m dch v c th phn hi my khch. Nu bn mun dch v 480 phn hi, khi bn cng cn to mt {@link android.os.Messenger} trong my khch. Sau 481 khi my khch nhn c lnh gi li {@link android.content.ServiceConnection#onServiceConnected 482 onServiceConnected()}, n s gi mt {@link android.os.Message} ti dch v, trong bao gm 483 {@link android.os.Messenger} ca my khch trong tham s {@link android.os.Message#replyTo} 484 ca phng php {@link android.os.Messenger#send send()}.</p> 485 486 <p>Bn c th xem mt v d v cch cung cp tnh nng nhn tin hai chiu trong <a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.html">{@code 487 MessengerService.java}</a> (dch v) v cc mu <a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerServiceActivities.html">{@code 488 MessengerServiceActivities.java}</a> (my khch).</p> 489 490 491 492 493 494 <h2 id="Binding">Gn kt vi mt Dch v</h2> 495 496 <p>Cc thnh phn ng dng (my khch) c th gn kt vi mt dch v bng cch gi 497 {@link android.content.Context#bindService bindService()}. H thng Android 498 khi s gi phng php {@link android.app.Service#onBind 499 onBind()} ca dch v, n tr v mt {@link android.os.IBinder} tng tc vi dch v.</p> 500 501 <p>Vic gn kt din ra khng ng b. {@link android.content.Context#bindService 502 bindService()} tr v ngay lp tc v <em>khng</em> tr {@link android.os.IBinder} v 503 my khch. nhn mt {@link android.os.IBinder}, my khch phi to mt thc th ca {@link 504 android.content.ServiceConnection} v chuyn n cho {@link android.content.Context#bindService 505 bindService()}. {@link android.content.ServiceConnection} bao gm mt phng php gi li m h thng 506 gi gi {@link android.os.IBinder}.</p> 507 508 <p class="note"><strong>Lu :</strong> Ch cc hot ng, dch v, v trnh cung cp ni dung mi c th gn kt 509 vi mt dch v—bn <strong>khng th</strong> gn kt vi mt dch v t mt hm nhn qung b (broadcast receiver).</p> 510 511 <p>V vy, gn kt vi mt dch v t my khch ca mnh, bn phi: </p> 512 <ol> 513 <li>Trin khai {@link android.content.ServiceConnection}. 514 <p>Vic trin khai ca bn phi khng ch hai phng php gi li:</p> 515 <dl> 516 <dt>{@link android.content.ServiceConnection#onServiceConnected onServiceConnected()}</dt> 517 <dd>H thng gi phng php ny gi {@link android.os.IBinder} c tr v bi 518 phng php {@link android.app.Service#onBind onBind()} ca dch v.</dd> 519 <dt>{@link android.content.ServiceConnection#onServiceDisconnected 520 onServiceDisconnected()}</dt> 521 <dd>H thng Android gi phng php ny khi kt ni vi dch v b mt 522 t ngt, chng hn nh khi dch v b li hoc b tt b. Phng php ny <em>khng</em> c gi khi 523 my khch b gn kt.</dd> 524 </dl> 525 </li> 526 <li>Gi {@link 527 android.content.Context#bindService bindService()}, chuyn vic trin khai {@link 528 android.content.ServiceConnection}. </li> 529 <li>Khi h thng gi phng php gi li {@link android.content.ServiceConnection#onServiceConnected 530 onServiceConnected()} ca bn, bn c th bt u thc hin cc lnh gi ti dch v bng cc phng php 531 c nh ngha bi giao din.</li> 532 <li> ngt kt ni khi dch v, hy gi {@link 533 android.content.Context#unbindService unbindService()}. 534 <p>Khi my khch ca bn b hy, n s b gn kt khi dch v, nhng bn nn lun b gn kt 535 khi bn tng tc xong vi dch v hoc khi hot ng ca bn tm dng sao cho dch v c th 536 tt khi khng dng n. (Thi im ph hp gn kt v b gn kt c cp 537 k hn bn di.)</p> 538 </li> 539 </ol> 540 541 <p>V d, on m HTML sau s kt ni my khch vi dch v c to bn trn bng cch 542 <a href="#Binder">m rng lp Trnh gn kt</a>, v vy tt c nhng vic m n phi lm l i kiu 543 {@link android.os.IBinder} c tr v thnh lp {@code LocalService} v yu cu thc th {@code 544 LocalService}:</p> 545 546 <pre> 547 LocalService mService; 548 private ServiceConnection mConnection = new ServiceConnection() { 549 // Called when the connection with the service is established 550 public void onServiceConnected(ComponentName className, IBinder service) { 551 // Because we have bound to an explicit 552 // service that is running in our own process, we can 553 // cast its IBinder to a concrete class and directly access it. 554 LocalBinder binder = (LocalBinder) service; 555 mService = binder.getService(); 556 mBound = true; 557 } 558 559 // Called when the connection with the service disconnects unexpectedly 560 public void onServiceDisconnected(ComponentName className) { 561 Log.e(TAG, "onServiceDisconnected"); 562 mBound = false; 563 } 564 }; 565 </pre> 566 567 <p>Vi {@link android.content.ServiceConnection} ny, my khch c th gn kt vi mt dch v bng cch chuyn 568 n cho {@link android.content.Context#bindService bindService()}. V d:</p> 569 570 <pre> 571 Intent intent = new Intent(this, LocalService.class); 572 bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 573 </pre> 574 575 <ul> 576 <li>Tham s u tin ca {@link android.content.Context#bindService bindService()} l mt 577 {@link android.content.Intent} trong nu r tn ca cc dch v s gn kt (mc d nh 578 c th ngm hiu).</li> 579 <li>Tham s th hai l i tng {@link android.content.ServiceConnection}.</li> 580 <li>Tham s th ba l mt c cho bit cc ty chn cho gn kt. Nn lun lun l {@link 581 android.content.Context#BIND_AUTO_CREATE} to dch v nu n cha hot ng. 582 Cc gi tr c th khc l {@link android.content.Context#BIND_DEBUG_UNBIND} 583 v {@link android.content.Context#BIND_NOT_FOREGROUND}, hoc {@code 0} trong trng hp khng c.</li> 584 </ul> 585 586 587 <h3>Lu b sung</h3> 588 589 <p>Sau y l mt s lu quan trng v vic gn kt vi mt dch v:</p> 590 <ul> 591 <li>Bn nn lun by cc li ngoi l {@link android.os.DeadObjectException} pht sinh khi 592 kt ni b t. y l li ngoi l duy nht pht sinh bi cc phng php t xa.</li> 593 <li>Cc i tng c xem l tham chiu khp cc tin trnh. </li> 594 <li>Bn nn lun ghp i gn kt v b gn kt trong khi 595 khp nhng khonh khc kt ni v t kt ni trong vng i ca my khch. V d: 596 <ul> 597 <li>Nu bn ch cn tng tc vi dch v trong khi hot ng ca bn hin th, bn 598 nn gn kt trong khi {@link android.app.Activity#onStart onStart()} v b gn kt trong khi {@link 599 android.app.Activity#onStop onStop()}.</li> 600 <li>Nu bn mun hot ng ca mnh nhn c phn hi ngay c trong khi b dng khi ang 601 di nn, khi bn c th gn kt trong khi {@link android.app.Activity#onCreate onCreate()} v b gn kt 602 trong khi {@link android.app.Activity#onDestroy onDestroy()}. Ch rng iu ny hm rng hot ng 603 ca bn cn s dng dch v trong ton b thi gian khi n ang chy (ngay c khi chy ngm), do nu 604 dch v trong mt tin trnh khc th bn hy tng trng s ca tin trnh v kh nng h thng 605 tt b tin trnh s cao hn.</li> 606 </ul> 607 <p class="note"><strong>Lu :</strong> Thng thng bn <strong>khng</strong> nn gn kt v b gn kt 608 trong khi {@link android.app.Activity#onResume onResume()} v {@link 609 android.app.Activity#onPause onPause()} cho hot ng ca mnh, v nhng lnh gi li ny din ra ti mi thi im chuyn tip vng i 610 v bn nn duy tr x l ti nhng thi im chuyn tip ny mc ti thiu. ng thi, nu 611 nhiu hot ng trong ng dng ca bn gn kt vi cng dch v v c s chuyn tip gia 612 hai trong s nhng hot ng , dch v c th b hy v to li khi hot ng hin ti b gn kt 613 (trong khi tm dng) trc khi hot ng tip theo gn kt (trong khi tip tc). (S chuyn tip hot ng ny i vi cch m cc hot ng 614 phi hp vng i ca chng c m t trong ti liu <a href="{@docRoot}guide/components/activities.html#CoordinatingActivities">Hot ng</a> 615 .)</p> 616 </ul> 617 618 <p> bit thm m v d, th hin cch gn kt vi mt dch v, hy xem lp <a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html">{@code 619 RemoteService.java}</a> trong <a href="{@docRoot}resources/samples/ApiDemos/index.html">ApiDemos</a>.</p> 620 621 622 623 624 625 <h2 id="Lifecycle">Qun l Vng i ca mt Dch v Gn kt</h2> 626 627 <p>Khi mt dch v b b gn kt khi tt c my khch, h thng Android s hy n (tr khi n cng 628 c bt u bng {@link android.app.Service#onStartCommand onStartCommand()}). Nh vy, bn khng phi 629 qun l vng i dch v ca mnh nu n thun ty l mt 630 dch v gn kt—h thng Android s qun l n cho bn da trn vic n c gn kt vi bt k my khch no khng.</p> 631 632 <p>Tuy nhin, nu bn chn trin khai phng php gi li {@link android.app.Service#onStartCommand 633 onStartCommand()}, vy th bn phi dng dch v mt cch tng minh, v dch v 634 lc ny ang c coi l <em>c bt u</em>. Trong trng hp ny, dch v s chy cho ti khi dch v 635 t dng bng {@link android.app.Service#stopSelf()} hoc mt thnh phn khc s gi {@link 636 android.content.Context#stopService stopService()}, bt k n c gn kt vi bt k my khch 637 no khng.</p> 638 639 <p>Ngoi ra, nu dch v ca bn c bt u v chp nhn gn kt, lc khi h thng gi 640 phng php {@link android.app.Service#onUnbind onUnbind()} ca bn, bn c th ty chn tr v 641 {@code true} nu bn mun nhn mt lnh gi ti {@link android.app.Service#onRebind 642 onRebind()} vo ln ti khi mt my khch gn kt vi dch v (thay v nhn mt lnh gi ti {@link 643 android.app.Service#onBind onBind()}). {@link android.app.Service#onRebind 644 onRebind()} s tr v rng, nhng my khch vn nhn c {@link android.os.IBinder} trong gi li 645 {@link android.content.ServiceConnection#onServiceConnected onServiceConnected()} ca mnh. 646 Hnh 1 bn di minh ha l-gic cho loi vng i ny.</p> 647 648 649 <img src="{@docRoot}images/fundamentals/service_binding_tree_lifecycle.png" alt="" /> 650 <p class="img-caption"><strong>Hnh 1.</strong> Vng i ca mt dch v c bt u 651 v cng cho php gn kt.</p> 652 653 654 <p> bit thm thng tin v vng i ca mt dch v c bt u, hy xem ti liu <a href="{@docRoot}guide/components/services.html#Lifecycle">Dch v</a>.</p> 655 656 657 658 659