Service官方教程(9)绑定服务时的注意事项
Binding to a Service
Application components (clients) can bind to a service by calling bindService(). The Android system then calls the service's onBind() method, which returns an IBinder for interacting with the service.
The binding is asynchronous. bindService() returns immediately and does not return the IBinder to the client. To receive the IBinder, the client must create an instance of ServiceConnection and pass it to bindService(). The ServiceConnection includes a callback method that the system calls to deliver the IBinder.
Note: Only activities, services, and content providers can bind to a service—you cannot bind to a service from a broadcast receiver.
So, to bind to a service from your client, you must:
- Implement
ServiceConnection.Your implementation must override two callback methods:
onServiceConnected()- The system calls this to deliver the
IBinderreturned by the service'sonBind()method. onServiceDisconnected()- The Android system calls this when the connection to the service is unexpectedly lost, such as when the service has crashed or has been killed. This is not called when the client unbinds.
- Call
bindService(), passing theServiceConnectionimplementation. - When the system calls your
onServiceConnected()callback method, you can begin making calls to the service, using the methods defined by the interface. - To disconnect from the service, call
unbindService().If your client is still bound to a service when your app destroys the client, destruction causes the client to unbind. It is better practice to unbind the client as soon as it is done interacting with the service. Doing so allows the idle service to shut down. For more information about appropriate times to bind and unbind, see Additional Notes.
For example, the following snippet connects the client to the service created above by extending the Binder class, so all it must do is cast the returned IBinder to the LocalService class and request the LocalService instance:
LocalService mService;
private ServiceConnection mConnection = new ServiceConnection() {
// Called when the connection with the service is established
public void onServiceConnected(ComponentName className, IBinder service) {
// Because we have bound to an explicit
// service that is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
} // Called when the connection with the service disconnects unexpectedly
public void onServiceDisconnected(ComponentName className) {
Log.e(TAG, "onServiceDisconnected");
mBound = false;
}
};
With this ServiceConnection, the client can bind to a service by passing it to bindService(). For example:
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
- The first parameter of
bindService()is anIntentthat explicitly names the service to bind (thought the intent could be implicit). - The second parameter is the
ServiceConnectionobject. - The third parameter is a flag indicating options for the binding. It should usually be
BIND_AUTO_CREATEin order to create the service if its not already alive. Other possible values areBIND_DEBUG_UNBINDandBIND_NOT_FOREGROUND, or0for none.
Additional notes 注意事项
Here are some important notes about binding to a service:
- You should always trap
DeadObjectExceptionexceptions, which are thrown when the connection has broken. This is the only exception thrown by remote methods. - Objects are reference counted across processes.
进程间对象是 引用+引用计数 访问。
- You should usually pair the binding and unbinding during matching bring-up and tear-down moments of the client's lifecycle. For example:
- If you only need to interact with the service while your activity is visible, you should bind during
onStart()and unbind duringonStop(). - If you want your activity to receive responses even while it is stopped in the background, then you can bind during
onCreate()and unbind duringonDestroy(). Beware that this implies that your activity needs to use the service the entire time it's running (even in the background), so if the service is in another process, then you increase the weight of the process and it becomes more likely that the system will kill it.绑定与解绑成对出现,注意组件的生命周期。通常可以在onCreate中绑定,onDestory解绑.而不要在onResume,onPause中绑定,解绑。
Note: You should usually not bind and unbind during your activity's
onResume()andonPause(), because these callbacks occur at every lifecycle transition and you should keep the processing that occurs at these transitions to a minimum. Also, if multiple activities in your application bind to the same service and there is a transition between two of those activities, the service may be destroyed and recreated as the current activity unbinds (during pause) before the next one binds (during resume). (This activity transition for how activities coordinate their lifecycles is described in the Activities document.) - If you only need to interact with the service while your activity is visible, you should bind during
For more sample code, showing how to bind to a service, see the RemoteService.java class in ApiDemos.
Service官方教程(9)绑定服务时的注意事项的更多相关文章
- Service官方教程(5)后台服务发送通知、把服务变前台服务。
1.Sending Notifications to the User (发送通知) Once running, a service can notify the user of events usi ...
- 绑定服务时什么时候调用onRebind
Serivce中onRebind被调用的时机非常特别,想知道什么时候onRebind被调用,能够接以下的次序来学习.最后自然就明确了! 1. 首先要知道.同一个服务既可能被启动也能够被绑定; 2. S ...
- 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 ...
- Service官方教程(6)Bound Services主要用来实现通信服务,以及3种实现通信的方案简介。
1.Bound Services A bound service is the server in a client-server interface. A bound service allows ...
- Service官方教程(11)Bound Service示例之2-AIDL 定义跨进程接口并通信
Android Interface Definition Language (AIDL) 1.In this document Defining an AIDL Interface Create th ...
- Service官方教程(1)Started与Bound的区别、要实现的函数、声明service
Services 简介和分类 A Service is an application component that can perform long-running operations in the ...
- 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官方教程(10)Bound Service的生命周期函数
Managing the Lifecycle of a Bound Service When a service is unbound from all clients, the Android sy ...
随机推荐
- “约定优于配置”与Magento改造尝试四之block、helper和model载入
暂定本章为这个系列最后一章,还是继续沿用模块的别名(alias)概念 <modules> <Mage_Wishlist> <version>1.6.0.0</ ...
- Linux - Ubuntu中文输入法安装(Ubuntu 12.04)
Ubuntu中文输入法安装(Ubuntu 12.04) 本文地址:http://blog.csdn.net/caroline_wendy Ubuntu作为Linux常见的操作系统,是须要熟练使用的. ...
- robotframework接口自动化
robot framework框架在测试接口上比soapUI好用的多,在此介绍下get方法的HTTP接口,其实这个接口也是把POST数据作为参数进行get请求,使用post 方法也是一样,一共6步就可 ...
- 常用近百个js代码汇总
//檢查空串 function isEmpty(str){ )) return (true); else return(false); } //檢查是否未數字 function isDigit(the ...
- 【转载】企业服务总线Enterprise service bus介绍
企业服务总线(Enterprise service bus). 以往企业已经实现了很多服务, 构成了面向服务的架构,也就是我们常说的SOA. 服务的参与双方都必须建立1对1 的联系,让我们回顾一下SO ...
- wsdl2objc定制(一)namespace
1.问题抛出: 如今还是有非常多人使用 wsdl2objc 来调用webservice,可是有时候会有不开心的事情发生, <soap:Envelope xmlns:soap="http ...
- vmware10上安装mac os 10.9
来源地址:http://dtbuluo.com/blog/archives/350 序言: 前几天跟朋友开玩笑说,要不我们一起来学习一下swift编程语言吧~我们就抱着玩玩的态度,没有想过要做出什么优 ...
- 数据库建表参考(SQL Server)
(1).字段设置为Not Null+Default Value.原因:减少三值判断,可为Null的字段要多判断null:另外,定长字段为null也占空间,变长字段为空字符串也是不占空间,所以设置成 ...
- 2016/05/25 Ajax 跨域 转
起因: 起因是这样的,为了复用,减少重复开发,单独开发了一个用户权限管理系统,共其他系统获取认证与授权信息,暂且称之为A系统:调用A系统以B为例.在B系统 中用ajax调用A系统系统的接口(数据格式为 ...
- 剑指Offer面试题11(Java版):数值的整数次方
题目:实现函数double Power(double base,int exponent),求base的exponent次方.不得使用库函数,同一时候不须要考虑大数问题 1.自以为非常easy的解法: ...