目录
实现BpDeviceMac和BnDeviceMac::onTransact()
定义Binder接口
要实现跨进程, 自然是使用Binder了, 因此我们首先要定义一个用于跨进程的接口, 我们通过一个读取和设置蓝牙地址的例子为例, 来讲解具体实现方法, 接口名为IDeviceMac
, 代码如下,
IDeviceMac.h
#ifndef XTC_IDEVICEMAC_H
#define XTC_IDEVICEMAC_H
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <utils/String8.h>
#include <android/log.h>
#ifdef TAG
#undef TAG
#endif
#define TAG "DeviceMac"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG ,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG ,__VA_ARGS__)
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,TAG ,__VA_ARGS__)
namespace android {
class IDeviceMac : public IInterface {
public:
enum {
SET_BT_MAC = IBinder::FIRST_CALL_TRANSACTION,
GET_BT_MAC,
};
virtual int setBTMac(String8 bt) = 0;
virtual String8 getBTMac() = 0;
DECLARE_META_INTERFACE(DeviceMac);
};
//-------------------------------------------
class BnDeviceMac : public BnInterface<IDeviceMac> {
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags);
};
} // end namespace android
#endif
代码很简单, 定义一个类继承自IInterface, 里面接口就是我们自己要用到的, 其中DECLARE_META_INTERFACE(DeviceMac);是一个宏定义, 用来定义继承IInterface必须实现的两个方法, 具体是什么方法后面接口实现部分讲
可以看到我们定义IDeviceMac后, 还定义了一个类BnDeviceMac,这个是Binder调用的一个规范, 即定义Ixxx接口后,
Bpxxx表示Client端接口,
Bnxxx表示Service端接口,
Bpxxx和Bnxxx都需要我们去实现具体内容,
并且Bnxxx和Bpxxx中的方法和Ixxx中的方法是一一对应的
实现BpDeviceMac和BnDeviceMac::onTransact()
IDeviceMac.cpp
#include "IDeviceMac.h"
namespace android {
class BpDeviceMac : public