提要
最近在Android 源码阅读与追踪中,跟踪代码Application -> Java Framework -> JNI -> Native C++的过程中,Native层涉及大量的进程间通信-Binder,实在是艰难理解,故通过分析一个Binder简单实例进行简单剖析,后续进一步通Android 子模块库进行实例分析。
本实例工程目录结构 (以Test命名):
- 接口端:ITestService.h、ITestService.cpp;
- 客户端:TestClient.cpp;
- 服务端:TestService.h、TestService.cpp;
1. 接口端
接口端主要是定义定义接口,主要包含BpTestService、BnTestService两个部分,其分别充当客户端与服务端的代理接口,流程可理解为:Client -> Bp -> Bn -> Service。
1.1 ITestService.h 头文件
#ifndef ITestService_H
#define ITestService_H
#include <binder/IInterface.h>
namespace android {
class ITestService : public IInterface { //定义一个服务接口类 ITestService,继承自IInterface
public:
DECLARE_META_INTERFACE(TestService); //声明一个TestService的接口
//该接口下定义两个简单函数,API声明
virtual int setSomething(int a) = 0; //虚函数定义
virtual int getSomething() = 0;
};
class BnTestService : public BnInterface<ITestService> { //定义一个服务端类 BnTestService,继承自BnInterface
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
}
#endif
1.2 ITestService.cpp
接口端核心文件,主要定义BpTestService、BnTestService这两个代理接口。
#include "ITestService.h"
#include <binder/Parcel.h>
#include <binder/IInterface.h>
#include <utils/Log.h>
#define LOG_NDEBUG 0
#define LOG_TAG "chenxf: IXXXXService"
namespace android {
//进程间通信代码,用于想service请求服务
enum {
SET_SOMETHING = IBinder::FIRST_CALL_TRANSACTION,
GET_SOMETHING,
};
/*------------------------------------Bp客户端代理接口定义 --------------------------------
*客服端通过调用transact函数向Bn发送调用请求和数据
*/
class BpTestService : public BpInterface<ITestService> { //派生类
public:
BpTestService(const sp<IBinder>& impl)
: BpInterface<ITestService>(impl) {
}
//接口中函数定义
virtual int setSomething(int a) {
ALOGD(" BpTestService::setSomething a = %d ", a);
//Parcel将要写入的数据,规整到一个连续的buffer内存中并记录数据属性,远端进程可接收后根据这些属性和读取顺序来克隆还原
Parcel data,reply;
data.writeInt32(a); //写入数据
remote()->transact(SET_SOMETHING,data,&reply); //remote()返回BpBinder对象
return reply.readInt32();
}
virtual int getSomething() {
ALOGD(" BpXXXXService::getSomething ");
Parcel data,reply;
data.writeInterfaceToken(IXXXXService::getInterfaceDescriptor());
remote()->transact(GET_SOMETHING,data,&reply);
return reply.readInt32();
}
};
//---------------------- interface--------------------
//实现了DECLARE_META_INTERFACE定义的虚函数,特别是asInterface! (IInterface.h)
IMPLEMENT_META_INTERFACE(TestService, "chenxf.binder.TestService");
//------------------------------------Bn服务端代理接口定义 --------------------------------
status_t BnTestService::onTransact ( //onTransact函数,处理proxy发来的调用
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags){
switch (code) {
case SET_SOMETHING: {
ALOGD("BnTestService::onTransact SET_SOMETHING ");
reply->writeInt32(setSomething((int) data.readInt32()));
return NO_ERROR;
} break;
case GET_SOMETHING: {
ALOGD("BnTestService::onTransact GET_SOMETHING ");
reply->writeInt32(getSomething());
return NO_ERROR;
} break;
}
return BBinder::onTransact(code, data, reply, flags);
}
}
2. 服务端
2.1 TestService.h
这是TestService的头文件,主要就是声明TestService,继承BnTestService。
#include "../interface/ITestService.h"
#include <binder/BinderService.h>
namespace android {
class TestService : public BinderService<TestService>, public BnTestService { //继承BnTestService
public:
TestService();
static const char* getServiceName() { return "TestService"; } //获取注册到ServiceManager的名字
virtual int setSomething(int a);
virtual int getSomething();
protected:
int myParam;
};
}
2.2 TestService.cpp
服务端主要代码,包含上述的具体实现函数
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
#include <utils/Log.h>
#include <binder/Parcel.h>
#include <binder/IPCThreadState.h>
#include <utils/threads.h>
#include <cutils/properties.h>
#include "TestService.h"
#define LOG_NDEBUG 0
#define LOG_TAG "chenxf: TestService"
namespace android {
TestService::TestService() {
myParam = 0;
}
//具体功能定义
int TestService::setSomething(int a) { //与BpTestService中定义的setSomething分属不同进程
ALOGD(" TestService::setSomething a = %d myParam %d", a, myParam);
myParam += a;
return 0;//OK
}
int TestService::getSomething() {
ALOGD("#TestService::getSomething myParam = %d", myParam);
return myParam;
}
}
2.3 注册
#include <binder/IPCThreadState.h>
#include <binder/ProcessState.h>
#include <binder/IServiceManager.h>
#include <utils/Log.h>
#include "XXXXService.h"
#define LOG_NDEBUG 0
#define LOG_TAG "chenxf: XXXXService-main"
#define EASY_START_BINDER_SERVICE 0
using namespace android;
int main(int argc, char** argv)
{
#if EASY_START_BINDER_SERVICE
//TestService实例化,向ServiceManager注册,其使用了父类BinderService的函数,使用了父类BinderService的函数
TestService::publishAndJoinThreadPool();
#else
sp<ProcessState> proc(ProcessState::self()); //打开binder驱动
sp<IServiceManager> sm(defaultServiceManager()); //获得ServiceManager的客户端,与ServiceManager通信(binder)
/********************************************/
//实例化TestService,并注册到TestService
sm->addService(String16(TestService::getServiceName()), new TestService());
/********************************************/
ProcessState::self()->startThreadPool(); //TestService创建一个Binder线程池
IPCThreadState::self()->joinThreadPool(); //把主线程加入Binder线程池,用来处理来自于clinet的通信请求
#endif
return 0;
}
3. 客户端
Client端如果想与Server端进行通信,必须通过Service Manager来实现,getService()。
#include <stdio.h>
#include "../interface/ITestService.h" //导入接口
#define LOG_NDEBUG 0
#define LOG_TAG "chenxf: Client-main"
using namespace android;
sp<ITestService> mTestService;
void initTestServiceClient() { //初始化
int count = 10;
if (mTestService == 0) {
sp<IServiceManager> sm = defaultServiceManager(); //打开binder驱动
sp<IBinder> binder;
do {
/********************************************************/
binder = sm->getService(String16("TestService")); //client获取ITestService的BpBinder对象
/********************************************************/
if (binder != 0)
break;
ALOGW("TestService not published, waiting...");
sleep(1); // 1 s
count++;
} while (count < 20);
//创建一个binder对象并返回, mTestService = new BpTestService(binder),将binder转换为BpTestService
mTestService = interface_cast<ITestService>(binder);
}
}
int main(int argc, char* argv[]) {
initTestServiceClient();
if(mTestService ==NULL) {
ALOGW("cannot find TestService");
return 0;
}
while(1) {
mTestService->setSomething(1); //BpTestserver调用远程server的接口setSomething()
sleep(1);
ALOGD("getSomething %d", mTestService->getSomething());
}
return 0;
}
流程总结
当客户端调用setSomething函数时,其代码走向为:
客户端:
- mTestService -> setSomething(1);
- Client.setSomething() -> BpTestService.setSomething();
- BpTestService数据打包,放置Parcel中;
- BpBinder.transact(); 向binder驱动写入数据
服务端: - 服务端的子线程通过执行executeCommand,不断的从binder驱动读取数据,如果发现是送给自己的,就处理数据,即执行了BBinder::transact,从而执行派生类BnTestService的onTransact。
- BnTestService.onTransact分析数据,发现有人要调用setSomething(即发送代号是SET_SOMETHING),于是乎,解包Parcel拿出函数参数,调用setSomething,其具体实现在TestService。
- TestService执行setSomething。