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