summaryrefslogtreecommitdiff
path: root/docs/html-intl/intl/zh-cn/guide/components/services.jd
blob: c7c848b75e39a90223b7ed6e0508afe72f8be83e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
page.title=服务
@jd:body

<div id="qv-wrapper">
<ol id="qv">
<h2>本文内容</h2>
<ol>
<li><a href="#Basics">基础知识</a></li>
<ol>
  <li><a href="#Declaring">使用清单文件声明服务</a></li>
</ol>
<li><a href="#CreatingAService">创建启动服务</a>
  <ol>
    <li><a href="#ExtendingIntentService">扩展 IntentService 类</a></li>
    <li><a href="#ExtendingService">扩展服务类</a></li>
    <li><a href="#StartingAService">启动服务</a></li>
    <li><a href="#Stopping">停止服务</a></li>
  </ol>
</li>
<li><a href="#CreatingBoundService">创建绑定服务</a></li>
<li><a href="#Notifications">向用户发送通知</a></li>
<li><a href="#Foreground">在前台运行服务</a></li>
<li><a href="#Lifecycle">管理服务生命周期</a>
<ol>
  <li><a href="#LifecycleCallbacks">实现生命周期回调</a></li>
</ol>
</li>
</ol>

<h2>关键类</h2>
<ol>
  <li>{@link android.app.Service}</li>
  <li>{@link android.app.IntentService}</li>
</ol>

<h2>示例</h2>
<ol>
  <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/ServiceStartArguments.html">{@code
      ServiceStartArguments}</a></li>
  <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html">{@code
      LocalService}</a></li>
</ol>

<h2>另请参阅</h2>
<ol>
<li><a href="{@docRoot}guide/components/bound-services.html">绑定服务</a></li>
</ol>

</div>


<p>{@link android.app.Service}
是一个可以在后台执行长时间运行操作而不使用用户界面的应用组件。服务可由其他应用组件启动,而且即使用户切换到其他应用,服务仍将在后台继续运行。

此外,组件可以绑定到服务,以与之进行交互,甚至是执行进程间通信 (IPC)。
例如,服务可以处理网络事务、播放音乐,执行文件 I/O
或与内容提供程序交互,而所有这一切均可在后台进行。
</p>

<p>服务基本上分为两种形式:</p>

<dl>
  <dt>启动</dt>
  <dd>当应用组件(如 Activity)通过调用
{@link android.content.Context#startService startService()} 启动服务时,服务即处于“启动”状态。一旦启动,服务即可在后台无限期运行,即使启动服务的组件已被销毁也不受影响。
已启动的服务通常是执行单一操作,而且不会将结果返回给调用方。例如,它可能通过网络下载或上传文件。

操作完成后,服务会自行停止运行。
</dd>
  <dt>绑定</dt>
  <dd>当应用组件通过调用 {@link
android.content.Context#bindService bindService()} 绑定到服务时,服务即处于“绑定”状态。绑定服务提供了一个客户端-服务器接口,允许组件与服务进行交互、发送请求、获取结果,甚至是利用进程间通信 (IPC)
跨进程执行这些操作。
仅当与另一个应用组件绑定时,绑定服务才会运行。
多个组件可以同时绑定到该服务,但全部取消绑定后,该服务即会被销毁。
</dd>
</dl>

<p>虽然本文档是分开概括讨论这两种服务,但是您的服务可以同时以这两种方式运行,也就是说,它既可以是启动服务(以无限期运行),也允许绑定。问题只是在于您是否实现了一组回调方法:{@link
android.app.Service#onStartCommand onStartCommand()}(允许组件启动服务)和 {@link
android.app.Service#onBind onBind()}(允许绑定服务)。

</p>

<p>无论应用是处于启动状态还是绑定状态,抑或处于启动并且绑定状态,任何应用组件均可像使用活动那样通过调用 {@link android.content.Intent} 来使用服务(即使此服务来自另一应用)。

不过,您可以通过清单文件将服务声明为私有服务,并阻止其他应用访问。
<a href="#Declaring">使用清单文件声明服务</a>部分将对此做更详尽的阐述。

</p>

<p class="caution"><strong>注意:</strong>服务在其托管进程的主线程中运行,它既<strong>不</strong>创建自己的线程,也<strong>不</strong>在单独的进程中运行(除非另行指定)。

这意味着,如果服务将执行任何
CPU 密集型工作或阻止性操作(例如 MP3
播放或联网),则应在服务内创建新线程来完成这项工作。通过使用单独的线程,可以降低发生“应用无响应”(ANR)
错误的风险,而应用的主线程仍可继续专注于运行用户与 Activity 之间的交互。
</p>


<h2 id="Basics">基础知识</h2>

<div class="sidebox-wrapper">
<div class="sidebox">
  <h3>您应使用服务还是线程?</h3>
  <p>简单地说,服务是一种即使用户未与应用交互,但它仍可以在后台运行的组件。
因此,您应仅在必要时才创建服务。
</p>
  <p>如需在主线程外部执行工作,不过只是在用户正在与应用交互时才有此需要,则应创建新线程而非服务。
例如,如果您只是想在 Activity 运行的同时播放一些音乐,则可在
{@link android.app.Activity#onCreate onCreate()}
中创建线程,在 {@link
android.app.Activity#onStart onStart()} 中启动线程,然后在 {@link android.app.Activity#onStop
onStop()} 中停止线程。您还可以考虑使用
{@link android.os.AsyncTask} 或 {@link android.os.HandlerThread},而非传统的 {@link java.lang.Thread} 类。如需了解有关线程的详细信息,请参阅<a href="{@docRoot}guide/components/processes-and-threads.html#Threads">进程和线程</a>文档。
</p>
  <p>请记住,如果您确实要使用服务,则默认情况下,它仍会在应用的主线程中运行,因此,如果服务执行的是密集型或阻止性操作,则您仍应在服务内创建新线程。

</p>
</div>
</div>

<p>要创建服务,您必须创建
{@link android.app.Service} 的子类(或使用它的一个现有子类)。在实现中,您需要重写一些回调方法,以处理服务生命周期的某些关键方面并提供一种机制将组件绑定到服务(如适用)。

应重写的最重要的回调方法包括:</p>

<dl>
  <dt>{@link android.app.Service#onStartCommand onStartCommand()}</dt>
    <dd>当另一个组件(如 Activity)通过调用
{@link android.content.Context#startService
startService()} 请求启动服务时,系统将调用此方法。一旦执行此方法,服务即会启动并可在后台无限期运行。
如果您实现此方法,则在服务工作完成后,需要由您通过调用
{@link android.app.Service#stopSelf stopSelf()} 或 {@link
android.content.Context#stopService stopService()} 来停止服务。(如果您只想提供绑定,则无需实现此方法。)
</dd>
  <dt>{@link android.app.Service#onBind onBind()}</dt>
    <dd>当另一个组件想通过调用 {@link android.content.Context#bindService
bindService()}
与服务绑定(例如执行 RPC)时,系统将调用此方法。在此方法的实现中,您必须通过返回
{@link android.os.IBinder} 提供一个接口,供客户端用来与服务进行通信。请务必实现此方法,但如果您并不希望允许绑定,则应返回 null。
</dd>
  <dt>{@link android.app.Service#onCreate()}</dt>
    <dd>首次创建服务时,系统将调用此方法来执行一次性设置程序(在调用
{@link android.app.Service#onStartCommand onStartCommand()} 或
{@link android.app.Service#onBind onBind()} 之前)。如果服务已在运行,则不会调用此方法。
</dd>
  <dt>{@link android.app.Service#onDestroy()}</dt>
    <dd>当服务不再使用且将被销毁时,系统将调用此方法。服务应该实现此方法来清理所有资源,如线程、注册的侦听器、接收器等。

这是服务接收的最后一个调用。</dd>
</dl>

<p>如果组件通过调用 {@link
android.content.Context#startService startService()} 启动服务(这会导致对 {@link
android.app.Service#onStartCommand onStartCommand()} 的调用),则服务将一直运行,直到服务使用
{@link android.app.Service#stopSelf()}
自行停止运行,或由其他组件通过调用 {@link android.content.Context#stopService stopService()} 停止它为止。</p>

<p>如果组件是通过调用
{@link android.content.Context#bindService bindService()} 来创建服务(且<em>未</em>调用
{@link
android.app.Service#onStartCommand onStartCommand()}),则服务只会在该组件与其绑定时运行。一旦该服务与所有客户端之间的绑定全部取消,系统便会销毁它。
</p>

<p>仅当内存过低且必须回收系统资源以供具有用户焦点的 Activity 使用时,Android
系统才会强制停止服务。如果将服务绑定到具有用户焦点的 Activity,则它不太可能会终止;如果将服务声明为<a href="#Foreground">在前台运行</a>(稍后讨论),则它几乎永远不会终止。或者,如果服务已启动并要长时间运行,则系统会随着时间的推移降低服务在后台任务列表中的位置,而服务也将随之变得非常容易被终止;如果服务是启动服务,则您必须将其设计为能够妥善处理系统对它的重启。




如果系统终止服务,那么一旦资源变得再次可用,系统便会重启服务(不过这还取决于从
{@link
android.app.Service#onStartCommand onStartCommand()} 返回的值,本文稍后会对此加以讨论)。如需了解有关系统会在何时销毁服务的详细信息,请参阅<a href="{@docRoot}guide/components/processes-and-threads.html">进程和线程</a>文档。

</p>

<p>在下文中,您将了解如何创建各类服务以及如何从其他应用组件使用服务。
</p>



<h3 id="Declaring">使用清单文件声明服务</h3>

<p>如同 Activity(以及其他组件)一样,您必须在应用的清单文件中声明所有服务。
</p>

<p>要声明服务,请添加 <a href="{@docRoot}guide/topics/manifest/service-element.html">{@code &lt;service&gt;}</a>
元素作为 <a href="{@docRoot}guide/topics/manifest/application-element.html">{@code &lt;application&gt;}</a>
元素的子元素。例如:</p>

<pre>
&lt;manifest ... &gt;
  ...
  &lt;application ... &gt;
      &lt;service android:name=".ExampleService" /&gt;
      ...
  &lt;/application&gt;
&lt;/manifest&gt;
</pre>

<p>如需了解有关使用清单文件声明服务的详细信息,请参阅
<a href="{@docRoot}guide/topics/manifest/service-element.html">{@code &lt;service&gt;}</a> 元素参考文档。</p>

<p>您还可将其他属性包括在
<a href="{@docRoot}guide/topics/manifest/service-element.html">{@code &lt;service&gt;}</a>
元素中,以定义一些特性,如启动服务及其运行所在进程所需的权限。<a href="{@docRoot}guide/topics/manifest/service-element.html#nm">{@code android:name}</a>
属性是唯一必需的属性,用于指定服务的类名。应用一旦发布,即不应更改此类名,如若不然,可能会存在因依赖显式 Intent 启动或绑定服务而破坏代码的风险(请阅读博客文章<a href="http://android-developers.blogspot.com/2011/06/things-that-cannot-change.html">Things That Cannot Change</a>[不能更改的内容])。




<p>为了确保应用的安全性,<strong>请始终使用显式 Intent 启动或绑定 {@link android.app.Service}</strong>,且不要为服务声明 Intent 过滤器。
启动哪个服务存在一定的不确定性,而如果对这种不确定性的考量非常有必要,则可为服务提供 Intent 过滤器并从
{@link
android.content.Intent}
中排除相应的组件名称,但随后必须使用 {@link
android.content.Intent#setPackage setPackage()}
 方法设置 Intent 的软件包,这样可以充分消除目标服务的不确定性。</p>

<p>此外,还可以通过添加
<a href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code android:exported}</a>
属性并将其设置为 {@code "false"},确保服务仅适用于您的应用。这可以有效阻止其他应用启动您的服务,即便在使用显式 Intent 时也如此。
</p>




<h2 id="CreatingStartedService">创建启动服务</h2>

<p>启动服务由另一个组件通过调用 {@link
android.content.Context#startService startService()} 启动,这会导致调用服务的
{@link android.app.Service#onStartCommand onStartCommand()} 方法。</p>

<p>服务启动之后,其生命周期即独立于启动它的组件,并且可以在后台无限期地运行,即使启动服务的组件已被销毁也不受影响。

因此,服务应通过调用
{@link android.app.Service#stopSelf stopSelf()} 结束工作来自行停止运行,或者由另一个组件通过调用
{@link android.content.Context#stopService stopService()} 来停止它。</p>

<p>应用组件(如 Activity)可以通过调用 {@link
android.content.Context#startService startService()} 方法并传递 {@link android.content.Intent} 对象
(指定服务并包含待使用服务的所有数据)来启动服务。服务通过
{@link android.app.Service#onStartCommand
onStartCommand()} 方法接收此 {@link android.content.Intent}。</p>

<p>例如,假设某 Activity 需要将一些数据保存到在线数据库中。该 Activity 可以启动一个协同服务,并通过向
{@link
android.content.Context#startService startService()} 传递一个 Intent,为该服务提供要保存的数据。服务通过
{@link
android.app.Service#onStartCommand onStartCommand()} 接收 Intent,连接到 Internet 并执行数据库事务。事务完成之后,服务会自行停止运行并随即被销毁。
</p>

<p class="caution"><strong>注意:</strong>默认情况下,服务与服务声明所在的应用运行于同一进程,而且运行于该应用的主线程中。
因此,如果服务在用户与来自同一应用的 Activity 进行交互时执行密集型或阻止性操作,则会降低 Activity 性能。

为了避免影响应用性能,您应在服务内启动新线程。
</p>

<p>从传统上讲,您可以扩展两个类来创建启动服务:</p>
<dl>
  <dt>{@link android.app.Service}</dt>
  <dd>这是适用于所有服务的基类。扩展此类时,必须创建一个用于执行所有服务工作的新线程,因为默认情况下,服务将使用应用的主线程,这会降低应用正在运行的所有 Activity 的性能。


</dd>
  <dt>{@link android.app.IntentService}</dt>
  <dd>这是
{@link android.app.Service} 的子类,它使用工作线程逐一处理所有启动请求。如果您不要求服务同时处理多个请求,这是最好的选择。
您只需实现 {@link
android.app.IntentService#onHandleIntent onHandleIntent()}
方法即可,该方法会接收每个启动请求的 Intent,使您能够执行后台工作。</dd>
</dl>

<p>下文介绍如何使用其中任一类实现服务。
</p>


<h3 id="ExtendingIntentService">扩展 IntentService 类</h3>

<p>由于大多数启动服务都不必同时处理多个请求(实际上,这种多线程情况可能很危险),因此使用
{@link android.app.IntentService}
类实现服务也许是最好的选择。</p>

<p>{@link android.app.IntentService} 执行以下操作:</p>

<ul>
  <li>创建默认的工作线程,用于在应用的主线程外执行传递给 {@link
android.app.Service#onStartCommand onStartCommand()}
的所有 Intent。</li>
  <li>创建工作队列,用于将一个 Intent 逐一传递给 {@link
android.app.IntentService#onHandleIntent onHandleIntent()}
实现,这样您就永远不必担心多线程问题。</li>
  <li>在处理完所有启动请求后停止服务,因此您永远不必调用
{@link android.app.Service#stopSelf}。</li>
  <li>提供
{@link android.app.IntentService#onBind onBind()} 的默认实现(返回 null)。</li>
  <li>提供 {@link android.app.IntentService#onStartCommand
onStartCommand()} 的默认实现,可将 Intent 依次发送到工作队列和 {@link
android.app.IntentService#onHandleIntent onHandleIntent()} 实现。</li>
</ul>

<p>综上所述,您只需实现
{@link
android.app.IntentService#onHandleIntent onHandleIntent()} 来完成客户端提供的工作即可。(不过,您还需要为服务提供小型构造函数。)</p>

<p>以下是 {@link android.app.IntentService} 的实现示例:</p>

<pre>
public class HelloIntentService extends IntentService {

  /**
   * A constructor is required, and must call the super {@link android.app.IntentService#IntentService}
   * constructor with a name for the worker thread.
   */
  public HelloIntentService() {
      super("HelloIntentService");
  }

  /**
   * The IntentService calls this method from the default worker thread with
   * the intent that started the service. When this method returns, IntentService
   * stops the service, as appropriate.
   */
  &#64;Override
  protected void onHandleIntent(Intent intent) {
      // Normally we would do some work here, like download a file.
      // For our sample, we just sleep for 5 seconds.
      long endTime = System.currentTimeMillis() + 5*1000;
      while (System.currentTimeMillis() &lt; endTime) {
          synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              } catch (Exception e) {
              }
          }
      }
  }
}
</pre>

<p>您只需要一个构造函数和一个 {@link
android.app.IntentService#onHandleIntent onHandleIntent()} 实现即可。</p>

<p>如果您决定还重写其他回调方法(如 {@link
android.app.IntentService#onCreate onCreate()}、{@link
android.app.IntentService#onStartCommand onStartCommand()} 或 {@link
android.app.IntentService#onDestroy onDestroy()}),请确保调用超类实现,以便
{@link android.app.IntentService} 能够妥善处理工作线程的生命周期。</p>

<p>例如,{@link android.app.IntentService#onStartCommand onStartCommand()}
必须返回默认实现(即,如何将 Intent 传递给 {@link
android.app.IntentService#onHandleIntent onHandleIntent()}):</p>

<pre>
&#64;Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    return super.onStartCommand(intent,flags,startId);
}
</pre>

<p>除
{@link android.app.IntentService#onHandleIntent onHandleIntent()} 之外,您无需从中调用超类的唯一方法就是 {@link android.app.IntentService#onBind
onBind()}(仅当服务允许绑定时,才需要实现该方法)。</p>

<p>在下一部分中,您将了解如何在扩展
{@link android.app.Service}
基类时实现同类服务。该基类包含更多代码,但如需同时处理多个启动请求,则更适合使用该基类。</p>


<h3 id="ExtendingService">扩展服务类</h3>

<p>正如上一部分中所述,使用
{@link android.app.IntentService} 显著简化了启动服务的实现。但是,若要求服务执行多线程(而不是通过工作队列处理启动请求),则可扩展
{@link android.app.Service}
类来处理每个 Intent。</p>

<p>为了便于比较,以下提供了 {@link
android.app.Service} 类实现的代码示例,该类执行的工作与上述使用 {@link
android.app.IntentService} 的示例完全相同。也就是说,对于每个启动请求,它均使用工作线程执行作业,且每次仅处理一个请求。
</p>

<pre>
public class HelloService extends Service {
  private Looper mServiceLooper;
  private ServiceHandler mServiceHandler;

  // Handler that receives messages from the thread
  private final class ServiceHandler extends Handler {
      public ServiceHandler(Looper looper) {
          super(looper);
      }
      &#64;Override
      public void handleMessage(Message msg) {
          // Normally we would do some work here, like download a file.
          // For our sample, we just sleep for 5 seconds.
          long endTime = System.currentTimeMillis() + 5*1000;
          while (System.currentTimeMillis() &lt; endTime) {
              synchronized (this) {
                  try {
                      wait(endTime - System.currentTimeMillis());
                  } catch (Exception e) {
                  }
              }
          }
          // Stop the service using the startId, so that we don't stop
          // the service in the middle of handling another job
          stopSelf(msg.arg1);
      }
  }

  &#64;Override
  public void onCreate() {
    // Start up the thread running the service.  Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block.  We also make it
    // background priority so CPU-intensive work will not disrupt our UI.
    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
  }

  &#64;Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

      // For each start request, send a message to start a job and deliver the
      // start ID so we know which request we're stopping when we finish the job
      Message msg = mServiceHandler.obtainMessage();
      msg.arg1 = startId;
      mServiceHandler.sendMessage(msg);

      // If we get killed, after returning from here, restart
      return START_STICKY;
  }

  &#64;Override
  public IBinder onBind(Intent intent) {
      // We don't provide binding, so return null
      return null;
  }

  &#64;Override
  public void onDestroy() {
    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
  }
}
</pre>

<p>正如您所见,与使用 {@link android.app.IntentService} 相比,这需要执行更多工作。</p>

<p>但是,因为是由您自己处理对 {@link android.app.Service#onStartCommand
onStartCommand()} 的每个调用,因此可以同时执行多个请求。此示例并未这样做,但如果您希望如此,则可为每个请求创建一个新线程,然后立即运行这些线程(而不是等待上一个请求完成)。

</p>

<p>请注意,{@link android.app.Service#onStartCommand onStartCommand()}
方法必须返回整型数。整型数是一个值,用于描述系统应该如何在服务终止的情况下继续运行服务(如上所述,{@link
android.app.IntentService}
的默认实现将为您处理这种情况,不过您可以对其进行修改)。从
{@link android.app.Service#onStartCommand onStartCommand()}
返回的值必须是以下常量之一:</p>

<dl>
  <dt>{@link android.app.Service#START_NOT_STICKY}</dt>
    <dd>如果系统在
{@link android.app.Service#onStartCommand
onStartCommand()} 返回后终止服务,则除非有挂起 Intent 要传递,否则系统不会重建服务。<em></em>这是最安全的选项,可以避免在不必要时以及应用能够轻松重启所有未完成的作业时运行服务。
</dd>
  <dt>{@link android.app.Service#START_STICKY}</dt>
    <dd>如果系统在
{@link android.app.Service#onStartCommand
onStartCommand()} 返回后终止服务,则会重建服务并调用
{@link
android.app.Service#onStartCommand onStartCommand()},但绝对不会重新传递最后一个 Intent。相反,除非有挂起 Intent 要启动服务(在这种情况下,将传递这些 Intent ),否则系统会通过空 Intent 调用
{@link android.app.Service#onStartCommand onStartCommand()}。<em></em>这适用于不执行命令、但无限期运行并等待作业的媒体播放器(或类似服务)。
</dd>
  <dt>{@link android.app.Service#START_REDELIVER_INTENT}</dt>
    <dd>如果系统在 {@link android.app.Service#onStartCommand
onStartCommand()} 返回后终止服务,则会重建服务,并通过传递给服务的最后一个 Intent 调用
{@link
android.app.Service#onStartCommand onStartCommand()}。任何挂起 Intent 均依次传递。这适用于主动执行应该立即恢复的作业(例如下载文件)的服务。
</dd>
</dl>
<p>有关这些返回值的更多详细信息,请查阅每个常量链接的参考文档。
</p>



<h3 id="StartingAService">启动服务</h3>

<p>您可以通过将
{@link android.content.Intent}(指定要启动的服务)传递给 {@link
android.content.Context#startService startService()},从 Activity 或其他应用组件启动服务。Android 系统调用服务的 {@link
android.app.Service#onStartCommand onStartCommand()} 方法,并向其传递 {@link
android.content.Intent}。(切勿直接调用 {@link android.app.Service#onStartCommand
onStartCommand()}。)</p>

<p>例如,Activity 可以结合使用显式 Intent 与 {@link android.content.Context#startService
startService()},启动上文中的示例服务 ({@code
HelloSevice}):</p>

<pre>
Intent intent = new Intent(this, HelloService.class);
startService(intent);
</pre>

<p>{@link android.content.Context#startService startService()} 方法将立即返回,且
Android 系统调用服务的 {@link android.app.Service#onStartCommand
onStartCommand()} 方法。如果服务尚未运行,则系统会先调用 {@link
android.app.Service#onCreate onCreate()},然后再调用 {@link android.app.Service#onStartCommand
onStartCommand()}。</p>

<p>如果服务亦未提供绑定,则使用
{@link
android.content.Context#startService startService()} 传递的 Intent 是应用组件与服务之间唯一的通信模式。但是,如果您希望服务返回结果,则启动服务的客户端可以为广播创建一个
{@link android.app.PendingIntent}
(使用 {@link android.app.PendingIntent#getBroadcast getBroadcast()}),并通过启动服务的
{@link android.content.Intent} 传递给服务。然后,服务就可以使用广播传递结果。
</p>

<p>多个服务启动请求会导致多次对服务的
{@link android.app.Service#onStartCommand onStartCommand()} 进行相应的调用。但是,要停止服务,只需一个服务停止请求(使用
{@link android.app.Service#stopSelf stopSelf()} 或 {@link
android.content.Context#stopService stopService()})即可。</p>


<h3 id="Stopping">停止服务</h3>

<p>启动服务必须管理自己的生命周期。也就是说,除非系统必须回收内存资源,否则系统不会停止或销毁服务,而且服务在
{@link android.app.Service#onStartCommand onStartCommand()}
返回后会继续运行。因此,服务必须通过调用
{@link android.app.Service#stopSelf stopSelf()} 自行停止运行,或者由另一个组件通过调用
{@link android.content.Context#stopService stopService()} 来停止它。</p>

<p>一旦请求使用 {@link android.app.Service#stopSelf stopSelf()}
或 {@link
android.content.Context#stopService stopService()} 停止服务,系统就会尽快销毁服务。</p>

<p>但是,如果服务同时处理多个
{@link
android.app.Service#onStartCommand onStartCommand()}
请求,则您不应在处理完一个启动请求之后停止服务,因为您可能已经收到了新的启动请求(在第一个请求结束时停止服务会终止第二个请求)。为了避免这一问题,您可以使用
{@link android.app.Service#stopSelf(int)}
确保服务停止请求始终基于最近的启动请求。也就说,在调用 {@link
android.app.Service#stopSelf(int)} 时,传递与停止请求的 ID 对应的启动请求的 ID(传递给 {@link android.app.Service#onStartCommand onStartCommand()}
的 <code>startId</code>)
。然后,如果在您能够调用 {@link
android.app.Service#stopSelf(int)} 之前服务收到了新的启动请求, ID 就不匹配,服务也就不会停止。</p>

<p class="caution"><strong>注意:</strong>为了避免浪费系统资源和消耗电池电量,应用必须在工作完成之后停止其服务。
如有必要,其他组件可以通过调用
{@link
android.content.Context#stopService stopService()} 来停止服务。即使为服务启用了绑定,一旦服务收到对
{@link
android.app.Service#onStartCommand onStartCommand()} 的调用,您始终仍须亲自停止服务。</p>

<p>如需了解有关服务生命周期的详细信息,请参阅下面有关<a href="#Lifecycle">管理服务生命周期</a>的部分。</p>



<h2 id="CreatingBoundService">创建绑定服务</h2>

<p>绑定服务允许应用组件通过调用 {@link
android.content.Context#bindService bindService()} 与其绑定,以便创建长期连接(通常不允许组件通过调用
{@link
android.content.Context#startService startService()} 来启动它)。<em></em></p>

<p>如需与 Activity 和其他应用组件中的服务进行交互,或者需要通过进程间通信 (IPC) 向其他应用公开某些应用功能,则应创建绑定服务。

</p>

<p>要创建绑定服务,必须实现
{@link
android.app.Service#onBind onBind()} 回调方法以返回 {@link android.os.IBinder},用于定义与服务通信的接口。然后,其他应用组件可以调用
{@link android.content.Context#bindService bindService()}
来检索该接口,并开始对服务调用方法。服务只用于与其绑定的应用组件,因此如果没有组件绑定到服务,则系统会销毁服务(您不必按通过
{@link android.app.Service#onStartCommand onStartCommand()}
启动的服务那样来停止绑定服务)。
<em></em></p>

<p>要创建绑定服务,首先必须定义指定客户端如何与服务通信的接口。
服务与客户端之间的这个接口必须是
{@link android.os.IBinder} 的实现,并且服务必须从
{@link android.app.Service#onBind
onBind()} 回调方法返回它。一旦客户端收到
{@link android.os.IBinder},即可开始通过该接口与服务进行交互。</p>

<p>多个客户端可以同时绑定到服务。客户端完成与服务的交互后,会调用
{@link android.content.Context#unbindService unbindService()} 取消绑定。一旦没有客户端绑定到该服务,系统就会销毁它。
</p>

<p>有多种方法实现绑定服务,其实现比启动服务更为复杂,因此绑定服务将在有关<a href="{@docRoot}guide/components/bound-services.html">绑定服务</a>的单独文档中专门讨论。

</p>



<h2 id="Notifications">向用户发送通知</h2>

<p>一旦运行起来,服务即可使用 <a href="{@docRoot}guide/topics/ui/notifiers/toasts.html">Toast 通知</a>或<a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">状态栏通知</a>来通知用户所发生的事件。</p>

<p>Toast 通知是指出现在当前窗口的表面、片刻随即消失不见的消息,而状态栏通知则在状态栏提供内含消息的图标,用户可以选择该图标来采取操作(例如启动 Activity)。

</p>

<p>通常,当某些后台工作已经完成(例如文件下载完成)且用户现在可以对其进行操作时,状态栏通知是最佳方法。

当用户从展开视图中选定通知时,通知即可启动 Activity(例如查看已下载的文件)。
</p>

<p>如需了解详细信息,请参阅
<a href="{@docRoot}guide/topics/ui/notifiers/toasts.html">Toast 通知</a>或<a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">状态栏通知</a>开发者指南。</p>



<h2 id="Foreground">在前台运行服务</h2>

<p>前台服务被认为是用户主动意识到的一种服务,因此在内存不足时,系统也不会考虑将其终止。
前台服务必须为状态栏提供通知,状态栏位于“正在进行”标题下方,这意味着除非服务停止或从前台删除,否则不能清除通知。


</p>

<p>例如,应该将从服务播放音乐的音乐播放器设置为在前台运行,这是因为用户明确意识到其操作。

状态栏中的通知可能表示正在播放的歌曲,并允许用户启动 Activity 来与音乐播放器进行交互。
</p>

<p>要请求让服务运行于前台,请调用 {@link
android.app.Service#startForeground startForeground()}。此方法取两个参数:唯一标识通知的整型数和状态栏的
{@link
android.app.Notification}。例如:</p>

<pre>
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
</pre>

<p class="caution"><strong>注意:</strong>提供给 {@link
android.app.Service#startForeground startForeground()} 的整型 ID 不得为 0。</p>


<p>要从前台删除服务,请调用
{@link android.app.Service#stopForeground stopForeground()}。此方法取一个布尔值,指示是否也删除状态栏通知。
此方法绝对不会停止服务。
<em></em>但是,如果您在服务正在前台运行时将其停止,则通知也会被删除。
</p>

<p>如需了解有关通知的详细信息,请参阅<a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">创建状态栏通知</a>。
</p>



<h2 id="Lifecycle">管理服务生命周期</h2>

<p>服务的生命周期比 Activity 的生命周期要简单得多。但是,密切关注如何创建和销毁服务反而更加重要,因为服务可以在用户没有意识到的情况下运行于后台。

</p>

<p>服务生命周期(从创建到销毁)可以遵循两条不同的路径:
</p>

<ul>
<li>启动服务
  <p>该服务在其他组件调用 {@link
android.content.Context#startService startService()} 时创建,然后无限期运行,且必须通过调用
{@link
android.app.Service#stopSelf() stopSelf()} 来自行停止运行。此外,其他组件也可以通过调用
{@link android.content.Context#stopService
stopService()} 来停止服务。服务停止后,系统会将其销毁。</p></li>

<li>绑定服务
  <p>该服务在另一个组件(客户端)调用 {@link
android.content.Context#bindService bindService()} 时创建。然后,客户端通过
{@link android.os.IBinder} 接口与服务进行通信。客户端可以通过调用
{@link android.content.Context#unbindService unbindService()} 关闭连接。多个客户端可以绑定到相同服务,而且当所有绑定全部取消后,系统即会销毁该服务。
(服务不必自行停止运行。)
<em></em></p></li>
</ul>

<p>这两条路径并非完全独立。也就是说,您可以绑定到已经使用
{@link android.content.Context#startService startService()} 启动的服务。例如,可以通过使用
{@link android.content.Intent}(标识要播放的音乐)调用 {@link android.content.Context#startService
startService()} 来启动后台音乐服务。随后,可能在用户需要稍加控制播放器或获取有关当前播放歌曲的信息时,Activity 可以通过调用
{@link
android.content.Context#bindService bindService()}
绑定到服务。在这种情况下,除非所有客户端均取消绑定,否则 {@link
android.content.Context#stopService stopService()} 或 {@link android.app.Service#stopSelf
stopSelf()} 不会真正停止服务。 </p>


<h3 id="LifecycleCallbacks">实现生命周期回调</h3>

<p>与 Activity 类似,服务也拥有生命周期回调方法,您可以实现这些方法来监控服务状态的变化并适时执行工作。
以下框架服务展示了每种生命周期方法:
</p>

<pre>
public class ExampleService extends Service {
    int mStartMode;       // indicates how to behave if the service is killed
    IBinder mBinder;      // interface for clients that bind
    boolean mAllowRebind; // indicates whether onRebind should be used

    &#64;Override
    public void {@link android.app.Service#onCreate onCreate}() {
        // The service is being created
    }
    &#64;Override
    public int {@link android.app.Service#onStartCommand onStartCommand}(Intent intent, int flags, int startId) {
        // The service is starting, due to a call to {@link android.content.Context#startService startService()}
        return <em>mStartMode</em>;
    }
    &#64;Override
    public IBinder {@link android.app.Service#onBind onBind}(Intent intent) {
        // A client is binding to the service with {@link android.content.Context#bindService bindService()}
        return <em>mBinder</em>;
    }
    &#64;Override
    public boolean {@link android.app.Service#onUnbind onUnbind}(Intent intent) {
        // All clients have unbound with {@link android.content.Context#unbindService unbindService()}
        return <em>mAllowRebind</em>;
    }
    &#64;Override
    public void {@link android.app.Service#onRebind onRebind}(Intent intent) {
        // A client is binding to the service with {@link android.content.Context#bindService bindService()},
        // after onUnbind() has already been called
    }
    &#64;Override
    public void {@link android.app.Service#onDestroy onDestroy}() {
        // The service is no longer used and is being destroyed
    }
}
</pre>

<p class="note"><strong>注:</strong>与 Activity 生命周期回调方法不同,您不需要调用这些回调方法的超类实现。
<em></em></p>

<img src="{@docRoot}images/service_lifecycle.png" alt="" />
<p class="img-caption"><strong>图 2. </strong>服务生命周期左图显示了使用
{@link android.content.Context#startService
startService()} 所创建的服务的生命周期,右图显示了使用
{@link android.content.Context#bindService bindService()} 所创建的服务的生命周期。</p>

<p>通过实现这些方法,您可以监控服务生命周期的两个嵌套循环: </p>

<ul>
<li>服务的<strong>整个生命周期</strong>从调用 {@link
android.app.Service#onCreate onCreate()} 开始起,到 {@link
android.app.Service#onDestroy} 返回时结束。与 Activity 类似,服务也在
{@link android.app.Service#onCreate onCreate()} 中完成初始设置,并在 {@link
android.app.Service#onDestroy onDestroy()} 中释放所有剩余资源。例如,音乐播放服务可以在 {@link
android.app.Service#onCreate onCreate()} 中创建用于播放音乐的线程,然后在 {@link
android.app.Service#onDestroy onDestroy()} 中停止该线程。


<p>无论服务是通过 {@link android.content.Context#startService startService()}
还是 {@link
android.content.Context#bindService bindService()} 创建,都会为所有服务调用 {@link android.app.Service#onCreate onCreate()} 和 {@link android.app.Service#onDestroy
onDestroy()} 方法。</p></li>

<li>服务的<strong>有效生命周期</strong>从调用 {@link
android.app.Service#onStartCommand onStartCommand()} 或 {@link android.app.Service#onBind onBind()}
方法开始。每种方法均有 {@link
android.content.Intent} 对象,该对象分别传递到 {@link android.content.Context#startService
startService()} 或 {@link android.content.Context#bindService bindService()}。
<p>对于启动服务,有效生命周期与整个生命周期同时结束(即便是在
{@link android.app.Service#onStartCommand
onStartCommand()} 返回之后,服务仍然处于活动状态)。对于绑定服务,有效生命周期在 {@link
android.app.Service#onUnbind onUnbind()} 返回时结束。</p>
</li>
</ul>

<p class="note"><strong>注:</strong>尽管启动服务是通过调用
{@link android.app.Service#stopSelf stopSelf()} 或 {@link
android.content.Context#stopService stopService()} 来停止,但是该服务并无相应的回调(没有 {@code onStop()}
回调)。因此,除非服务绑定到客户端,否则在服务停止时,系统会将其销毁&mdash;{@link
android.app.Service#onDestroy onDestroy()} 是接收到的唯一回调。
</p>

<p>图 2 说明了服务的典型回调方法。尽管该图分开介绍通过
{@link android.content.Context#startService startService()} 创建的服务和通过
{@link android.content.Context#bindService bindService()}
创建的服务,但是请记住,不管启动方式如何,任何服务均有可能允许客户端与其绑定。因此,最初使用
{@link android.app.Service#onStartCommand
onStartCommand()}(通过客户端调用 {@link android.content.Context#startService startService()})启动的服务仍可接收对
{@link android.app.Service#onBind onBind()} 的调用(当客户端调用
{@link android.content.Context#bindService bindService()} 时)。</p>

<p>如需了解有关创建提供绑定的服务的详细信息,请参阅<a href="{@docRoot}guide/components/bound-services.html">绑定服务</a>文档,该文档的<a href="{@docRoot}guide/components/bound-services.html#Lifecycle">管理绑定服务的生命周期</a>部分提供了有关
{@link android.app.Service#onRebind onRebind()}
回调方法的更多信息。
</p>


<!--
<h2>Beginner's Path</h2>

<p>To learn how to query data from the system or other applications (such as contacts or media
stored on the device), continue with the <b><a
href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a></b>
document.</p>
-->