纯C++binder服务和客户端浅解

纯C++binder服务和客户端浅解

binder

Binder通信是Android用的比较多的一种通信机制,它是一种client-server的通信结构。Binder 是一种进程间通信机制,基于开源的 OpenBinder 实现;OpenBinder 起初由 Be Inc. 开发,后由 Plam Inc. 接手。从字面上来解释 Binder 有胶水、粘合剂的意思,顾名思义就是粘和不同的进程,使之实现通信。Binder 之复杂远远不是一篇文章就能说清楚的,网上Binder方面的资料非常多,此文仅是初学者对Binder的简单理解和使用.

源码

目录结构在这里插入图片描述
bindertest目录下的Android.mk

Android.mk

include $(call all-subdir-makefiles)

binderlib目录下,ITestClient下面是Binder的客户端,ITestService是binder的服务端
ITestClient.cpp

#define LOG_TAG "ITestClient"
#include <utils/Log.h>
#include <stdint.h>
#include <sys/types.h>
#include <binder/Parcel.h>
#include <ITestClient.h>

#include "../include/debug.h"

namespace xxxxx {
   
   

using namespace android;

	enum {
   
   
		IO_CONFIG_CHANGED = IBinder::FIRST_CALL_TRANSACTION,
		CALL_CHANGE,
	};

	class BpTestClient : public BpInterface<ITestClient> {
   
   
		public:
			BpTestClient(const sp<IBinder>& impl)
				: BpInterface<ITestClient>(impl)
			{
   
   
			}
	};

	IMPLEMENT_META_INTERFACE(TestClient, "android.xxxxx.ITestClient");
	
	status_t BnTestClient::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
   
   
		switch(code) 
		{
   
   
			case CALL_CHANGE:
			{
   
   
				return NO_ERROR;
			}
			default:
				return BBinder::onTransact(code, data, reply, flags);
		}
	}

}; // namespace android

ITestService.cpp

#define LOG_TAG "##Test binder##"
#include "utils/Log.h"
#include <utils/String16.h>
#include <stdarg.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
#include <Test.h>
#include <ITest.h>
#include <ITestClient.h>
#include <binder/MemoryHeapBase.h>
#include <binder/IMemory.h>

#include "../include/debug.h"

namespace xxxxx{
   
   

	using namespace android;

	enum {
   
   
		OPEN_TEST_DEVICE = IBinder::FIRST_CALL_TRANSACTION,
	};
	
	class BpTest :public BpInterface<ITest>
	{
   
   
		public:
		  	BpTest(const sp<IBinder>& impl): BpInterface<ITest>(impl){
   
   
		  	}
					
			virtual int binsertest(int num)
		    {
   
   
				Parcel data, reply;
				data.writeInt32(num);
		        remote()->transact(OPEN_TEST_DEVICE, data, &reply);
		        int status = reply.readInt32();
		        return status;
		    }
	};

	IMPLEMENT_META_INTERFACE(Test, "android.xxxxx.Test");
	
	status_t BnTest::
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值