关闭

Android Service

5044人阅读 评论(0) 收藏 举报

Class Overview

A Service is an application component that runs in the background, not interacting with the user, for an indefinite period of time. Each service class must have a corresponding <service> declaration in its package's AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().

Service是在一段不定的时间运行在后台,不和用户交互应用组件。每个Service必须在manifest 通过<service>来声明。可以通过contect.startservicecontect.bindserverice来启动。

 

Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. More information on this can be found in Application Fundamentals: Processes and Threads.

Service和其他的应用组件一样,运行在进程的主线程中。这就是说如果service需要很多耗时或者阻塞的操作,需要在其子线程中实现。

The Service class is an important part of an application's overall lifecycle.

Topics covered here:

1.       Service Lifecycle

2.       Permissions

3.       Process Lifecycle

Service Lifecycle

There are two reasons that a service can be run by the system. If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

 

Service的生命周期。系统有两种方式启动service.如果通过调用context.startservice. 系统会在找到service(如果需要,会调用onCreate,并通过客户端传递的参数来调用onStartCommandService将从这时一直运行到context.stopservciestopself的调用。多次重复调用startservice并不会嵌套(尽管会有相应次数的onStartCommand的调用),只要有一次stopServicestopSelf的调用就会停止掉service. 然后service可以利用stopSelf(int)方法确保自身一直到启动的intents被执行才停止。

For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them. See the linked documentation for more detail on the semantics.

对于启动的service,根据onStartCommand的返回值不同,有两个附加的模式。

1 START_STICKY 用于显示启动和停止service

2START_NOT_STICKYSTART_REDELIVER_INTENT用于有命令需要处理时菜运行的模式。

 

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service's IBinder). Usually the IBinder returned is for a complex interface that has been written in aidl.

客户点可以 通过bindService来获取和service的长久连接,如果没有启动,则会调用onCreate来启动,但是不会调用onStartCommand 客户端会接受到Service返回的IBinder对象,这个对象允许客户端对service发出调用。 Service会在保持连接的过程中保持运行状态(不管客户端是不是保留着serviceIBinder对象)。通过IBinder是通过AIDL实现的负责接口。

 

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().

一个service可以同时启动并连接,在这样的情况,系统会一直保持service的运行状态如果service已经启动了或者BIND_AUTO_CREATE标志被设置。如果没有一个条件满足,那么系统将会调用onDestory方法来终止service.所有的清理工作(终止线程,反注册接收器)都在onDestory中完成。

 

Permissions

Global access to a service can be enforced when it is declared in its manifest's <service> tag. By doing so, other applications will need to declare a corresponding <uses-permission> element in their own manifest to be able to start, stop, or bind to the service.

 

如果在manifest中声明了全局的强制的访问权限,其他引用必须声明权限才能来startstopbind这个service.

In addition, a service can protect individual IPC calls into it with permissions, by calling the checkCallingPermission(String) method before executing the implementation of that call.

另外,service可以通过权限来保护她的IPC方法调用,通过调用checkCallPermission方法来确保可以执行这个操作。

See the Security and Permissions document for more information on permissions and security in general.

Process Lifecycle

The Android system will attempt to keep the process hosting a service around as long as the service has been started or has clients bound to it. When running low on memory and needing to kill existing processes, the priority of a process hosting the service will be the higher of the following possibilities:

Android系统会尽量保持拥有service的进程运行,只要在该service已经被启动或者客户端连接到他。当内存不足时,需要保持,拥有service的进程具有较高的优先级。

 

·         If the service is currently executing code in its onCreate(), onStartCommand(), or onDestroy() methods, then the hosting process will be a foreground process to ensure this code can execute without being killed.

·         If the service has been started, then its hosting process is considered to be less important than any processes that are currently visible to the user on-screen, but more important than any process not visible. Because only a few processes are generally visible to the user, this means that the service should not be killed except in extreme low memory conditions.

·         If there are clients bound to the service, then the service's hosting process is never less important than the most important client. That is, if one of its clients is visible to the user, then the service itself is considered to be visible.

·         A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)

1.    如果service正在调用onCreate,onStartCommand或者onDestory方法,那么用于当前service的进程则变为前台进程以避免被killed

2.    如果当前service已经被启动,拥有它的进程则比那些用户可见的进程优先级低一些,但是比那些不可见的进程更重要,这就意味着service一般不会被killed.

3.    如果客户端已经连接到service,那么拥有Service的进程则拥有最高的优先级,可以认为service是可见的。

4.    如果service可以使用startForeground来将service设置为前台状态,那么系统就认为是对用户可见的,并不会在内存不足时killed

 

Note this means that most of the time your service is running, it may be killed by the system if it is under heavy memory pressure. If this happens, the system will later try to restart the service. An important consequence of this is that if you implement onStartCommand() to schedule work to be done asynchronously or in another thread, then you may want to use START_FLAG_REDELIVERY to have the system re-deliver an Intent for you so that it does not get lost if your service is killed while processing it.

这就意味着大部分时间service的运行并不会被killed,除非严重的内存不足,这种情况下,系统会尝试重启service。如果实现 onStartCommand去调度异步工作或者其他的线程,有必要设置START_FLAG_REDELIVERY让系统重发intentservice以便servicekilled后不会丢失intent数据。

Other application components running in the same process as the service (such as an Activity) can, of course, increase the importance of the overall process beyond just the importance of the service itself.

如果有其他的应用组件运行在相同的进程中,那么将会增加该进程的重要性。

Summary

Constants

int

START_CONTINUATION_MASK

Bits returned by onStartCommand(Intent, int, int) describing how to continue the service if it is killed.

 

 

 

 

 

 

 

 

 

int

START_FLAG_REDELIVERY

This flag is set in onStartCommand(Intent, int, int) if the Intent is a re-delivery of a previously delivered intent, because the service had previously returned START_REDELIVER_INTENT but had been killed before calling stopSelf(int) for that Intent.

 

 

 

 

 

 

 

 

 

int

START_FLAG_RETRY

This flag is set in onStartCommand(Intent, int, int) if the Intent is a a retry because the original attempt never got to or returned from onStartCommand(Intent, int, int).

 

 

 

 

 

 

 

 

 

int

START_NOT_STICKY

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call to Context.startService(Intent).

 

 

 

 

 

 

 

 

 

int

START_REDELIVER_INTENT

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then it will be scheduled for a restart and the last delivered Intent re-delivered to it again via onStartCommand(Intent, int, int).

 

 

 

 

 

 

 

 

 

int

START_STICKY

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent.

 

 

 

 

 

 

 

 

 

int

START_STICKY_COMPATIBILITY

Constant to return from onStartCommand(Intent, int, int): compatibility version of START_STICKY that does not guarantee that onStartCommand(Intent, int, int) will be called again after being killed.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Constants

public static final int START_CONTINUATION_MASK

Since: API Level 5

Bits returned by onStartCommand(Intent, int, int) describing how to continue the service if it is killed. May be START_STICKY, START_NOT_STICKY, START_REDELIVER_INTENT, or START_STICKY_COMPATIBILITY.

Constant Value: 15 (0x0000000f)

public static final int START_FLAG_REDELIVERY

Since: API Level 5

This flag is set in onStartCommand(Intent, int, int) if the Intent is a re-delivery of a previously delivered intent, because the service had previously returned START_REDELIVER_INTENT but had been killed before calling stopSelf(int) for that Intent.

Constant Value: 1 (0x00000001)

public static final int START_FLAG_RETRY

Since: API Level 5

This flag is set in onStartCommand(Intent, int, int) if the Intent is a a retry because the original attempt never got to or returned from onStartCommand(Intent, int, int).

Constant Value: 2 (0x00000002)

public static final int START_NOT_STICKY

Since: API Level 5

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call to Context.startService(Intent). The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will not be re-started if there are no pending Intents to deliver.

This mode makes sense for things that want to do some work as a result of being started, but can be stopped when under memory pressure and will explicit start themselves again later to do more work. An example of such a service would be one that polls for data from a server: it could schedule an alarm to poll every N minutes by having the alarm start its service. When its onStartCommand(Intent, int, int) is called from the alarm, it schedules a new alarm for N minutes later, and spawns a thread to do its networking. If its process is killed while doing that check, the service will not be restarted until the alarm goes off.

Constant Value: 2 (0x00000002)

public static final int START_REDELIVER_INTENT

Since: API Level 5

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then it will be scheduled for a restart and the last delivered Intent re-delivered to it again via onStartCommand(Intent, int, int). This Intent will remain scheduled for redelivery until the service calls stopSelf(int) with the start ID provided to onStartCommand(Intent, int, int). The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will will only be re-started if it is not finished processing all Intents sent to it (and any such pending events will be delivered at the point of restart).

Constant Value: 3 (0x00000003)

public static final int START_STICKY

Since: API Level 5

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.

Constant Value: 1 (0x00000001)

public static final int START_STICKY_COMPATIBILITY

Since: API Level 5

Constant to return from onStartCommand(Intent, int, int): compatibility version of START_STICKY that does not guarantee that onStartCommand(Intent, int, int) will be called again after being killed.

Constant Value: 0 (0x00000000)

Public Constructors

public Service ()

Since: API Level 1

Public Methods

public final Application getApplication ()

Since: API Level 1

Return the application that owns this service.

public abstract IBinder onBind (Intent intent)

Since: API Level 1

Return the communication channel to the service. May return null if clients can not bind to the service. The returned IBinder is usually for a complex interface that has been described using aidl.

Note that unlike other application components, calls on to the IBinder interface returned here may not happen on the main thread of the process. More information about this can be found in Application Fundamentals: Processes and Threads.

Parameters

intent

The Intent that was used to bind to this service, as given to Context.bindService. Note that any extras that were included with the Intent at that point will not be seen here.

Returns

·       Return an IBinder through which clients can call on to the service.

public void onConfigurationChanged (Configuration newConfig)

Since: API Level 1

Called by the system when the device configuration changes while your component is running. Note that, unlike activities, other components are never restarted when a configuration changes: they must always deal with the results of the change, such as by re-retrieving resources.

At the time that this function has been called, your Resources object will have been updated to return resource values matching the new configuration.

Parameters

newConfig

The new device configuration.

public void onCreate ()

Since: API Level 1

Called by the system when the service is first created. Do not call this method directly.

public void onDestroy ()

Since: API Level 1

Called by the system to notify a Service that it is no longer used and is being removed. The service should clean up an resources it holds (threads, registered receivers, etc) at this point. Upon return, there will be no more calls in to this Service object and it is effectively dead. Do not call this method directly.

 

当Service

public void onLowMemory ()

Since: API Level 1

This is called when the overall system is running low on memory, and would like actively running process to try to tighten their belt. While the exact point at which this will be called is not defined, generally it will happen around the time all background process have been killed, that is before reaching the point of killing processes hosting service and foreground UI that we would like to avoid killing.

Applications that want to be nice can implement this method to release any caches or other unnecessary resources they may be holding on to. The system will perform a gc for you after returning from this method.

public void onRebind (Intent intent)

Since: API Level 1

Called when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind(Intent). This will only be called if the implementation of onUnbind(Intent) was overridden to return true.

当的客户端原来连接断开的情况下重新又来连接到service时会被调用。

 

Parameters

intent

The Intent that was used to bind to this service, as given to Context.bindService. Note that any extras that were included with the Intent at that point will not be seen here.

public void onStart (Intent intent, int startId)

Since: API Level 1

This method is deprecated.
Implement
onStartCommand(Intent, int, int) instead.

public int onStartCommand (Intent intent, int flags, int startId)

Since: API Level 5

Called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it supplied and a unique integer token representing the start request. Do not call this method directly.

 

在用户显示的调用startService时调用该方法,提供一个唯一的inter代表开始的请求。

For backwards compatibility, the default implementation calls onStart(Intent, int) and returns either START_STICKY or START_STICKY_COMPATIBILITY.

Parameters

intent

The Intent supplied to startService(Intent), as given. This may be null if the service is being restarted after its process has gone away, and it had previously returned anything except START_STICKY_COMPATIBILITY.

flags

Additional data about this start request. Currently either 0, START_FLAG_REDELIVERY, or START_FLAG_RETRY.

startId

A unique integer representing this specific request to start. Use with stopSelfResult(int).

Returns

·       The return value indicates what semantics the system should use for the service's current started state. It may be one of the constants associated with the START_CONTINUATION_MASK bits.

See Also

·       stopSelfResult(int)

public boolean onUnbind (Intent intent)

Since: API Level 1

Called when all clients have disconnected from a particular interface published by the service. The default implementation does nothing and returns false.

当客户端和Service的某个连接都端口是被调用,

Parameters

intent

The Intent that was used to bind to this service, as given to Context.bindService. Note that any extras that were included with the Intent at that point will not be seen here.

Returns

·       Return true if you would like to have the service's onRebind(Intent) method later called when new clients bind to it.

public final void setForeground (boolean isForeground)

Since: API Level 1

This method is deprecated.
This is a now a no-op, use
startForeground(int, Notification) instead. This method has been turned into a no-op rather than simply being deprecated because analysis of numerous poorly behaving devices has shown that increasingly often the trouble is being caused in part by applications that are abusing it. Thus, given a choice between introducing problems in existing applications using this API (by allowing them to be killed when they would like to avoid it), vs allowing the performance of the entire system to be decreased, this method was deemed less important.

public final void startForeground (int id, Notification notification)

Since: API Level 5

Make this service run in the foreground, supplying the ongoing notification to be shown to the user while in this state. By default services are background, meaning that if the system needs to kill them to reclaim more memory (such as to display a large page in a web browser), they can be killed without too much harm. You can set this flag if killing your service would be disruptive to the user, such as if your service is performing background music playback, so the user would notice if their music stopped playing.

确保service运行在前台,允许通过notification来通知到用户。。一般情况下service是出于后台的,这就意味着如果系统需要回收内存,那么就有可能killed这个service。如果想在被kill的时候通知用户,那么可以设置这个标志。

Parameters

id

The identifier for this notification as per NotificationManager.notify(int, Notification).

notification

The Notification to be displayed.

See Also

·       stopForeground(boolean)

public final void stopForeground (boolean removeNotification)

Since: API Level 5

Remove this service from foreground state, allowing it to be killed if more memory is needed.

将service从前台移除,如果内存不足时可能会被killed。

Parameters

removeNotification

If true, the notification previously provided to startForeground(int, Notification) will be removed. Otherwise it will remain until a later call removes it (or the service is destroyed).

See Also

·       startForeground(int, Notification)

public final void stopSelf ()

Since: API Level 1

Stop the service, if it was previously started. This is the same as calling stopService(Intent) for this particular service.

 

如果启动了,则停止掉。

See Also

·       stopSelfResult(int)

public final void stopSelf (int startId)

Since: API Level 1

Old version of stopSelfResult(int) that doesn't return a result.

See Also

·       stopSelfResult(int)

public final boolean stopSelfResult (int startId)

Since: API Level 1

Stop the service if the most recent time it was started was startId. This is the same as calling stopService(Intent) for this particular service but allows you to safely avoid stopping if there is a start request from a client that you haven't yet seen in onStart(Intent, int).

如果最后一次调用service的是startId,那么将停止service. 这个方法对于特殊的Service类似于调用stopService.但是可以完全避免有启动请求没有到达之前就停止掉了service

Be careful about ordering of your calls to this function.. If you call this function with the most-recently received ID before you have called it for previously received IDs, the service will be immediately stopped anyway. If you may end up processing IDs out of order (such as by dispatching them on separate threads), then you are responsible for stopping them in the same order you received them.

 

应当小心的使用该方法,如果通过在调用该方法之前的最近接受的ID来调用该方法,那么将service将立即停止。如果想不按照顺序结束处理的ID,那么需要按照相同的接受顺序停止。

Parameters

startId

The most recent start identifier received in onStart(Intent, int).

Returns

·       Returns true if the startId matches the last start request and the service will be stopped, else false.

See Also

·       stopSelf()

Protected Methods

protected void dump (FileDescriptor fd, PrintWriter writer, String[] args)

Since: API Level 1

Print the Service's state into the given stream. This gets invoked if you run "adb shell dumpsys activity service ". This is distinct from "dumpsys ", which only works for named system services and which invokes the dump(FileDescriptor, String[]) method on the IBinder interface registered with ServiceManager.

Parameters

fd

The raw file descriptor that the dump is being sent to.

writer

The PrintWriter to which you should dump your state. This will be closed for you after you return.

args

additional arguments to the dump request.

protected void finalize ()

Since: API Level 1

Is called before the object's memory is being reclaimed by the VM. This can only happen once the VM has detected, during a run of the garbage collector, that the object is no longer reachable by any thread of the running application.

The method can be used to free system resources or perform other cleanup before the object is garbage collected. The default implementation of the method is empty, which is also expected by the VM, but subclasses can override finalize() as required. Uncaught exceptions which are thrown during the execution of this method cause it to terminate immediately but are otherwise ignored.

Note that the VM does guarantee that finalize() is called at most once for any object, but it doesn't guarantee when (if at all) finalize() will be called. For example, object B's finalize() can delay the execution of object A's finalize() method and therefore it can delay the reclamation of A's memory. To be safe, use a ReferenceQueue, because it provides more control over the way the VM deals with references during garbage collection.

Throws

Throwable

 

 

0
0

猜你在找
深度学习基础与TensorFlow实践
【在线峰会】前端开发重点难点技术剖析与创新实践
【在线峰会】一天掌握物联网全栈开发之道
【在线峰会】如何高质高效的进行Android技术开发
机器学习40天精英计划
Python数据挖掘与分析速成班
微信小程序开发实战
JFinal极速开发企业实战
备战2017软考 系统集成项目管理工程师 学习套餐
Python大型网络爬虫项目开发实战(全套)
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:105532次
    • 积分:1253
    • 等级:
    • 排名:千里之外
    • 原创:12篇
    • 转载:19篇
    • 译文:0篇
    • 评论:29条
    文章分类
    最新评论