您的位置:首页 > 移动开发 > Android开发

android service (官方文档翻译)

2013-10-11 17:52 579 查看

Services

A
Service
is an application component that can performlong-running operations in the background and does not provide a
user interface. Anotherapplication component can start a service and it will continue to run in the background even if theuser switches to another application. Additionally, a component can bind to a service tointeract with it and even perform interprocess
communication (IPC). For example, a service mighthandle network transactions, play music, perform file I/O, or interact with a content provider, allfrom the background.

Service
是一个应用部件,它可以在后台长时间运行。他没有用户借口。另一个部件可以启动一个service,运行在后台,甚至用户切换到另一个应用。另外,一个部件可以绑定一个服务,表现一个ipc。比如,一个service可以放音乐,。。。从后台。

A service can essentially take two forms:

一个服务本质分两种。

StartedA service is "started" when an application component (such as an activity) starts it bycalling
startService()
. Once started, a servicecan 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, theservice should stop itself.
被开始服务:一个应用组件(比如activity),调用startService().只有开始,一个服务在后台无限期的运行,甚至是启动它的组件被销毁。通常,一个被启动服务表现为一个单一操作,不返回结果。比如,下载上传文件。当操作结束,这个service必须终止自己。

BoundA service is "bound" when an application component binds to it by calling
bindService()
. A bound service offers a client-serverinterface
that allows components to interact with the service, send requests, get results, and evendo so across processes with interprocess communication (IPC). A bound service runs only as long asanother 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.
绑定服务:一个应用组件绑定靠
bindService()
。一个绑定服务提供一个c/s接口,它允许组件和服务通信,发送请求,得到结果通过IPC实现。只要一个应用组件绑定服务,这个服务就开始运行。多个组件可以同时绑定一个服务,但是当所有组件都解除绑定,这个服务被销毁。

Caution: A service runs in themain thread of its hosting process—the service does
not create its own threadand does not run in a separate process (unless you specify otherwise). This meansthat, if your service is going to do any CPU intensive work or blocking operations (such as MP3playback or networking),
you should create a new thread within the service to do that work. By usinga separate thread, you will reduce the risk of Application Not Responding (ANR) errors and theapplication's main thread can remain dedicated to user interaction with your activities.

service跑在宿主的主线程,service不会创建自己的线程,不会跑在一个分离的线程中。这就意味着,如果service去作cpu密集的工作,你必须在service生成一个新线程.使用分离的线程,可以减少ANR风险,主线程可以作用户的交互工作。

To create a service, you must create a subclass of
Service
(or oneof its existing subclasses). In your implementation, you need to override some callback methods thathandle key aspects of the service lifecycle
and provide a mechanism for components to bind tothe service, if appropriate. The most important callback methods you should override are:

为了生成一个服务,你必须生成一个服务的子类。在你的实现中,你必须override 生命周期回调。提供一个机制。你必须override如下回调:

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 thebackground indefinitely.
If you implement this, it is your responsibility to stop the service whenits work is done, by calling
stopSelf()
or
stopService()
. (If you only want to provide binding, you don'tneed to implement this method.)

一个activity 调用startService(),请求生成started service,会调用这个方法。只要这个方法执行,这个服务在后台无限期运行。如果你实现了这个方法,你有责任停止这个服务,当工作结束的时候。通过调用
stopSelf()

or
stopService()
。(如果你只想提供绑定,你不必实现这个方法)。

onBind()
The system calls this method when another component wants to bind with theservice (such as to perform RPC), by calling
bindService()
. In your implementation of this method, you must
provide an interface that clientsuse to communicate with the service, by returning an
IBinder
. You must alwaysimplement 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 setupprocedures (before it calls either
onStartCommand()
or
onBind()
).
If the service is already running, this method is notcalled.

当这个服务第一次被生成时,系统调用这个方法,执行一次性的创建过程。在
onStartCommand()
or
onBind()
之前。如果服务已经正在运行,这个方法不被调用。

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, registeredlisteners, receivers, etc. This is the last call
the service receives.
当这个服务不再被使用的时候,系统调用这个方法。你的服务要清理threads, registeredlisteners, receivers, etc.

If a component starts the service by calling
startService()
(which results in a call to
onStartCommand()
), then the serviceremains running until it stops itself with
stopSelf()
or anothercomponent stops it by calling
stopService()
.

如果一个组件调用startService(),来开始一个服务,(将导致调用onStartCommand())。这个服务一直执行,直到调用stopSelf,stopSerice().

If a component calls
bindService()

to create the service (and
onStartCommand()
is
not called), then the service runsonly as long as the component is bound to it. Once the service is unbound from all clients, thesystem destroys it.

如果一个组件调用bindSerice(),生成服务(onStartCommand不被调用),只要这个组件绑定,这个服务就一直运行。只有所有的客户端解除绑定,系统将销毁这个服务。

The Android system will force-stop a service only when memory is low and it must recover systemresources for the activity that has user focus. If the service is bound to an activity that has userfocus, 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 positionin the list of background tasks over time and the service will become highly susceptible
tokilling—if your service is started, then you must design it to gracefully handle restartsby the system. If the system kills your service, it restarts it as soon as resources becomeavailable again (though this also depends on the value you return from
onStartCommand()
, as discussed later). For more informationabout when the system might destroy
a service, see the
Processes and Threadingdocument.

系统将强迫停止一个服务,当内存少的时候。系统必须覆盖资源为了有focus的activity, 如果服务被绑定到一个有focus的activity,这个服务不可能被杀掉。如果一个服务被声明到前台,它将永远不被杀掉。否则,如果服务是被开始的,长时间运行,系统低内存,这个服务很有可能被杀掉。如果服务是被开始的,你必须很好的设计当restart的时候。如果系统杀掉你的服务,它将会restart.(虽然也依赖onStartCommand的返回值)。

In the following sections, you'll see how you can create each type of service and how to useit from other application components.

Declaring a service in the manifest

Like activities (and other components), you must declare all services in your application'smanifest file.

To declare your service, add a
<service>
elementas a child of the
<application>
element. For example:

<manifest ... >
  ...
  <application ... >
      <service android:name=".ExampleService" />
      ...
  </application>
</manifest>

There are other attributes you can include in the

<service>
element todefine properties such as permissions required to start the service and the process inwhich the service should run. The

android:name
attribute is the only required attribute—it specifies the class name of the service. Onceyou publish your application, you should not change this name, because if you do, you might breaksome functionality where explicit intents
are used to reference your service (read the blog post,
ThingsThat Cannot Change).

android:name
是唯一必须的属性,它是service类的名字。一旦你发布了你的程序,你不能改变这个名字,因为如果你这么做了,你可能破坏功能,在显示intent调用service.

See the
<service>
elementreference for more information about declaring your service in the manifest.

Just like an activity, a service can define intent filters that allow other components toinvoke the service using implicit intents. By declaring intent filters, componentsfrom any application installed on the user's device can
potentially start your service if yourservice declares an intent filter that matches the intent another application passes to
startService()
.

就像一个activity, 一个服务也可以定义intent filters, 它允许其他组件服务使用隐式intents. 通过声明intent filters,任何应用的组件可以开始你的服务,如果intent匹配。

If you plan on using your service only locally (other applications do not use it), then youdon't need to (and should not) supply any intent filters. Without any intent filters, you muststart the service using an intent that explicitly
names the service class. More informationabout
starting a service is discussed below.

如果你计划使用你的服务只在本地,你禁止提供任何filter.没有任何filter,你必须开始服务使用显式的intert.

Additionally, you can ensure that your service is private to your application only ifyou include the

android:exported
attribute and set it to
"false"
. This is effective even if your service supplies intentfilters.

For more information about creating intent filters for your service, see the

Intents and Intent Filtersdocument.

另外,你确认你的服务是私有的对于你的应用,把
android:exported
attribute and set it to
"false"
。这个是有效的,甚至你的服务提供filiter.

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 thecomponent that started it and the service can run in the background indefinitely, even ifthe component that started it is destroyed. As such, the service should stop itself when its jobis
done by calling
stopSelf()
, or another component can stop itby calling
stopService()
.

An application component such as an activity can start the service by calling
startService()
and passing an
Intent
that specifies the service and includes any data for the service to use. The service receivesthis
Intent
in the
onStartCommand()
method.

For instance, suppose an activity needs to save some data to an online database. The activity canstart a companion service and deliver it the data to save by passing an intent to
startService()
. The service receives the intent in
onStartCommand()
, connects to the Internet and performs thedatabase transaction. When the transaction
is done, the service stops itself and it isdestroyed.

Caution: A services runs in the same process as the applicationin which it is declared and in the main thread of that application, by default. So, if your serviceperforms intensive or blocking operations while the user interacts
with an activity from the sameapplication, the service will slow down activity performance. To avoid impacting applicationperformance, you should start a new thread inside the service.
Traditionally, there are two classes you can extend to create a started service:

Service
This is the base class for all services. When you extend this class, it's important thatyou create a new thread in which to do all the service's work, because the service uses yourapplication's main thread, by default, which could slow the performance of
any activity yourapplication is running.
IntentService
This is a subclass of
Service
that uses a worker thread to handle allstart requests, one at a time. This is the best option if you don't require that
your servicehandle multiple requests simultaneously. All you need to do is implement
onHandleIntent()
, which receives the intent for eachstart request so you can do the background work.
The following sections describe how you can implement your service using either one for theseclasses.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: