首先要明白需要的情景,然后对三种方式进行选择:

(一)可以接收Service的信息(获取Service中的方法),但不可以给Service发送信息

(二) 使用Messenger既可以接受Service消息,也可以发送Service消息。但是无法调用Service中的方法。因为利用Message,所以不用担心并发

Extending the Binder class
If your service is private to your own application and runs in the same process as the client (which is common), you should create your interface by extending the Binder class and returning an instance of it from onBind(). The client receives the Binder and can use it to directly access public methods available in either the Binder implementation(得到Service对象,从而获取Service中的方法) or even the Service.
This is the preferred technique when your service is merely a background worker for your own application. The only reason you would not create your interface this way is because your service is used by other applications or across separate processes.
Service代码如下:
Activity代码如下:
 
Using a Messenger
If you need your interface to work across different processes, you can create an interface for the service with a Messenger. In this manner, the service defines a Handler that responds to different types of Message objects. This Handler is the basis for a Messenger that can then share an IBinder with the client, allowing the client to send commands to the service using Message objects. Additionally, the client can define a Messenger of its own so the service can send messages back.

This is the simplest way to perform interprocess communication (IPC), because the Messenger queues all requests into a single thread so that you don't have to design your service to be thread-safe.

If you need your service to communicate with remote processes, then you can use a Messenger
to provide the interface for your service. This technique allows you to
perform interprocess communication (IPC) without the need to use AIDL.

Here's a summary of how to use a Messenger:

  • The service implements a Handler that receives a callback for each call from a client.
  • The Handler is used to create a Messenger object (which is a reference to the Handler).
  • The Messenger creates an IBinder that the service returns to clients from onBind().
  • Clients use the IBinder to instantiate the Messenger (that references the service's Handler), which the client uses to sendMessage objects to the service.
  • The service receives each Message in its Handler—specifically, in the handleMessage() method.

    In this way, there are no methods for the client to call on the service. Instead, the client delivers messages (Message objects) that the service receives in its Handler.

    Messenger和AIDL的比较:

    Compared to AIDL

    When you need to perform IPC, using a Messenger for your interface is simpler than implementing it with AIDL, because Messenger
    queues all calls to the service, whereas, a pure AIDL interface sends
    simultaneous requests to the service, which must then handle
    multi-threading.

    For most applications, the service doesn't need to perform multi-threading, so using a Messengerallows
    the service to handle one call at a time. If it's important that your
    service be multi-threaded, then you should use AIDL to define your
    interface.

    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.

    Managing the Lifecycle of a Bound Service


    When a service is unbound from all clients, the Android system destroys it (unless it was also started with onStartCommand()).
    As such, you don't have to manage the lifecycle of your service if it's
    purely a bound service—the Android system manages it for you based on
    whether it is bound to any clients.

    However, if you choose to implement the onStartCommand() callback method, then you must explicitly stop the service, because the service is now considered to be started. In this case, the service runs until the service stops itself with stopSelf() or another component calls stopService(), regardless of whether it is bound to any clients.

    Additionally, if your service is started and accepts binding, then when the system calls your onUnbind()method, you can optionally return true if you would like to receive a call to onRebind() the next time a client binds to the service (instead of receiving a call to onBind()). onRebind() returns void, but the client still receives the IBinder in its onServiceConnected() callback. Below, figure 1 illustrates the logic for this kind of lifecycle.

    (三) 使用AIDL (1.不需要IPC:implement a Binder; 2.需要IPC,不需要并发:use a Messenger;
    3.需要IPC,需要并发:AIDL) Using AIDL is necessary only if you allow clients
    from different applications to access your service for IPC and want to
    handle multithreading in your service. If you do not need to perform
    concurrent IPC across different applications, you should create your
    interface by implementing a Binder or, if you want to perform IPC, but
    do not need to handle multithreading, implement your interface using a
    Messenger.

    1. Create the .aidl file

      This file defines the programming interface with method signatures.

    2. Implement the interface

      The Android SDK tools generate an interface in the Java programming language, based on your .aidl file. This interface has an inner abstract class named Stub that extends Binder and implements methods from your AIDL interface. You must extend the Stub class and implement the methods.

    3. Expose the interface to clients

      Implement a Service and override onBind() to return your implementation of the Stub class.

      IRemoteService.aidl文件:

      // IRemoteService.aidl
      package com.example.boundservice; // Declare any non-default types here with import statements /** Example service interface */
      interface IRemoteService {
      /** Request the process ID of this service, to do evil things with it. */
      int getPid(); /** Demonstrates some basic types that you can use as parameters
      * and return values in AIDL.
      */
      void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
      double aDouble, String aString);
      }

      自动生成(eclipse自动,studio需要rebuild)的IRemoteService.java:

[转] Bound Service的三种方式(Binder、 Messenger、 AIDL)的更多相关文章

  1. OpenCV4Android释疑: 透析Android以JNI调OpenCV的三种方式(让OpenCVManager永不困扰)

    OpenCV4Android释疑: 透析Android以JNI调OpenCV的三种方式(让OpenCVManager永不困扰) 前文曾详细探讨了关于OpenCV的使用,原本以为天下已太平.但不断有人反 ...

  2. android Service Activity三种交互方式(付源码)(转)

    android Service Activity三种交互方式(付源码) Android应用服务器OSBeanthread  android Service Binder交互通信实例 最下边有源代码: ...

  3. Service Activity三种交互方式

    Service Activity三种交互方式 2012-09-09 22:52 4013人阅读 评论(2) 收藏 举报 serviceandroidimportclassthreadjava     ...

  4. 【整理】Linux下中文检索引擎coreseek4安装,以及PHP使用sphinx的三种方式(sphinxapi,sphinx的php扩展,SphinxSe作为mysql存储引擎)

          一,软件准备 coreseek4.1 (包含coreseek测试版和mmseg最新版本,以及测试数据包[内置中文分词与搜索.单字切分.mysql数据源.python数据源.RT实时索引等测 ...

  5. 【Java EE 学习 52】【Spring学习第四天】【Spring与JDBC】【JdbcTemplate创建的三种方式】【Spring事务管理】【事务中使用dbutils则回滚失败!!!??】

    一.JDBC编程特点 静态代码+动态变量=JDBC编程. 静态代码:比如所有的数据库连接池 都实现了DataSource接口,都实现了Connection接口. 动态变量:用户名.密码.连接的数据库. ...

  6. angularjs 自定义服务的三种方式

    angularjs 中可通过三种($provider,$factory,$service)方式自定义服务,以下是不同的实现形式: // 定义module , module中注入$providevar ...

  7. Linux中设置服务自启动的三种方式

    有时候我们需要Linux系统在开机的时候自动加载某些脚本或系统服务 主要用三种方式进行这一操作: ln -s                       在/etc/rc.d/rc*.d目录中建立/e ...

  8. [转]Linux中设置服务自启动的三种方式

    from:http://www.cnblogs.com/nerxious/archive/2013/01/18/2866548.html 有时候我们需要Linux系统在开机的时候自动加载某些脚本或系统 ...

  9. 宿主机为linux、windows分别实现VMware三种方式上网(转)

    一.VMware三种方式工作原理1 Host-only连接方式  让虚机具有与宿主机不同的各自独立IP地址,但与宿主机位于不同网段,同时为宿主主机新增一个IP地址,且保证该IP地址与各虚机IP地址位于 ...

随机推荐

  1. WebApi(四)-Post接口请求失败或接受不到参数(解决方法)

    post方式只能接受一个参数而且必须用FromBody特性标识,所以当没有使用FromBody特性标识的时候就会请求失败,如有添加添加了那访问接口时候参数应传对象不能是key:val的格式否则会接收到 ...

  2. sqlserver 学习

    http://www.cnblogs.com/CareySon/category/411344.html SQL Server查找的最小单位实际上是页.也就是说即使你只查找一行很小的数据,SQL Se ...

  3. [BZOJ 1053] [HAOI 2007] 反素数ant

    题目链接:BZOJ 1053 想一想就会发现,题目让求的 1 到 n 中最大的反素数,其实就是 1 到 n 中因数个数最多的数.(当有多于一个的数的因数个数都为最大值时,取最小的一个) 考虑:对于一个 ...

  4. Gogs:可能是比Gitlab更好的选择

    Gitlab是一个很棒的Git托管服务,几乎像GitHub一样强大. 但是,有没有能和Gitlab/Github媲美但操作更简单的项目呢?我认为 Gogs 是很好的选择. 简介 现在,GitHub已经 ...

  5. Android中关于List与Json转化问题

    比如 List<String>list=new ArrayList<String>(); list.add("test1"); list.add(" ...

  6. c++复习基础要点02 虚函数与模板 与static inline是否共存

    1.      虚函数能否定义为模板函数 当一个类有虚函数时,它一定有一个虚表,用来纪录每个虚函数的实际地址.这也就是说这个虚表的大小是在编译期就确定了的.有多少个虚函数,虚表就纪录几个.       ...

  7. java.sql.SQLException: Can not issue executeUpdate() for SELECTs

    未处理的多个select语句 解决方法就是:查看有没有用了同一个连接来处理多个SQL语句!

  8. 14.8.2 Role of the .frm File for InnoDB Tables InnoDB 表得到 .frm文件的作用

    14.8.2 Role of the .frm File for InnoDB Tables InnoDB 表得到 .frm文件的作用 Vsftp:/data01/mysql/zjzc# ls -lt ...

  9. bzoj2821

    其实和bzoj2724是一样的都是先处理多个块的答案,然后多余部分暴力空间要注意一下,还是O(nsqrt(n)); ..,..] of longint; g:..,..] of longint; a, ...

  10. Spring - Sring MVC入门

    2.1.Spring Web MVC是什么 Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职 ...