Service官方教程(1)Started与Bound的区别、要实现的函数、声明service
Services 简介和分类
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.
A service can essentially take two forms:
- Started
- A service is "started" when an application component (such as an activity) starts it by calling
startService()
. 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.
started类型的service一但启动,一直在后台运行,直到自己停止或被停止,生命周期与启动者无关,不与启动者通信。
- 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.
Bound类型的service生命随绑定者存在,当有多个时,直到最后一个解绑才销毁。它是c-s中的s,通常与c通信。
- 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 andonBind()
to allow binding. - 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 about 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.
The Basics 重要函数
To create a service, you must create a subclass of Service
(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:
- 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 callingstopSelf()
orstopService()
. (If you only want to provide binding, you don't need to implement this method.)
- 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 anIBinder
. You must always implement this method, but if you don't want to allow binding, then you should return null.
- The system calls this method when the service is first created, to perform one-time setup procedures (before it calls either
onStartCommand()
oronBind()
). If the service is already running, this method is not called.
- 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.
If a component starts the service by calling startService()
(which results in a call to onStartCommand()
), 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.
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 (声明一个service)
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:
<manifest ... >
...
<application ... >
<service android:name=".ExampleService" />
...
</application>
</manifest>
See the <service>
element reference for more information about declaring your service in the manifest.
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. The android: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 your Service
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.
两种类型的Service都要以精确型Intent启动。
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.
Service官方教程(1)Started与Bound的区别、要实现的函数、声明service的更多相关文章
- Service官方教程(10)Bound Service的生命周期函数
Managing the Lifecycle of a Bound Service When a service is unbound from all clients, the Android sy ...
- Service官方教程(6)Bound Services主要用来实现通信服务,以及3种实现通信的方案简介。
1.Bound Services A bound service is the server in a client-server interface. A bound service allows ...
- Service官方教程(3)Bound Services
Bound Services 1.In this document The Basics Creating a Bound Service Extending the Binder class Usi ...
- Service官方教程(8)Bound Service示例之2-跨进程使用Messenger
Compared to AIDL When you need to perform IPC, using a Messenger for your interface is simpler than ...
- Service官方教程(9)绑定服务时的注意事项
Binding to a Service Application components (clients) can bind to a service by calling bindService() ...
- Service官方教程(4)两种Service的生命周期函数
Managing the Lifecycle of a Service The lifecycle of a service is much simpler than that of an activ ...
- Service官方教程(2)*IntentService与Service示例、onStartCommand()3个返回值的含义。
1.Creating a Started Service A started service is one that another component starts by calling start ...
- linux下service+命令和直接去执行命令的区别,怎么自己建立一个service启动
启动一些程序服务的时候,有时候直接去程序的bin目录下去执行命令,有时候利用service启动. 比如启动mysql服务时,大部分喜欢执行service mysqld start.当然也可以去mysq ...
- Service官方教程(11)Bound Service示例之2-AIDL 定义跨进程接口并通信
Android Interface Definition Language (AIDL) 1.In this document Defining an AIDL Interface Create th ...
随机推荐
- 弄技术要弄通-公司reis的pub/sub怎么使用的呢?
Pub/Sub in Redis using PHP Posted on November 14, 2011by xmeng I would like to put an example togeth ...
- Registration system
Registration system 时间限制:1000 ms | 内存限制:65535 KB 难度:2 描写叙述 A new e-mail service "Berlandesk&q ...
- SQL 快速参考
SQL 快速参考 SQL 语句 语法 AND / OR SELECT column_name(s)FROM table_nameWHERE conditionAND|OR condition ALTE ...
- ASP.NET MVC 学习笔记-2.Razor语法 ASP.NET MVC 学习笔记-1.ASP.NET MVC 基础 反射的具体应用 策略模式的具体应用 责任链模式的具体应用 ServiceStack.Redis订阅发布服务的调用 C#读取XML文件的基类实现
ASP.NET MVC 学习笔记-2.Razor语法 1. 表达式 表达式必须跟在“@”符号之后, 2. 代码块 代码块必须位于“@{}”中,并且每行代码必须以“: ...
- c#Winform程序调用app.config文件配置数据库连接字符串 SQL Server文章目录 浅谈SQL Server中统计对于查询的影响 有关索引的DMV SQL Server中的执行引擎入门 【译】表变量和临时表的比较 对于表列数据类型选择的一点思考 SQL Server复制入门(一)----复制简介 操作系统中的进程与线程
c#Winform程序调用app.config文件配置数据库连接字符串 你新建winform项目的时候,会有一个app.config的配置文件,写在里面的<connectionStrings n ...
- Android 使用图片异步载入框架Universal Image Loader的问题
使用的Jar包 问题: optionsm = new DisplayImageOptions.Builder() .displayer(new RoundedBitmap ...
- 程序C++ to C#交互
第一次用C#调用C/C++生成的DLL文件,感觉有点新鲜,事实上仅仅是实现了执行在公共语言执行库 (CLR) 的控制之外的"非托管代码"(执行在公共语言执行库(CLR)的控制之中的 ...
- Python爬虫开发【第1篇】【Scrapy框架】
Scrapy 框架介绍 Scrapy是用纯Python实现一个为了爬取网站数据.提取结构性数据而编写的应用框架. Srapy框架,用户只需要定制开发几个模块就可以轻松的实现一个爬虫,用来抓取网页内容以 ...
- 网易新闻client(高仿)
近期整理了下自己曾经做过的项目,决定分享出来.本篇所展示的是仿网易新闻client,服务端是在新浪SAE部署着的.所以大家下载后,可直接在手机上看到效果.接下来看效果图: watermark/2/te ...
- 在webkit中如何避免触发layout(重排)
很多web开发者都已经意识到,在脚本执行中,DOM操作的用时可能比js本身执行时间要长很多,其中潜在的消耗基本上是由于触发了layout(即重排reflow:由DOM树构建为Render渲染树的过程) ...