【翻译】安卓最新API文档——Services(The Basics基本概况)

一、目录

1The Basics(基本概况)

2Declaring aservice in the manifest(在manifest中声明一个服务)

3Creating aStarted Service(创建一个Started服务)

        Extending theIntentService class(继承IntentService类)

        Extending theService class(继承Service类)

        Starting aservice(开始service

        Stopping aservice(停止service

3Creating a BoundService(创建一个Bound服务)

4SendingNotifications to the User(给用户发通知)

5Running aService in the Foreground(在前台运行服务)

6Managing theLifecycle of a Service(管理服务的生命周期)

7Implementing thelifecycle callbacks进行生命周期回调)

二、内容

1TheBasics(基本概况)

Service is an application component thatcan perform long-running operations in the background and does not provide auser interface. Another application component can start a service and it willcontinue to run in the background even if the user switches to anotherapplication. Additionally, a component can bind to a service to interact withit and even perform interprocess communication (IPC). For example, a servicemight handle network transactions, play music, perform file I/O, or interactwith a content provider, all from the background.

服务(Service)是一个应用程序组件,可以在不显示用户界面的情况下,在后台长期运行。一个应用程序组件也可以启动一个服务,即使用户切换到另一个应用程序,它也会继续在后台运行。另外,一个组件可以绑定一个服务并与它交互,甚至可以进行进程间通信(IPC)。例如,一个服务可以在后台处理网络事务,播放音乐,执行文件I/O,或者与内容提供者交互。

A service can essentially take twoforms:

一个服务从本质上来说有两种形式:

Started

A service is "started" when anapplication component (such as an activity) starts it by callingstartService(). Once started, a service can run in thebackground indefinitely, even if the component that started it is destroyed.Usually, a started service performs a single operation and does not return aresult to the caller. For example, it might download or upload a file over thenetwork. When the operation is done, the service should stop itself.

当一个应用程序组件(如activity)开始它的callingstartservice()方法的时候,服务处于"started"状态。一旦开始,即使启动它的组件被销毁,这个服务依然可以一直在后台运行。通常,这个启动的服务用于执行一个操作,并且不返回结果给调用者。例如,它可以通过网络下载或上传一个文件。当完成操作的时候,应该停止服务。

Bound

A service is "bound" when an applicationcomponent 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 even do so across processes with interprocess communication(IPC). A bound service runs only as long as another application component isbound to it. Multiple components can bind to the service at once, but when allof them unbind, the service is destroyed.

当一个应用组件通过调用bindservice()绑定一个服务的时候,服务处于"bound"状态。被绑定的服务提供了一个客户端-服务器的接口,允许组件与服务交互,发送请求并得到的结果,甚至进行进程间通信(IPC)。一个被绑定的服务,只要另一个应用程序组件绑定它,它就一直开启。多个组件可以同时绑定这个服务,但当他们全部解除绑定的时候,服务结束。

Although this documentation generallydiscusses these two types of services separately, your service can work bothways—it can be started (to run indefinitely) and also allow binding. It'ssimply a matter of whether you implement a couple callback methods: onStartCommand() to allow components to start itand onBind() to allow binding.

虽然该文档分开讨论了这两种服务,但是你可以同时开启这两种服务。你只要:使用onstartcommand()方法允许组件启动它,使用onbind()允许绑定它。

Regardless of whether your applicationis started, bound, or both, any application component can use the service (evenfrom a separate application), in the same way that any component can use anactivity—by starting it with an Intent. However, you can declare the serviceas private, in the manifest file, and block access from other applications.This is discussed more in the section about Declaringthe service in the manifest.

不管你的应用程序使用startedbound,或者都用,任何应用程序组件都可以使用服务,就像在任何组件都可以通过intent使用activity一样。当然,你也可以在manifest文件中或其他的应用程序的语句块中,把服务声明为私有服务。这些内容详情请见Declaringthe service in the manifest部分

Caution: A service runs in the mainthread of its hosting process—the service does not create its ownthread and does not run in a separate process (unless you specifyotherwise). This means that, if your service is going to do any CPU intensivework or blocking operations (such as MP3 playback or networking), you shouldcreate a new thread within the service to do that work. By using a separatethread, you will reduce the risk of Application Not Responding (ANR) errors andthe application's main thread can remain dedicated to user interaction withyour activities.

注意:如果一个服务运行在其主线程中,而不是开一个单独的线程,并且你的服务是要做CPU密集的工作或阻塞的操作(如MP3播放或网络)。那么,你应该创建一个新的线程开启服务去做这项工作。通过使用一个单独的线程,你将减少应用程序无响应的风险(ANR),那么应用程序的主线程可以继续致力于与用户交互活动。

To create a service, you must create asubclass of Service(or one of its existing subclasses). Inyour implementation, you need to override some callback methods that handle keyaspects of the service lifecycle and provide a mechanism for components to bindto the service, if appropriate. The most important callback methods you shouldoverride are:

创建一个服务,您必须创建服务类(或它的一个现有的子类)。在你用的时候,需要重写一些回调方法处理的服务生命周期的关键节点,并且提供一个组件和服务的绑定机制,如果需要的话,你应该自己实现这些回调方法:

onStartCommand()

The system calls this method whenanother component, such as an activity, requests that the service be started,by calling startService(). Once this method executes, the serviceis 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() or stopService(). (If you only want to provide binding,you don't need to implement this method.)

一个组件,如activity,要求该服务开始的时候,系统调用通过调用startservice()这个方法实现。一旦这个方法执行,服务就开始启动并在后台一直运行下去。当你想停止服务时,通过调用stopself()stopservice()停止。(如果你只想提供绑定,你不需要实现这个方法。)

onBind()

The system calls this method whenanother component wants to bind with the service (such as to perform RPC), bycalling 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.

一个组件要与服务绑定(如执行RPC)的时候(通过调用bindservice()),那么系统将调用这个方法。在你实现这个方法的时候,你必须提供一个接口:这个接口通过客户端与服务端进行通信,并返回一个IBinder。但是如果你不想允许绑定,那么你应该返回null

onCreate()

The system calls this method when theservice is first created, to perform one-time setup procedures (before it callseither onStartCommand() or onBind()). If the service is already running,this method is not called.

服务第一次创建调用此方法,系统执行此方法( 在onStartCommand() or onBind()之前)。如果该服务已经在运行,这个方法不会被调用。

onDestroy()

The system calls this method when theservice is no longer used and is being destroyed. Your service should implementthis to clean up any resources such as threads, registered listeners,receivers, etc. This is the last call the service receives.

当服务不再被使用或被调用的时候,使用这个方法。你的服务通过这个方法去清理任何资源,如threads, registered listeners, receivers等。

If a component starts the service by calling startService() (which results in a call toonStartCommand()), then the service remains runninguntil it stops itself with stopSelf() or another component stops it by calling stopService().

如果一个组件通过调用startservice()启动该服务,那么服务一直运行,直到自己调用stopself()或另一个部件调用stopservice()的时候才停止。

If a component calls bindService() to create the service (and onStartCommand() is not called), then the service runs only aslong as the component is bound to it. Once the service is unbound from allclients, the system destroys it.

如果一个组件调用bindservice()创建服务,那么只要有使用者绑定它,那么它会一直运行。一旦所有的使用者解除绑定,系统才销毁它。

The Android system will force-stop aservice only when memory is low and it must recover system resources for theactivity that has user focus. If the service is bound to an activity that hasuser focus, then it's less likely to be killed, and if the service is declaredto run in the foreground(discussed later), then it will almostnever be killed.

Android系统只有当内存低的时候,才会将强制停止一个服务,并回收系统资源。如果服务被绑定到一个用户焦点的活动,那么它不太可能被杀死。如果服务被声明为前台运行(稍后讨论),那么它几乎不可能被杀。

Otherwise, if the service was startedand is long-running, then the system will lower its position in the list ofbackground tasks over time and the service will become highly susceptible tokilling—if your service is started, then you must design it to gracefullyhandle restarts by the system. If the system kills your service, it restarts itas soon as resources become available again (though this also depends on thevalue you return from onStartCommand(), as discussed later). For moreinformation about when the system might destroy a service, see the Processes and Threading document.

否则,如果服务被启动并长期运行,那么一段时间后,系统会在的后台任务中减少她的使用空间,于是这个服务更容易被杀死。所以你得设计一种好的重启service机制,以便系统能在短时间让它活过来。更多service销毁方面的信息,请参阅Processesand Threading 的文档。

如果系统杀死你的服务,它重新启动它当资源变得再次可用(虽然这也取决于你从onstartcommand(),价值为以后讨论)。更多系统摧毁服务的信息,请参见进程和线程文档。

In the following sections, you'll seehow you can create each type of service and how to use it from otherapplication components.

在下面的章节中,你将看到如何创建每种类型的服务以及如何在其他应用程序组件中使用它。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值