C++ binder 实现自定义Android Native Service

目录

定义Binder接口

实现BpDeviceMac和BnDeviceMac::onTransact()

BnDeviceMac实现(Service)

启动Service和Client端调用

编译

Java端调用


定义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
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值