Android Service官方文档的介绍

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.

A service can essentially take two forms:

Started
A 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.
Bound
A 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.

Although this documentation generally discusses these two types of services separately, yourservice 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.

Regardless of whether your application is started, bound, or both, any application componentcan use the service (even from a separate application), in the same way that any component can usean activity—by starting it with anIntent. However, you can declarethe service as private, in the manifest file, and block access from other applications. This isdiscussed more in the section aboutDeclaring the service in themanifest.

Caution: A service runs in themain thread of its hosting process—the service doesnot 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.

The Basics

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:

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.)
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.
onCreate()
The system calls this method when the service is first created, to perform one-time setupprocedures (before it calls eitheronStartCommand() oronBind()). If the service is already running, this method is notcalled.
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.

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

If a component callsbindService() to create the service (andonStartCommand() isnot 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.

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 theProcesses and Threadingdocument.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值