[转] Bound Service的三种方式(Binder、 Messenger、 AIDL)
首先要明白需要的情景,然后对三种方式进行选择:
(一)可以接收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
Binderclass and returning an instance of it fromonBind(). The client receives theBinderand can use it to directly access public methods available in either theBinderimplementation(得到Service对象,从而获取Service中的方法) or even theService. - 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 aHandlerthat responds to different types ofMessageobjects. ThisHandleris the basis for aMessengerthat can then share anIBinderwith the client, allowing the client to send commands to the service usingMessageobjects. Additionally, the client can define aMessengerof its own so the service can send messages back.This is the simplest way to perform interprocess communication (IPC), because the
Messengerqueues 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
Handlerthat receives a callback for each call from a client. - The
Handleris used to create aMessengerobject (which is a reference to theHandler). - The
Messengercreates anIBinderthat the service returns to clients fromonBind(). - Clients use the
IBinderto instantiate theMessenger(that references the service'sHandler), which the client uses to sendMessageobjects to the service. - The service receives each
Messagein itsHandler—specifically, in thehandleMessage()method.In this way, there are no methods for the client to call on the service. Instead, the client delivers messages (
Messageobjects) that the service receives in itsHandler.Messenger和AIDL的比较:
Compared to AIDL
When you need to perform IPC, using a
Messengerfor your interface is simpler than implementing it with AIDL, becauseMessenger
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'sonBind()method, which returns anIBinderfor interacting with the service.The binding is asynchronous.
bindService()returns immediately and does not return theIBinderto the client. To receive theIBinder, the client must create an instance ofServiceConnectionand pass it tobindService(). TheServiceConnectionincludes a callback method that the system calls to deliver theIBinder.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 withstopSelf()or another component callsstopService(), 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 returntrueif you would like to receive a call toonRebind()the next time a client binds to the service (instead of receiving a call toonBind()).onRebind()returns void, but the client still receives theIBinderin itsonServiceConnected()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.- Create the .aidl file
This file defines the programming interface with method signatures.
- Implement the interface
The Android SDK tools generate an interface in the Java programming language, based on your
.aidlfile. This interface has an inner abstract class namedStubthat extendsBinderand implements methods from your AIDL interface. You must extend theStubclass and implement the methods. - Expose the interface to clients
Implement a
Serviceand overrideonBind()to return your implementation of theStubclass.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:
- Create the .aidl file
- The service implements a
[转] Bound Service的三种方式(Binder、 Messenger、 AIDL)的更多相关文章
- OpenCV4Android释疑: 透析Android以JNI调OpenCV的三种方式(让OpenCVManager永不困扰)
OpenCV4Android释疑: 透析Android以JNI调OpenCV的三种方式(让OpenCVManager永不困扰) 前文曾详细探讨了关于OpenCV的使用,原本以为天下已太平.但不断有人反 ...
- android Service Activity三种交互方式(付源码)(转)
android Service Activity三种交互方式(付源码) Android应用服务器OSBeanthread android Service Binder交互通信实例 最下边有源代码: ...
- Service Activity三种交互方式
Service Activity三种交互方式 2012-09-09 22:52 4013人阅读 评论(2) 收藏 举报 serviceandroidimportclassthreadjava ...
- 【整理】Linux下中文检索引擎coreseek4安装,以及PHP使用sphinx的三种方式(sphinxapi,sphinx的php扩展,SphinxSe作为mysql存储引擎)
一,软件准备 coreseek4.1 (包含coreseek测试版和mmseg最新版本,以及测试数据包[内置中文分词与搜索.单字切分.mysql数据源.python数据源.RT实时索引等测 ...
- 【Java EE 学习 52】【Spring学习第四天】【Spring与JDBC】【JdbcTemplate创建的三种方式】【Spring事务管理】【事务中使用dbutils则回滚失败!!!??】
一.JDBC编程特点 静态代码+动态变量=JDBC编程. 静态代码:比如所有的数据库连接池 都实现了DataSource接口,都实现了Connection接口. 动态变量:用户名.密码.连接的数据库. ...
- angularjs 自定义服务的三种方式
angularjs 中可通过三种($provider,$factory,$service)方式自定义服务,以下是不同的实现形式: // 定义module , module中注入$providevar ...
- Linux中设置服务自启动的三种方式
有时候我们需要Linux系统在开机的时候自动加载某些脚本或系统服务 主要用三种方式进行这一操作: ln -s 在/etc/rc.d/rc*.d目录中建立/e ...
- [转]Linux中设置服务自启动的三种方式
from:http://www.cnblogs.com/nerxious/archive/2013/01/18/2866548.html 有时候我们需要Linux系统在开机的时候自动加载某些脚本或系统 ...
- 宿主机为linux、windows分别实现VMware三种方式上网(转)
一.VMware三种方式工作原理1 Host-only连接方式 让虚机具有与宿主机不同的各自独立IP地址,但与宿主机位于不同网段,同时为宿主主机新增一个IP地址,且保证该IP地址与各虚机IP地址位于 ...
随机推荐
- Ubuntu启动错误Checking Battery State的处理
一.问题描述 二.处理方法 方法一: 按下 ctrl + alt + F1,进入终端,使用管理员权限执行下列代码 sudo rm /etc/X11/xorg.conf sudo reboot 方法二: ...
- Warning: Invalid argument supplied for foreach()
经常对提交过来的数据进行双重循环,但是为空时会报错:Warning: Invalid argument supplied for foreach() 如下解决即可:foreach($data[$i] ...
- 需求分析Point
1.码段的查询结果的汇总值计算有问题.被删除的是否还算是被使用范围内呢?现在是即使废弃了也算使用的.这就有范围和重叠的问题,需要识别这种集合关系的数据好概念,并搞清楚他们的关系和概念.
- hello,world不使用ARC
main.m // // main.m // Hello // // Created by lishujun on 14-8-28. // Copyright (c) 2014年 lishujun. ...
- hadoop Yarn 编程API
客户端编程库: 所在jar包: org.apache.hadoop.yarn.client.YarnClient 使用方法: 1 定义一个YarnClient实例: private YarnClien ...
- 【Java】java基本知识
1.int与Integer的区别 int是基本数据类型,Integer是一个引用数据类型. e.g: int num = 100; // 不是对象 Integer i = 100; // 是对象 // ...
- Ecshop开发
http://www.cnblogs.com/xcxc/category/579565.html
- 【UVA10765】Doves and bombs (BCC求割点后联通块数量)
题目: 题意: 给了一个联通无向图,现在问去掉某个点,会让图变成几个联通块? 输出的按分出的从多到小,若相等,输出标号从小到大.输出M个. 分析: BCC求割点后联通块数量,Tarjan算法. 联通块 ...
- LINUX6.3下RHCS的安装文档
LINUX6.3下RHCS的安装及集群的配置文档 环境: 目前要给华为E6000系列的两个刀片安装RHCS,每一块刀片有两个业务网口和一个管理网口,但是看不见不物理网卡,而是连接到刀片自身携带的一个交 ...
- bzoj1014
动态询问LCP,所以我们不好用后缀数组考虑使用维护序列问题的splay+hash求LCP这里mark一下,hash求LCP常用mo=9875321自然溢出的话交上去莫名其妙WA了这里树上某节点hash ...