C++实例讲解Binder通信

  binder是android里面的通信机制,这就不说它如何如何好了,Goog已经说过了,这里不多说。binder是一个面向对象的编程方法,大量使用虚函数类。最近研究binder看到一网友写的,就借鉴一下。这个例子很好的解释里binder通信关系。原文:http://blog.csdn.net/new_abc/article/details/8097775 例子不错不过就是没运行起来,不过这都不是问题,关键是很容易理解。

  我将他的源码整理类图看看,不过这个是简单的继承关系。

  

  基本上使用binder就这个关系,从中间一分为二,左边客户端使用,右边服务端。不管是客户端还是服务端都继承子IXXXService这个类,这个类可以裂解为客户端和服务端的“爷爷”,而“爷爷”继承IInterface,所有自定义的binder都必须继承这个类,这个是android强指针实现计数的方法。先看看源码后再理解这个图。

首先看下目录结构:

  TestBinderClient目录:  Android.mk  ITestBinderService.cpp

  TestBinderServer目录: Android.mk  ITestBinderService.h  main_testBinder.cpp  testBinder.cpp  TestBinderService.cpp  TestBinderService.h  

TestBinderClient下面是Binder的客户端,TestBinderServer是binder的服务端

我们先来看下biner服务端代码

1、ITestBinderService.h

 1     #ifndef ANDROID_ITESTBINDERSERVICE_H_  
 2     #define ANDROID_ITESTBINDERSERVICE_H_  
 3       
 4     #include <utils/RefBase.h>  
 5     #include <binder/IInterface.h>  
 6     #include <binder/Parcel.h>  
 7       
 8       
 9     namespace android {  
10       
11     class Parcel;  
12       
13     class ITestBinderService: public IInterface {  
14     public:  
15         DECLARE_META_INTERFACE(TestBinderService);  
16       
17         virtual int add(int a, int b) = 0;  
18     };  
19       
20     class BnTestBinderService: public BnInterface<ITestBinderService> {  
21     public:  
22         virtual status_t onTransact(uint32_t code, const Parcel& data,  
23                 Parcel* reply, uint32_t flags = 0);  
24     };  
25       
26     }  
27       
28     #endif /* ANDROID_ITESTBINDERSERVICE_H_ */  
ITestBinderService.h

      这里主要是定义了两个类ITestBinderService 和 BnTestBinderService,ITestBinderService 是TestBinderService 的基类,这里主要是DECLARE_META_INTERFACE 这个宏,定义在frameworks\base\include\binder\IInterface.h文件中。

1 #define DECLARE_META_INTERFACE(INTERFACE)                               \  
2     static const android::String16 descriptor;                          \  
3     static android::sp<I##INTERFACE> asInterface(                       \  
4             const android::sp<android::IBinder>& obj);                  \  
5     virtual const android::String16& getInterfaceDescriptor() const;    \  
6     I##INTERFACE();                                                     \  
7     virtual ~I##INTERFACE();   
DECLARE_META_INTERFACE 宏

把TestBinderService代入进去

1 #define DECLARE_META_INTERFACE(TestBinderService)                               \  
2     static const android::String16 descriptor;                          \  
3     static android::sp<ITestBinderService> asInterface(                       \  
4             const android::sp<android::IBinder>& obj);                  \  
5     virtual const android::String16& getInterfaceDescriptor() const;    \  
6     ITestBinderService();                                                     \  
7     virtual ~I##TestBinderService();  
带入宏后

其中封装了实现binder所需要的一些类成员变量和成员函数,通过这些成员函数可以为一个binder实现创建proxy(代理)

2、TestBinderService.h

 1     #ifndef ANDROID_TESTBINDERSERVICE_H_  
 2     #define ANDROID_TESTBINDERSERVICE_H_  
 3       
 4     #include <utils/KeyedVector.h>  
 5     #include "ITestBinderService.h"  
 6       
 7     namespace android {  
 8       
 9     class TestBinderService: public BnTestBinderService {  
10     public:  
11         static void instantiate();  
12         int add(int a,int b);  
13     private:  
14         TestBinderService();  
15         virtual ~TestBinderService();  
16     };  
17       
18     }  
19       
20     #endif /* ANDROID_TESTBINDERSERVICE_H_ */  
TestBinderService.h

这个文件比较简单,主要就是定义了一个类TestBinderService,继承于前面 的BnTestBinderService,并定义了一个方法add函数和instantiate

3、TestBinderService.cpp

 1     #define LOG_TAG "TestBinderService"  
 2     #include <utils/Log.h>  
 3     #include <binder/IServiceManager.h>  
 4     #include <binder/IPCThreadState.h>  
 5       
 6     #include "TestBinderService.h"  
 7     static int debug_flag = 1;  
 8     namespace android {  
 9       
10     void TestBinderService::instantiate() {  
11         LOGI("Enter TestBinderService::instantiate");  
12         status_t st = defaultServiceManager()->addService(  
13                 String16("my.test.binder"), new TestBinderService());  
14         LOGD("ServiceManager addService ret=%d", st);  
15         LOGD("instantiate> end");  
16     }  
17       
18     TestBinderService::TestBinderService() {  
19         LOGD(" TestBinderServicet");  
20     }  
21       
22     TestBinderService::~TestBinderService() {  
23         LOGD("TestBinderService destroyed,never destroy normally");  
24     }  
25       
26     int TestBinderService::add(int a,int b) {  
27       
28         LOGI("TestBinderService::add a = %d, b = %d.", a , b);    
29         return a+b;  
30     }  
31  
32  }  
TestBinderService.cpp

在instantiate函数中,将TestBinderService注册到系统的binder service列表中,这样以后就可以使用这个service提供的方法,该service提供了一个add 方法,返回两个数的和。

再来看下clinet端 的代码

1、ITestBinderService.cpp

 1     #define LOG_TAG "ITeeveePlayerService"  
 2       
 3     #include <utils/Log.h>  
 4       
 5     #include "../TestBinderServer/ITestBinderService.h"  
 6       
 7     namespace android {  
 8       
 9     enum {  
10         TEST_ADD = IBinder::FIRST_CALL_TRANSACTION,  
11     };  
12       
13     class BpTestBinderService: public BpInterface<ITestBinderService> {  
14     public:  
15         BpTestBinderService(const sp<IBinder>& impl) :  
16             BpInterface<ITestBinderService> (impl) {  
17         }  
18       
19         int add(int a, int b) {  
20               
21             Parcel data, reply;  
22             LOGI("Enter BpTestBinderService add,a = %d , b = %d", a, b);  
23             data.writeInterfaceToken(ITestBinderService::getInterfaceDescriptor());  
24             data.writeInt32(a);  
25             data.writeInt32(b);  
26             remote()->transact(TEST_ADD, data, &reply);  
27             int sum = reply.readInt32();  
28             LOGI("BpTestBinderService sum = %d", sum);  
29             return sum;  
30         }  
31     };  
32       
33     IMPLEMENT_META_INTERFACE(TestBinderService, "android.test.ITestBinderService");  
34       
35     // ----------------------------------------------------------------------  
36       
37     status_t BnTestBinderService::onTransact(uint32_t code, const Parcel& data,  
38             Parcel* reply, uint32_t flags) {  
39         switch (code) {  
40         case TEST_ADD: {  
41               
42             CHECK_INTERFACE(ITestBinderService, data, reply);  
43             int a = data.readInt32();  
44             int b = data.readInt32();  
45             LOGI("Enter BnTestBinderService add,a = %d , b = %d", a, b);  
46             int sum = 0;  
47             sum  = add(a, b);  
48             LOGI("BnTestBinderService sum = %d", sum);  
49              reply->writeInt32(sum);  
50             return sum;  
51         }  
52         default:  
53             return BBinder::onTransact(code, data, reply, flags);  
54         }  
55     }  
56       
57     }  
ITestBinderService.cpp

定义了一个类BpTestBinderService,提供add方法,该方法通过调用远端的binder service提供的服务返回两个数的和重载了BnTestBinderService的onTransact方法,使其在TEST_ADD时调用add方法

这个文件里面也使用了一个宏IMPLEMENT_META_INTERFACE,也是定义在frameworks\base\include\binder\IInterface.h文件中

 1     #define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                       \  
 2         const android::String16 I##INTERFACE::descriptor(NAME);             \  
 3         const android::String16&                                            \  
 4                 I##INTERFACE::getInterfaceDescriptor() const {              \  
 5             return I##INTERFACE::descriptor;                                \  
 6         }                                                                   \  
 7         android::sp<I##INTERFACE> I##INTERFACE::asInterface(                \  
 8                 const android::sp<android::IBinder>& obj)                   \  
 9         {                                                                   \  
10             android::sp<I##INTERFACE> intr;                                 \  
11             if (obj != NULL) {                                              \  
12                 intr = static_cast<I##INTERFACE*>(                          \  
13                     obj->queryLocalInterface(                               \  
14                             I##INTERFACE::descriptor).get());               \  
15                 if (intr == NULL) {                                         \  
16                     intr = new Bp##INTERFACE(obj);                          \  
17                 }                                                           \  
18             }                                                               \  
19             return intr;                                                    \  
20         }                                                                   \  
21         I##INTERFACE::I##INTERFACE() { }                                    \  
22         I##INTERFACE::~I##INTERFACE() { }   
IMPLEMENT_META_INTERFACE宏

代入展开后:

 1 #define IMPLEMENT_META_INTERFACE(TestBinderService, "android.test.ITestBinderService")                       \  
 2     const android::String16 ITestBinderService::descriptor("android.test.ITestBinderService");             \  
 3     const android::String16&                                            \  
 4             ITestBinderService::getInterfaceDescriptor() const {              \  
 5         return ITestBinderService::descriptor;                                \  
 6     }                                                                   \  
 7     android::sp<ITestBinderService> ITestBinderService::asInterface(                \  
 8             const android::sp<android::IBinder>& obj)                   \  
 9     {                                                                   \  
10         android::sp<ITestBinderService> intr;                                 \  
11         if (obj != NULL) {                                              \  
12             intr = static_cast<ITestBinderService*>(                          \  
13                 obj->queryLocalInterface(                               \  
14                         ITestBinderService::descriptor).get());               \  
15             if (intr == NULL) {                                         \  
16                 intr = new BpTestBinderService(obj);                          \  
17             }                                                           \  
18         }                                                               \  
19         return intr;                                                    \  
20     }                                                                   \  
21     ITestBinderService::ITestBinderService() { }                                    \  
22     ITestBinderService::~ITestBinderService() { } 
带入到宏后

这样,server和client端的binder代码主写好了,接着就需要把binder service加入到binder中

这里有两种方法:

1、在system_init.cpp中添加

TestBinderService::instantiate();

如果是在这里加的话可以去掉TestBinderService中实现的instantiate方法,同时将TestBinderService继 承自BinderService,因为在BinderService实现了这一方法,同时将其添加到binder service

2、以单独的程序启动

main_testBinder.cpp

 1     #include <binder/IPCThreadState.h>  
 2     #include <binder/ProcessState.h>  
 3     #include <binder/IServiceManager.h>  
 4     #include <utils/Log.h>  
 5       
 6       
 7     #include "TestBinderService.h"  
 8       
 9     using namespace android;  
10       
11     int main(int argc, char** argv)  
12      {  
13           
14         sp<ProcessState> proc(ProcessState::self());  
15         sp<IServiceManager> sm = defaultServiceManager();  
16         LOGI("TestBinderService before");  
17         TestBinderService::instantiate();  
18         LOGI("TestBinderService End");  
19         ProcessState::self()->startThreadPool();  
20         IPCThreadState::self()->joinThreadPool();  
21         return 0;  
22       
23     }  
将server添加到servermanage里面

这里调用的是TestBinderService自己的instantiate来添加的

再来看下测试testBinder.cpp

 1     #define LOG_TAG "TestBinserService"  
 2       
 3     #include <utils/Log.h>  
 4     #include <nativehelper/jni.h>  
 5     #include <nativehelper/JNIHelp.h>  
 6     #include <android_runtime/AndroidRuntime.h>  
 7     #include <binder/IServiceManager.h>  
 8     #include "../TestBinderServer/ITestBinderService.h"  
 9       
10       
11     #include "TestBinderService.h"  
12       
13     using namespace android;  
14       
15     int main(int argc, char** argv)  
16      {  
17         int sum = 0;  
18         sp<ITestBinderService> mTestBinserService;  
19         if (mTestBinserService.get() == 0) {  
20             sp<IServiceManager> sm = defaultServiceManager();  
21             sp<IBinder> binder;  
22             do {  
23                 binder = sm->getService(String16("my.test.binder"));  
24                 if (binder != 0)  
25                     break;  
26                     LOGI("getService fail");  
27                 usleep(500000); // 0.5 s  
28             } while (true);  
29             mTestBinserService = interface_cast<ITestBinderService> (binder);  
30             LOGE_IF(mTestBinserService == 0, "no ITestBinserService!?");  
31         }  
32         sum = mTestBinserService->add(3, 4);  
33         LOGI("sum = %d", sum);  
34         return 0;  
35       
36     }  
testBinder.cpp

以上就是测试代码。

转载于:https://www.cnblogs.com/winfu/p/5853586.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/373947.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2014编程之美初赛第一场

题目1 : 焦距 时间限制:2000ms单点时限:1000ms内存限制:256MB描述 一般来说&#xff0c;我们采用针孔相机模型&#xff0c;也就是认为它用到的是小孔成像原理。 在相机坐标系下&#xff0c;一般来说&#xff0c;我们用到的单位长度&#xff0c;不是“米”这样的国际单位&#x…

高中python公开课怎么上好_如何上好高中英语公开课

谈如何上好高中英语公开课对青年教师来说&#xff0c;开一节公开课&#xff0c;如同完成一次蜕变&#xff0c;累掉一层皮&#xff0c;有着刻骨铭心的阵痛&#xff0c;但换来的是突飞猛进的专业成长。可以说&#xff0c;公开课是青年教师培训的有效途径&#xff0c;是名师培养的…

Codeforces Round #261 (Div. 2) - E (459E)

题目连接&#xff1a;http://codeforces.com/contest/459/problem/E 题目大意&#xff1a;给定一张有向图&#xff0c;无自环无重边&#xff0c;每条边有一个边权&#xff0c;求最长严格上升路径长度。(1≤n&#xff0c;m≤3 *10^5) 初见此题觉得以边为点&#xff0c;以点为边&…

回收对象以提高性能

总览 在上一篇文章中&#xff0c;我说过对象反序列化更快的原因是由于使用了回收对象。 由于两个原因&#xff0c;这可能令人惊讶&#xff1a;1&#xff09;相信如今创建对象是如此之快&#xff0c;无关紧要或与回收自己一样快&#xff0c;2&#xff09;默认情况下&#xff0c;…

jquery GET POST

<!DOCTYPE html> <html> <head> <meta charset"UTF-8"> <head> <!--引入百度库--> <script src"http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <title></title> <scrip…

C++高精度运算类bign (重载操作符)

大数据操作&#xff0c;有如下问题&#xff1a; 计算&#xff1a;45678913561232654213212314875231656511323132 456789135612326542132123*14875231656511323132 比较&#xff1a;7531479535511335666686565>753147953551451213356666865 ? long long类型存储不了&…

oj系统格式错误_论文查重会不会检查格式?【paperpp吧】

高等学校一般都会要求大学生在毕业时需要写作毕业论文&#xff0c;并且会提前发出关于毕业论文的通知&#xff0c;在通知上一般会说明论文写作的相关要求&#xff0c;其中就会规定论文的相关格式。当然&#xff0c;学校也会在通知中说明论文查重的相关事宜&#xff0c;那么论文…

JavaScript Cookies

相关&#xff1a;jquery-cookie cookie 是存储于访问者的计算机中的变量&#xff0c;常用来存储用户名字&#xff0c;密码&#xff0c;日期&#xff0e; 示例&#xff1a; 1 document.cookie"usernameJohn Doe"; 2 document.cookie"usernameJohn Doe; expiresTh…

大数据 -- Hadoop集群搭建

Hadoop集群搭建 1.修改/etc/hosts文件 在每台linux机器上&#xff0c;sudo vim /etc/hosts 编写hosts文件。将主机名和ip地址的映射填写进去。编辑完后&#xff0c;结果如下&#xff1a; 2.配置ssh&#xff0c;实现无密码登录 四台虚拟机上&#xff0c;使用&#xff1a; ssh-ke…

通过示例休眠–第2部分(DetachedCriteria)

所以上次我们帮助正义联盟有效地管理了他们的超级英雄。 今天&#xff0c;我们集中讨论“复仇者联盟”将如何使用冬眠的“分离标准”找出每个超级英雄的敌人&#xff0c;以保护他们的超级英雄。 您可以从此处下载工作示例。 在此示例中&#xff0c;我们仅考虑两个实体。 复仇者…

2014编程之美初赛第二场

题目1 : 神奇的数列 时间限制:2000ms单点时限:1000ms内存限制:256MB描述 大神同学是一个热爱数字的孩子&#xff0c;她无时无刻不在思考生活与数学的联系。有一天&#xff0c;她发现其实公历的设计是有讲究的。 每4年就会多闰一天&#xff0c;每一百年又会有一年不是闰年&#…

usb大容量存储设备驱动_usb无法识别怎么办 如何解决usb识别故障【详细步骤】...

usb无法识别怎么办? 随着计算机硬件飞速发展&#xff0c;外围设备日益增多&#xff0c;键盘、鼠标等早已为人所共知&#xff0c;数码相机、MP3随身听接踵而至&#xff0c;这么多的设备&#xff0c;如何接入个人计算机?USB就是基于这个目的产生的。USB是一个使计算机周边设备连…

CSDN编程挑战——《交替字符串》

交替字符串 题目详情: 如果字符串str3能够由str1和str2中的字符按顺序交替形成&#xff0c;那么称str3为str1和str2的交替字符串。例如str1"abc"&#xff0c;str2"def"&#xff0c;那么"adbecf", "abcdef", "abdecf", "…

hdu-5834 Magic boy Bi Luo with his excited tree(树形dp)

题目链接&#xff1a; Magic boy Bi Luo with his excited tree Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 1037 Accepted Submission(s): 298 Problem DescriptionBi Luo is a magic boy, he also has …

Java EE过去,现在和云7

最近的JavaOne 2011的一个突出主题是下一个主要的Java EE 7版本。 正如主题发言中所述&#xff0c;有关工作正在进行中。 它将包含我们已经从先行者那里知道的28个规范以及一些新规范。 没人可以告诉您确切的号码&#xff0c;因为EE 7仅在“及时”完成时才会接受新的规范。 这意…

python cnn识别图像_笨方法学习CNN图像识别(一)—— 图片预处理

— 全文阅读5分钟 —在本文中&#xff0c;你将学习到以下内容&#xff1a;通过数据增强增加样本量调整图片大小便于网络训练前言图像识别的准备工作就是要对我们拿到手的样本图片进行预处理&#xff0c;具体就是数据增强和调整图片大小&#xff0c;这些准备工作都是为训练网络做…

随机数发生器

很多人喜欢用 rand()%n产生区间 [0,n]内的一个随机整数。姑且不论这样产生的整数是否仍然均匀分布&#xff0c;当 n大于 RAND_MAX 时&#xff0c;此法并不能得到期望的结果。由于RAND_MAX 很可能只是32767这么小&#xff0c;在使用此法时应当小心。 #include "stdio.h&quo…

Request和Response详解

转自&#xff1a;http://zhidao.baidu.com/link?url8BI0cjlcFdBSJKHTZlpo874eqtbTJoZfrh3miQgM_05RvSER8skPiBc1wSPZtXT8OGGCHfVXFAzAosa6E5HBl_ 内置对象request&#xff1a;请求对象request.getParameter("名字") 获得客户端输入的信息***************request.get…

将Maven与Ivy集成

问题是&#xff1a;您在Ivy存储库中&#xff08;只有那里&#xff09;有一些资源&#xff0c;您想在基于Maven的项目中使用这些资源。 可能的解决方案&#xff1a; 由于Ivy可以轻松使用Maven风格的存储库&#xff08;因此&#xff0c;您的Ivy客户端可以继续使用Ivy并进行一些微…

用python下载辞典

用python下载词源词典Etymoline Online Etymology Dictionary是最好的 English 词源词典&#xff0c;现在来说没有之一。但是&#xff0c;一直在PC上查单词有时不是很方便&#xff0c;遂就想怎么才能在手机上使用。现在的手机上的词典&#xff0c;除了BlueDict、MDict之外&…