A Service
is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
服务是一个可以执行长时间后台操作并且不提供用户接口的应用组件。其他的应用组件可以开启一个服务并且它将在用户跳到另一个应用时继续后台运行。此外,一个组件可以与一个服务进行绑定来与它进行交互甚至进行进程间通信(IPC)。例如,一个服务可能在后台处理网络传输,播放音乐,执行文件I/O,或者与内容提供者进行交互。
A service can essentially take two forms:
Started:
A service is "started" when an application component (such as an activity) starts it by callingstartService()
. Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.
Bound:
A service is "bound" when an application component binds to it by calling bindService()
. A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.
一个服务基本有两种形式:
开始:一个应用组件(例如一个activity)通过调用startSsevice()方法来开始一个服务。一旦开始了,服务就能够独立地后台运行,即使开启它的组件已经被摧毁。通常,一个开始的服务执行一个单一的操作并且不会给调用者返回一个结果。例如,它可能下载或者上传一个文件通过网络。当操作完成,这个服务应该结束它自己。
Bound: 一个应用组件通过调用bindService()方法来“绑定”一个服务。一个绑定了的服务提供一个允许组件与服务交互,发送请求,GET结果,甚至跨进程通信的主从式接口。一个“绑定”的服务运行仅当另一个应用组件与它绑定。大多数组件可以同时与服务进行绑定,但是当所有解绑时,这个服务被摧毁。
Although this documentation generally discusses these two types of services separately, your service can work both ways—it can be started (to run indefinitely) and also allow binding. It's simply a matter of whether you implement a couple callback methods: onStartCommand()
to allow components to start it and onBind()
to allow binding.
虽然这个文档分开讨论这两种类型的服务,但你的服务可以工作在这两种方式——它可以被开始(无限期的?运行)并且也允许绑定。这仅仅取决与你是否实施了一个联合回调方法:onStartCommand()来允许组件开始它以及一个onBind()方法来允许绑定。
Regardless of whether your application is started, bound, or both, any application component can use the service (even from a separate application), in the same way that any component can use an activity—by starting it with an Intent
. However, you can declare the service as private, in the manifest file, and block access from other applications. This is discussed more in the section aboutDeclaring the service in the manifest.
不管你的应用是否被开始,绑定,或者两者都有,任何应用组件可以使用这个服务(即使是一个外来的应用),同样地任何组件可以启用一个activity -通过一个意图。但是你可以在manifest文件中声明服务为私有的,并且禁止其他应用访问。更多关于它的讨论请参阅Declaring the service in the manifest。
Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.
警告:服务运行在它宿主进程的主线程下——服务并不会创造它自己的线程,而且不会运行在一个外部进程中(除非你指定了其他的)。这就意味着,当你的服务正在进行任何CPU集中型工作或者阻塞式操作时(例如播放MP3或者网络进程),你应该为服务创造一个新的线程来做那个工作。通过用其他线程,你可以减少ANR错误的风险并且应用的主线程可以专注与用户交互。
Should you use a service or a thread?
A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need.
If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate()
, start running it in onStart()
, then stop it in onStop()
. Also consider using AsyncTask
orHandlerThread
, instead of the traditional Thread
class. See the Processes and Threadingdocument for more information about threads.
Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.
你应该使用一个服务还是一个线程?
简单来说,服务只是一个运行在后台的组件,即使用户并没有与你的APP进行交互。因此,你应该创建一个服务仅当你需要的时候。
如果你需要进行一些你主进程之外的工作,但是仅当用户与你的APP进行交互的时候,这时候你你应该创建一个新的进程而不是一个服务。例如,如果你想在你的activity运行的时候播放一些音乐,你可以创建一个进程用onCreate(),用onStart()开始运行它,然后用onStop()停止它。也可以考虑用AsyncTask或者HandlerTherad,代替传统的Therad类。 查阅Processes and Threading文档来获取更多的关于进程的信息。
记住如果你确实用了一个服务,那么它还是会默认的运行在你的APP主进程中,因此如果它用进行一些高强度的或者阻塞式的操作时,记得仍然要为它创建一个新的进程。
The Basics
To create a service, you must create a subclass ofService
(or one of its existing subclasses). In your implementation, you need to override some callback methods that handle key aspects of the service lifecycle and provide a mechanism for components to bind to the service, if appropriate. The most important callback methods you should override are:
基本要素:
要创建一个服务,你必须创建一个Service的子类(或者它的存在的子类)。在你的实例中,你需要复写一些处理服务生命周期关键特性并且为组件提供绑定到服务的功能(如果有的话)的回调方法。一些你需要复写的回调方式包括:
onStartCommand()
The system calls this method when another component, such as an activity, requests that the service be started, by calling startService()
. Once this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is done, by calling stopSelf()
orstopService()
. (If you only want to provide binding, you don't need to implement this method.)
当另一个组件,例如一个activity,通过调用startService()要求启用服务时,系统调用这个方法。一旦执行了这个方法,服务就会在后台无限期的运行下去。如果你执行了这一步,那么你就有责任停止它当它的工作完成的时候,通过调用stopSelf()
orstopService().(如果你仅仅想提供绑定,那么你不需要执行这个方法。)
onBind()
The system calls this method when another component wants to bind with the service (such as to perform RPC), by calling
bindService()
. In your implementation of this method, you must provide an interface that clients use to communicate with the service, by returning an
IBinder
. You must always implement this method, but if you don't want to allow binding, then you should return null.
当另一个组件通过调用bindService()想与服务进行绑定时,系统会调用这个方法。在你的方法实例中,你必须提供一个客户接口用来与服务进行通信,通过返回一个IBinder。你必须实施这个方法,除非你不想运行绑定,那么你应该返回null。
onCreate()
The system calls this method when the service is first created, to perform one-time setup procedures (before it calls either
onStartCommand()
or
onBind()
). If the service is already running, this method is not called.
onDestroy()
The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc. This is the last call the service receives.
onCreate()
当服务第一次创建时,系统调用这个方法来进行一次性设置程序(在调用onStartCommand()
or onBind()之前
)。如果服务已经在运行,那么这个方法不会被调用。
onDestroy() 当服务不再使用正在被摧毁时,系统调用这个方法。你的服务应该通过它来清除一些资源,例如进程,监听器,接收器等等。这个是服务接受的最好一个方法。
If a component starts the service by calling startService()
(which results in a call toonStartCommand()
), then the service remains running until it stops itself with stopSelf()
or another component stops it by calling stopService()
.
If a component calls bindService()
to create the service (and onStartCommand()
is not called), then the service runs only as long as the component is bound to it. Once the service is unbound from all clients, the system destroys it.
The Android system will force-stop a service only when memory is low and it must recover system resources for the activity that has user focus. If the service is bound to an activity that has user focus, then it's less likely to be killed, and if the service is declared to run in the foreground(discussed later), then it will almost never be killed. Otherwise, if the service was started and is long-running, then the system will lower its position in the list of background tasks over time and the service will become highly susceptible to killing—if your service is started, then you must design it to gracefully handle restarts by the system. If the system kills your service, it restarts it as soon as resources become available again (though this also depends on the value you return from onStartCommand()
, as discussed later). For more information about when the system might destroy a service, see the Processes and Threading document.
如果一个组件通过调用startService()方法开启一个服务(这将导致调用onStartCommand()),那么这个服务将持续运行直到它通过stopSelf()
停止自己或者其他组件通过stopService()方法停止它。
如果一个组件通过调用bindService() 方法开启一个服务(并且onStartCommand()没有被调用),那么这个服务只在组件与它绑定的时候运行。一旦这个服务与所有客户?都没有绑定,系统将会摧毁它。
系统仅在内存太少并且必须要释放系统资源给用户关注的活动时才会去暴力停止一个服务。如果一个服务与一个用户关注的活动绑定时,那么它将很少被摧毁,而且如果服务被声明run in the foreground,那么它将几乎从不会被摧毁。否则,如果一个服务被开启并且吃长时间运行,那么系统之后系统将会降低它在后台任务表中的位置而且这个服务也将具有更高的被摧毁的可能性——如果你的服务开启了,那么你必须设计好它将怎样被系统重新启动。如果系统杀死了你的服务,它将会重新启动只要资源再次充足(尽管这也取决于onStartCommand()的返回值)。关于什么时候系统可能摧毁一个服务,查阅Processes and Threading 文档。
In the following sections, you'll see how you can create each type of service and how to use it from other application components.
下面几节,你将看到怎么样创建每种类型的服务以及怎样从应用组件中使用它。
Declaring a service in the manifest 在manifest中声明一个服务
Like activities (and other components), you must declare all services in your application's manifest file.To declare your service, add a <service>
element as a child of the <application>
element. For example:
就像活动以及其他组件一样,你必须声明所有的服务在你的应用mainfest文件中。要声明你的服务,添加一个<service>条目作为
<application>条目的子条目。例如:
<pre class="prettyprint" style="font-size: 13px; margin-top: 0px; margin-bottom: 1em; color: rgb(0, 102, 0); font-stretch: normal; line-height: 18px; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; -webkit-font-smoothing: subpixel-antialiased; padding: 1em; overflow: auto; border: 1px solid rgb(221, 221, 221); background: rgb(247, 247, 247);"><span class="tag" style="color: rgb(0, 0, 136);"><manifest</span><span class="pln" style="color: rgb(0, 0, 0);"> ... </span><span class="tag" style="color: rgb(0, 0, 136);">></span><span class="pln" style="color: rgb(0, 0, 0);">
...
</span><span class="tag" style="color: rgb(0, 0, 136);"><application</span><span class="pln" style="color: rgb(0, 0, 0);"> ... </span><span class="tag" style="color: rgb(0, 0, 136);">></span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="tag" style="color: rgb(0, 0, 136);"><service</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="atn" style="color: rgb(136, 34, 136);">android:name</span><span class="pun" style="color: rgb(102, 102, 0);">=</span><span class="atv" style="color: rgb(136, 0, 0);">".ExampleService"</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="tag" style="color: rgb(0, 0, 136);">/></span><span class="pln" style="color: rgb(0, 0, 0);">
...
</span><span class="tag" style="color: rgb(0, 0, 136);"></application></span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="tag" style="color: rgb(0, 0, 136);"></manifest></span>
There are other attributes you can include in the <service>
element to define properties such as permissions required to start the service and the process in which the service should run. Theandroid:name
attribute is the only required attribute—it specifies the class name of the service. Once you publish your application, you should not change this name, because if you do, you risk breaking code due to dependence on explicit intents to start or bind the service (read the blog post, Things That Cannot Change).
To ensure your app is secure, always use an explicit intent when starting or binding yourService
and do not declare intent filters for the service. If it's critical that you allow for some amount of ambiguity as to which service starts, you can supply intent filters for your services and exclude the component name from the Intent
, but you then must set the package for the intent with setPackage()
, which provides sufficient disambiguation for the target service.
有很多其他的属性你可以包括在<services>条目中来定义属性例如开启服务的权限请求以及服务应该运行在哪个进程。android:name属性仅仅是被要求的属性——它指定了服务的类名。一旦你发布了你的应用,你就不应该再改变这个名字,因为如果你这么做了,你正在冒着破坏代码的风险,由于开启或者绑定服务的明确意图的关系。
为了保证你的应用的安全性,总是用一个明确的意图来启动或者绑定你的服务而且不要为你的服务声明意图过滤器。如果允许服务执行一些模棱两可的操作是必须的话,那么你可以为你的服务提供意图过滤器并从意图中排除组件的名字,但是之后你必须利用setPackage()为意图设置包名,其目的是为目标服务提供足够的消岐。
Additionally, you can ensure that your service is available to only your app by including the
android:exported
attribute and setting it to "false"
. This effectively stops other apps from starting your service, even when using an explicit intent.
此外,你可以通过包含一个
android:exported属性并且设置它为“false”来确保你的服务仅适用于你的应用。这有效地阻止其他应用启动你的服务,即使它用了一个明确的意图。
Creating a Started Service 创建一个开始服务
A started service is one that another component starts by calling startService()
, resulting in a call to the service's onStartCommand()
method.
When a service is started, it has a lifecycle that's independent of the component that started it and the service can run in the background indefinitely, even if the component that started it is destroyed. As such, the service should stop itself when its job is done by calling stopSelf()
, or another component can stop it by calling stopService()
.
An application component such as an activity can start the service by calling startService()
and passing an Intent
that specifiesthe service and includes any data for the service to use. The service receives this Intent
in the onStartCommand()
method.
startService()
. The service receives the intent in
onStartCommand()
, connects to the Internet and performs the database transaction. When the transaction is done, the service stops itself and it is destroyed.
Traditionally, there are two classes you can extend to create a started service:
- This is the base class for all services. When you extend this class, it's important that you create a new thread in which to do all the service's work, because the service uses your application's main thread, by default, which could slow the performance of any activity your application is running.
-
This is a subclass of
Service
that uses a worker thread to handle all start requests, one at a time. This is the best option if you don't require that your service handle multiple requests simultaneously. All you need to do is implementonHandleIntent()
, which receives the intent for each start request so you can do the background work.
Service
IntentService
Extending the IntentService class
Because most started services don't need to handle multiple requests simultaneously (which can actually be a dangerous multi-threading scenario), it's probably best if you implement your service using the IntentService
class.
The IntentService
does the following:
- Creates a default worker thread that executes all intents delivered to
onStartCommand()
separate from your application's main thread. - Creates a work queue that passes one intent at a time to your
onHandleIntent()
implementation, so you never have to worry about multi-threading. - Stops the service after all start requests have been handled, so you never have to call
stopSelf()
. - Provides default implementation of
onBind()
that returns null. - Provides a default implementation of
onStartCommand()
that sends the intent to the work queue and then to youronHandleIntent()
implementation.
All this adds up to the fact that all you need to do is implement onHandleIntent()
to do the work provided by the client. (Though, you also need to provide a small constructor for the service.)
Here's an example implementation of IntentService
:
由于大多数的初始服务不需要同时地处理多个请求(那可能是一个危险的多线程想法),因此如果你实现你的服务用IntentService类可能是一个最好的选择。IntentService一般做以下几个事情:
1、创建一个可以执行从你的应用主线程中分离出来的被传递给onStartCommand()的所有意图的工作线程。
2、创建一个每次只传送一个意图到你的onHandleIntent()中的工作队列,因此你永远不必担心出现多线程的情况。
3、当所有的初始请求被处理完之后停止服务,因此你不必调用stopSelf()方法。
4、提供一个返回空值的onBind()方法的示例。
5、提供一个onStartCommand()方法的默认实例,它可以发送意图到工作队列然后发送到你的onHandleIntent()实例。
总的来说上面说得意思就是你需要做的就是实现onHandleIntent()方法来处理客户提供的工作。(虽然,你也需要为服务提供一个小的构造函数。)
下面是一个实现IntentService的例子:
<pre class="prettyprint" style="font-size: 13px; margin-top: 0px; margin-bottom: 1em; color: rgb(0, 102, 0); font-stretch: normal; line-height: 18px; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; -webkit-font-smoothing: subpixel-antialiased; padding: 1em; overflow: auto; border: 1px solid rgb(221, 221, 221); background: rgb(247, 247, 247);"><span class="kwd" style="color: rgb(0, 0, 136);">public</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="kwd" style="color: rgb(0, 0, 136);">class</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="typ" style="color: rgb(102, 0, 102);">HelloIntentService</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="kwd" style="color: rgb(0, 0, 136);">extends</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="typ" style="color: rgb(102, 0, 102);">IntentService</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="pun" style="color: rgb(102, 102, 0);">{</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="com">/**
* A constructor is required, and must call the super </span><code style="font-stretch: normal; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; -webkit-font-smoothing: subpixel-antialiased; padding: 3px 5px;"><a target=_blank href="http://android.xsoftlab.net/reference/android/app/IntentService.html#IntentService(java.lang.String)" style="color: rgb(3, 155, 229); text-decoration: none;"><span class="com">IntentService(String)</span></a></code><span class="com">
* constructor with a name for the worker thread.
*/</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="kwd" style="color: rgb(0, 0, 136);">public</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="typ" style="color: rgb(102, 0, 102);">HelloIntentService</span><span class="pun" style="color: rgb(102, 102, 0);">()</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="pun" style="color: rgb(102, 102, 0);">{</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="kwd" style="color: rgb(0, 0, 136);">super</span><span class="pun" style="color: rgb(102, 102, 0);">(</span><span class="str" style="color: rgb(136, 0, 0);">"HelloIntentService"</span><span class="pun" style="color: rgb(102, 102, 0);">);</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="pun" style="color: rgb(102, 102, 0);">}</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="com">/**
* 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.
*/</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="lit" style="color: rgb(0, 102, 102);">@Override</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="kwd" style="color: rgb(0, 0, 136);">protected</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="kwd" style="color: rgb(0, 0, 136);">void</span><span class="pln" style="color: rgb(0, 0, 0);"> onHandleIntent</span><span class="pun" style="color: rgb(102, 102, 0);">(</span><span class="typ" style="color: rgb(102, 0, 102);">Intent</span><span class="pln" style="color: rgb(0, 0, 0);"> intent</span><span class="pun" style="color: rgb(102, 102, 0);">)</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="pun" style="color: rgb(102, 102, 0);">{</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="com">// Normally we would do some work here, like download a file.</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="com">// For our sample, we just sleep for 5 seconds.</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="kwd" style="color: rgb(0, 0, 136);">long</span><span class="pln" style="color: rgb(0, 0, 0);"> endTime </span><span class="pun" style="color: rgb(102, 102, 0);">=</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="typ" style="color: rgb(102, 0, 102);">System</span><span class="pun" style="color: rgb(102, 102, 0);">.</span><span class="pln" style="color: rgb(0, 0, 0);">currentTimeMillis</span><span class="pun" style="color: rgb(102, 102, 0);">()</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="pun" style="color: rgb(102, 102, 0);">+</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="lit" style="color: rgb(0, 102, 102);">5</span><span class="pun" style="color: rgb(102, 102, 0);">*</span><span class="lit" style="color: rgb(0, 102, 102);">1000</span><span class="pun" style="color: rgb(102, 102, 0);">;</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="kwd" style="color: rgb(0, 0, 136);">while</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="pun" style="color: rgb(102, 102, 0);">(</span><span class="typ" style="color: rgb(102, 0, 102);">System</span><span class="pun" style="color: rgb(102, 102, 0);">.</span><span class="pln" style="color: rgb(0, 0, 0);">currentTimeMillis</span><span class="pun" style="color: rgb(102, 102, 0);">()</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="pun" style="color: rgb(102, 102, 0);"><</span><span class="pln" style="color: rgb(0, 0, 0);"> endTime</span><span class="pun" style="color: rgb(102, 102, 0);">)</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="pun" style="color: rgb(102, 102, 0);">{</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="kwd" style="color: rgb(0, 0, 136);">synchronized</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="pun" style="color: rgb(102, 102, 0);">(</span><span class="kwd" style="color: rgb(0, 0, 136);">this</span><span class="pun" style="color: rgb(102, 102, 0);">)</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="pun" style="color: rgb(102, 102, 0);">{</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="kwd" style="color: rgb(0, 0, 136);">try</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="pun" style="color: rgb(102, 102, 0);">{</span><span class="pln" style="color: rgb(0, 0, 0);">
wait</span><span class="pun" style="color: rgb(102, 102, 0);">(</span><span class="pln" style="color: rgb(0, 0, 0);">endTime </span><span class="pun" style="color: rgb(102, 102, 0);">-</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="typ" style="color: rgb(102, 0, 102);">System</span><span class="pun" style="color: rgb(102, 102, 0);">.</span><span class="pln" style="color: rgb(0, 0, 0);">currentTimeMillis</span><span class="pun" style="color: rgb(102, 102, 0);">());</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="pun" style="color: rgb(102, 102, 0);">}</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="kwd" style="color: rgb(0, 0, 136);">catch</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="pun" style="color: rgb(102, 102, 0);">(</span><span class="typ" style="color: rgb(102, 0, 102);">Exception</span><span class="pln" style="color: rgb(0, 0, 0);"> e</span><span class="pun" style="color: rgb(102, 102, 0);">)</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="pun" style="color: rgb(102, 102, 0);">{</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="pun" style="color: rgb(102, 102, 0);">}</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="pun" style="color: rgb(102, 102, 0);">}</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="pun" style="color: rgb(102, 102, 0);">}</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="pun" style="color: rgb(102, 102, 0);">}</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="pun" style="color: rgb(102, 102, 0);">}</span>
That's all you need: a constructor and an implementation of onHandleIntent()
.
If you decide to also override other callback methods, such as onCreate()
, onStartCommand()
, oronDestroy()
, be sure to call the super implementation, so that the IntentService
can properly handle the life of the worker thread.
For example, onStartCommand()
must return the default implementation (which is how the intent gets delivered to onHandleIntent()
):
onCreate()
, onStartCommand()
, oronDestroy(),
确定调用超级示例,以至于IntentService可以处理工作线程的生命。例如
@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); }
Besides onHandleIntent()
, the only method from which you don't need to call the super class isonBind()
(but you only need to implement that if your service allows binding).
In the next section, you'll see how the same kind of service is implemented when extending the baseService
class, which is a lot more code, but which might be appropriate if you need to handle simultaneous start requests.
Extending the Service class
As you saw in the previous section, using IntentService
makes your implementation of a started service very simple. If, however, you require your service to perform multi-threading (instead of processing start requests through a work queue), then you can extend the Service
class to handle each intent.
For comparison, the following example code is an implementation of the Service
class that performs the exact same work as the example above using IntentService
. That is, for each start request, it uses a worker thread to perform the job and processes only one request at a time.
正如前面几段讲的,用一个IntentService实施一个初始服务是非常简单的。然而,如果你要求你的应用执行多线程(而不是通过工作队列处理开始请求),那么你可以继承Service类来处理每个意图。
作为对比,下面是关于Service类的与前面使用IntentService类执行相同工作时的示例代码。可以看出,对于每一个初始请求,它用一个工作线程来解决对应的工作并且一次仅处理一个请求。
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); } @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() < 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); } } @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); } @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; } @Override public IBinder onBind(Intent intent) { // We don't provide binding, so return null return null; } @Override public void onDestroy() { Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show(); } }
As you can see, it's a lot more work than using IntentService
.
However, because you handle each call to onStartCommand()
yourself, you can perform multiple requests simultaneously. That's not what this example does, but if that's what you want, then you can create a new thread for each request and run them right away (instead of waiting for the previous request to finish).
Notice that the onStartCommand()
method must return an integer. The integer is a value that describes how the system should continue the service in the event that the system kills it (as discussed above, the default implementation for IntentService
handles this for you, though you are able to modify it). The return value from onStartCommand()
must be one of the following constants:
START_NOT_STICKY
onStartCommand()
returns,
do not recreate the service, unless there are pending intents to deliver. This is the safest option to avoid running your service when not necessary and when your application can simply restart any unfinished jobs.
START_STICKY
onStartCommand()
returns, recreate the service and call
onStartCommand()
, but
do not redeliver the last intent. Instead, the system calls
onStartCommand()
with a null intent, unless there were pending intents to start the service, in which case, those intents are delivered. This is suitable for media players (or similar services) that are not executing commands, but running indefinitely and waiting for a job.
If the system kills the service after onStartCommand()
returns, recreate the service and call onStartCommand()
with the last intent that was delivered to the service. Any pending intents are delivered in turn. This is suitable for services that are actively performing a job that should be immediately resumed, such as downloading a file.
如果onStartCommand()
返回这个值之后系统杀死了服务,那么将不创建服务,除非有待处理的意图要传递。这是最安全的选择来避免不必要的时候或者是你的应用可以轻松重启任何未完成工作的时候运行你的服务。
onStartCommand()
返回这个值之后系统杀死了服务,重新创建服务并且调用onStartCommand(),但是不会重新传递最后的意图。相反,系统用 一个空的意图调用onStartCommand(),除非有待定的意图来开启服务,那种情况的话,这些意图将被传递。这对于那些不需要执行命令,只是无限运行等待一个工作的应用(例如媒体播放)是非常合适的。
onStartCommand()
返回这个值之后系统杀死了服务,重新创建服务并且用最后一个传递给服务的意图来调用onStartCommand()
。任何待定的意图被依次传递。这比较适合那些经常执行一些需要立即重启的工作的应用,例如下载一个文件。
Starting a Service
You can start a service from an activity or other application component by passing an Intent
(specifying the service to start) to startService()
. The Android system calls the service'sonStartCommand()
method and passes it the Intent
. (You should never call onStartCommand()
directly.)
For example, an activity can start the example service in the previous section (HelloSevice
) using an explicit intent with startService()
:
Intent intent = new Intent(this, HelloService.class); startService(intent);
The startService()
method returns immediately and the Android system calls the service'sonStartCommand()
method. If the service is not already running, the system first callsonCreate()
, then calls onStartCommand()
.
If the service does not also provide binding, the intent delivered with startService()
is the only mode of communication between the application component and the service. However, if you want the service to send a result back, then the client that starts the service can create a PendingIntent
for a broadcast (with getBroadcast()
) and deliver it to the service in the Intent
that starts the service. The service can then use the broadcast to deliver a result.
Multiple requests to start the service result in multiple corresponding calls to the service'sonStartCommand()
. However, only one request to stop the service (with stopSelf()
orstopService()
) is required to stop it.
startService()将会立即返回然后系统将调用服务的onStartCommand()方法。如果服务未运行,那么系统首先调用onCreate(),然后调用onStartCommand()。如果服务不提供绑定,那么startService()提供的意图就是应用组件和服务之间仅有的联系模式。然而,如果你想要服务返回一个结果,那么启动服务的控制器可以创建一个PendingIntent给一个广播然后用开启服务的意图把它交给服务。多数开启服务的请求导致了一致的结果,那就是对服务中onStartCommand()方法的调用。然而,仅仅停止服务的请求(用stopSelf()
orstopService())
是要求去停止它。
Stopping a service
A started service must manage its own lifecycle. That is, the system does not stop or destroy the service unless it must recover system memory and the service continues to run afteronStartCommand()
returns. So, the service must stop itself by calling stopSelf()
or another component can stop it by calling stopService()
.
Once requested to stop with stopSelf()
or stopService()
, the system destroys the service as soon as possible.
However, if your service handles multiple requests to onStartCommand()
concurrently, then you shouldn't stop the service when you're done processing a start request, because you might have since received a new start request (stopping at the end of the first request would terminate the second one). To avoid this problem, you can use stopSelf(int)
to ensure that your request to stop the service is always based on the most recent start request. That is, when you call stopSelf(int)
, you pass the ID of the start request (the startId
delivered to onStartCommand()
) to which your stop request corresponds. Then if the service received a new start request before you were able to call stopSelf(int)
, then the ID will not match and the service will not stop.
一个开启了的服务必须管理自己的生命周期。也就是说,系统并不会停止或者摧毁服务除非它必须回收系统内存,并且在onStartCommand()返回之后服务会继续运行。因此,系统必须通过调用stopSelf()终止自己或者另一个组件通过调用stopService()来终止它。一旦用stopSelf()
or stopService()发出停止请求,那么系统将尽可能快的摧毁它。
然而,如果你的服务同时处理多个请求,那么你在完成一个开始请求的时候就不应该立即停止你的服务,因为你可能曾收到了一个新的开始请求(在第一个请求结束后停止将会结束第二个)。为了避免这个问题,你可以用stopSelf(int)方法来确认你每次的停止请求是基于最近的开始请求。也就是说,当你调用一个stopSelf(int)方法时,你传递一个开始请求的ID与你的停止请求对应。然后如果在你能够调用stopSelf(int)之前,服务收到了一个新的开始请求,那么这个ID将不匹配,服务将不会停止。
Caution: It's important that your application stops its services when it's done working, to avoid wasting system resources and consuming battery power. If necessary, other components can stop the service by calling
stopService()
. Even if you enable binding for the service, you must always stop the service yourself if it ever received a call to onStartCommand()
.
警告:当你的服务完成它的工作时,把它停止是非常重要的,这可以避免浪费系统资源、消耗电池。如果有必要的话,其他组件可以通过调用 stopService()来停止服务。即使你为服务使能了绑定,如果它从没有接受到一个onStartCommand()的调用,你也必须自己停止服务。
Creating a Bound Service
A bound service is one that allows application components to bind to it by calling bindService()
in order to create a long-standing connection (and generally does not allow components to start it by calling startService()
).
You should create a bound service when you want to interact with the service from activities and other components in your application or to expose some of your application's functionality to other applications, through interprocess communication (IPC).
To create a bound service, you must implement the onBind()
callback method to return an IBinder
that defines the interface for communication with the service. Other application components can then call bindService()
to retrieve the interface and begin calling methods on the service. The service lives only to serve the application component that is bound to it, so when there are no components bound to the service, the system destroys it (you do not need to stop a bound service in the way you must when the service is started through onStartCommand()
).
一个bound服务是一个允许应用组件为了创建一个长时间存在的连接而通过调用bindService()方法创建的服务。(通常不允许组件通过调用startService()方法来开启它)
当你想用你应用中的activity或者其他组件与服务进行交互时或者通过IPC来显示你应用中的某些函数给其他应用时,你应该创建一个bound服务。
为了创建一个bound服务,你必须实现onBind()回调方法来返回一个定义了与服务通信的接口的IBinder。其他应用组件可以调用bindService()来恢复接口以及开始调用子服务里方法。服务仅存活在为与绑定的应用组件服务的时候,所以当没有组件与它绑定时,系统将会摧毁它(当服务由onStartCommand()方法开始时,你不必这样停止一个bound服务)
To create a bound service, the first thing you must do is define the interface that specifies how a client can communicate with the service. This interface between the service and a client must be an implementation of IBinder
and is what your service must return from the onBind()
callback method. Once the client receives the IBinder
, it can begin interacting with the service through that interface.
Multiple clients can bind to the service at once. When a client is done interacting with the service, it calls unbindService()
to unbind. Once there are no clients bound to the service, the system destroys the service.
There are multiple ways to implement a bound service and the implementation is more complicated than a started service, so the bound service discussion appears in a separate document about Bound Services.
要创建一个bound服务,首先你必须要定义指定了控制器怎样与服务通信的接口。这个在控制器和服务直接的接口必须是一个IBinder的实例,而且也是你的服务必须从onBind()方法返回的内容。一旦控制器接收到了IBinder,它开始通过接口与服务进行交互。大多数控制器可以实时的与服务进行绑定。当一个控制器完成了与服务的交互,那它会调用unbindService()方法来进行解绑。一旦不再有控制器与服务进行绑定,系统将摧毁服务。有很多中方法来实现一个bound服务而且这个实现比一个started服务要复杂的多,所以另开一个文档Bound Services进行讨论。
Sending Notifications to the User
Once running, a service can notify the user of events using Toast Notifications or Status Bar Notifications.
A toast notification is a message that appears on the surface of the current window for a moment then disappears, while a status bar notification provides an icon in the status bar with a message, which the user can select in order to take an action (such as start an activity).
Usually, a status bar notification is the best technique when some background work has completed (such as a file completed downloading) and the user can now act on it. When the user selects the notification from the expanded view, the notification can start an activity (such as to view the downloaded file).
一旦开始运行,服务可以通过Toast Notifications或者Status Bar Notifications来通知事件的用户。一个吐司通知是短暂出现在屏幕最前方的一个信息,而一个状态条通知在有信息的状态条中提供了一个按钮,用户可以用这个按钮来执行一个动作(例如开始一个activity)。Running a Service in the Foreground
A foreground service is a service that's considered to be something the user is actively aware of and thus not a candidate for the system to kill when low on memory. A foreground service must provide a notification for the status bar, which is placed under the "Ongoing" heading, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.
For example, a music player that plays music from a service should be set to run in the foreground, because the user is explicitly aware of its operation. The notification in the status bar might indicate the current song and allow the user to launch an activity to interact with the music player.
To request that your service run in the foreground, call startForeground()
. This method takes two parameters: an integer that uniquely identifies the notification and the Notification
for the status bar. For example:
前台服务一般是一些比较让用户关心的服务而且当内存较低时,它不会在被“杀掉”的候补名单中。一个前台服务必须为放置在“正在运行”标题中的状态条提供一个通知,那就意味着通知不能被忽略,除非服务停止或者从前台中移除。
例如,一个来自服务的音乐播放器应该运行在前台中,因为用户关心它的操作。出现在状态条中的通知可能包含当前播放的歌曲而且运行用户开始一个活动来与音乐播放器进行交互。
要使你的服务运行在前台,调用startForeground()方法。这个方法携带两个参数:一个用来独立识别通知的整数和一个状态条通知。举例如下:
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);
Caution: The integer ID you give to startForeground()
must not be 0.
To remove the service from the foreground, call stopForeground()
. This method takes a boolean, indicating whether to remove the status bar notification as well. This method does not stop the service. However, if you stop the service while it's still running in the foreground, then the notification is also removed.
要从前台中移除服务,可以调用stopForeground()方法。这个方法携带了一个指明了是否同时移除状态条通知的布尔值。这个方法不会终止服务。但是,当你在服务运行在前台时停止它,那么通知也会被移除。
Managing the Lifecycle of a Service
The lifecycle of a service is much simpler than that of an activity. However, it's even more important that you pay close attention to how your service is created and destroyed, because a service can run in the background without the user being aware.
The service lifecycle—from when it's created to when it's destroyed—can follow two different paths:
- A started service
The service is created when another component calls
startService()
. The service then runs indefinitely and must stop itself by callingstopSelf()
. Another component can also stop the service by callingstopService()
. When the service is stopped, the system destroys it.. - A bound service
The service is created when another component (a client) calls
bindService()
. The client then communicates with the service through anIBinder
interface. The client can close the connection by callingunbindService()
. Multiple clients can bind to the same service and when all of them unbind, the system destroys the service. (The service does not need to stop itself.)
startService()
. For example, a background music service could be started by callingstartService()
with an Intent
that identifies the music to play. Later, possibly when the user wants to exercise some control over the player or get information about the current song, an activity can bind to the service by calling bindService()
. In cases like this, stopService()
orstopSelf()
does not actually stop the service until all clients unbind.stopService()
orstopSelf()不会停止服务直到所有的控制器解绑。
Implementing the lifecycle callbacks
Like an activity, a service has lifecycle callback methods that you can implement to monitor changes in the service's state and perform work at the appropriate times. The following skeleton service demonstrates each of the lifecycle methods:
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 @Override public voidNote: Unlike the activity lifecycle callback methods, you are not required to call the superclass implementation of these callback methods.onCreate
() { // The service is being created } @Override public intonStartCommand
(Intent intent, int flags, int startId) { // The service is starting, due to a call tostartService()
return mStartMode; } @Override public IBinderonBind
(Intent intent) { // A client is binding to the service withbindService()
return mBinder; } @Override public booleanonUnbind
(Intent intent) { // All clients have unbound withunbindService()
return mAllowRebind; } @Override public voidonRebind
(Intent intent) { // A client is binding to the service withbindService()
, // after onUnbind() has already been called } @Override public voidonDestroy
() { // The service is no longer used and is being destroyed } }
注意:不像活动的生命周期回调方法,你不必调用实现这些方法的超类。
图2. 服务的生命周期图。左边显示的是startService()创建的服务,右边显示的是bindService()创建的服务。
By implementing these methods, you can monitor two nested loops of the service's lifecycle:
- The entire lifetime of a service happens between the time
onCreate()
is called and the timeonDestroy()
returns. Like an activity, a service does its initial setup inonCreate()
and releases all remaining resources inonDestroy()
. For example, a music playback service could create the thread where the music will be played inonCreate()
, then stop the thread inonDestroy()
.The
onCreate()
andonDestroy()
methods are called for all services, whether they're created bystartService()
orbindService()
. - The active lifetime of a service begins with a call to either
onStartCommand()
oronBind()
. Each method is handed theIntent
that was passed to eitherstartService()
orbindService()
, respectively.If the service is started, the active lifetime ends the same time that the entire lifetime ends (the service is still active even after
onStartCommand()
returns). If the service is bound, the active lifetime ends whenonUnbind()
returns.
1、一个服务的整个生命在onCreate()的创建和onDestroy()的返回之间。像一个activity一样,服务在onCreate()中初始化设置,在onDestroy()中释放系统资源。例如,一个后台音乐播放服务可以用onCreate()创建一个播放音乐的线程,然后用onDestroy()停止线程。
onCreate()
和 onDestroy()
方法可以用于所有服务,不论他们是由startService()还是bindService()创建的。
2、一个服务的有效生命时间从调用onStartCommand()或者onBind()开始。每一个方法分别被递送了来自startService()或者bindService()的意图。如果一个服务是被开启的,那么有效生命时间结束时整个生命也就结束了(服务在onStartCommand()
返回之后仍然活动)。如果一个服务是被绑定的,那么有效生命在onUnbind()返回之后结束。
Note: Although a started service is stopped by a call to either stopSelf()
or stopService()
, there is not a respective callback for the service (there's no onStop()
callback). So, unless the service is bound to a client, the system destroys it when the service is stopped—onDestroy()
is the only callback received.
Figure 2 illustrates the typical callback methods for a service. Although the figure separates services that are created by startService()
from those created by bindService()
, keep in mind that any service, no matter how it's started, can potentially allow clients to bind to it. So, a service that was initially started with onStartCommand()
(by a client calling startService()
) can still receive a call to onBind()
(when a client calls bindService()
).
尽管一个started服务可以由调用stopSelf()或者stopService()停止,但是没有一个对于服务的回调函数(没有一个onStop()回调函数)。因此,除非服务被绑定到一个控制器,服务被停止时,系统将摧毁它--onDestroy()被认为是仅有的回调函数。
图2阐明了对于一个服务的典型的回调方法。虽然图片区别开了被startService()创建的服务和被bindService()创建的服务,但是记住,任何服务(无论它是怎么被创建的)都可能允许控制器与它绑定。因此,一个一开始被onStartCommand()创建的服务(通过控制器调用startService())仍然可以接收onBind()方法(当控制器调用bindService()时)。
仅作为个人学习笔记,欢迎批评指正。