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:

  1. Implement ServiceConnection.

    Your implementation must override two callback methods:

    onServiceConnected()
    The system calls this to deliver the IBinder returned by the service's onBind() 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.
  2. Call bindService(), passing the ServiceConnection implementation.
  3. When the system calls your onServiceConnected() callback method, you can begin making calls to the service, using the methods defined by the interface.
  4. 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);

Additional notes 注意事项

  Here are some important notes about binding to a service:

  • You should always trap DeadObjectException exceptions, which are thrown when the connection has broken. This is the only exception thrown by remote methods.

    捕获DeadObjectException异常
  • 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 during onStop().
    • If you want your activity to receive responses even while it is stopped in the background, then you can bind during onCreate() and unbind during onDestroy(). 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() and onPause(), 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.)

  For more sample code, showing how to bind to a service, see the RemoteService.java class in ApiDemos.

Service官方教程(9)绑定服务时的注意事项的更多相关文章

  1. Service官方教程(5)后台服务发送通知、把服务变前台服务。

    1.Sending Notifications to the User (发送通知) Once running, a service can notify the user of events usi ...

  2. 绑定服务时什么时候调用onRebind

    Serivce中onRebind被调用的时机非常特别,想知道什么时候onRebind被调用,能够接以下的次序来学习.最后自然就明确了! 1. 首先要知道.同一个服务既可能被启动也能够被绑定; 2. S ...

  3. Service官方教程(4)两种Service的生命周期函数

    Managing the Lifecycle of a Service The lifecycle of a service is much simpler than that of an activ ...

  4. Service官方教程(2)*IntentService与Service示例、onStartCommand()3个返回值的含义。

    1.Creating a Started Service A started service is one that another component starts by calling start ...

  5. Service官方教程(6)Bound Services主要用来实现通信服务,以及3种实现通信的方案简介。

    1.Bound Services A bound service is the server in a client-server interface. A bound service allows ...

  6. Service官方教程(11)Bound Service示例之2-AIDL 定义跨进程接口并通信

    Android Interface Definition Language (AIDL) 1.In this document Defining an AIDL Interface Create th ...

  7. Service官方教程(1)Started与Bound的区别、要实现的函数、声明service

    Services 简介和分类 A Service is an application component that can perform long-running operations in the ...

  8. Service官方教程(8)Bound Service示例之2-跨进程使用Messenger

    Compared to AIDL When you need to perform IPC, using a Messenger for your interface is simpler than ...

  9. Service官方教程(10)Bound Service的生命周期函数

    Managing the Lifecycle of a Bound Service When a service is unbound from all clients, the Android sy ...

随机推荐

  1. Hadoop-异常-Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/avro/io/DatumReader

    //maven org.apache.avr 下载不完全 ,去maven   If you are using maven to build your jar, you need to add the ...

  2. react-document-title

    根据不同的路由改变文档的title 使用该组件: import ReactDocumentTitle from 'path/ReactDocumentTitle' render() { return ...

  3. 三. 200多万元得到的创业教训--创业并不须要app

    摘要:有个点子,研发app或站点,推广,不断改进,探索盈利模式.这个通用的移动互联网创业流程.但我觉得.在某些特定的商业模式下,"研发app或站点"这步能够砍掉或推迟. 健生干货分 ...

  4. [LeetCode][Java] Remove Duplicates from Sorted List II

    题意: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct  ...

  5. 【iOS系列】-iOS查看沙盒文件图文教程(真机+模拟器)

    [iOS系列]-iOS查看沙盒文件图文教程(真机+模拟器) 1:模拟器 1.1 方法1: 程序中打印一下的地址,能直接前往沙盒路径. NSString *path = [NSSearchPathFor ...

  6. 2016/4/17 去除 ul ol 前标记 list-style:none list-style-type:none

    对于很多人用div来做网站时,总会用到,但在显示效果时前面总是会有一个小黑点,这个令很多人头痛,但又找不到要源,其它我们可以用以下方法来清除. 1.在CSS中写入代码.找到相关性的CSS,在..li和 ...

  7. JSON使用总结

    参考网站 官网: http://www.json.org/ 菜鸟教程:http://www.runoob.com/json/json-tutorial.html 什么是 JSON ? JSON 指的是 ...

  8. unix2dos/dos2unix

    dos2unix命令用来将DOS格式的文本文件转换成UNIX格式的(DOS/MAC to UNIX text file format converter).DOS下的文本文件是以\r\n作为断行标志的 ...

  9. ubuntu字符界面下显示中文和调整分辨率

    1.sudo apt-get install zhcon 2.vi /etc/zhcon.conf  修改下面两行 x_resolution 1024 y_resolution 768 完成这两步后在 ...

  10. RDD变换

    对Key/Value型RDD进行变换 groupBy按Key汇聚 fruit,applevegetable,cucumberfruit,cherryvegetable,beanfruit,banana ...