android native(C++)层的service 一般都会用到binder,通过binder的机制对外提供接口,如果我们需要实现一个native 层的service,那么要怎么做呢?
这个基本上是一个固定的套路,所以我们需要先了解一下android 提供的binder (框架?)的关系。XXXService就是要基于binder通信的类。
例如要实现一个TestService
1、ITestService.h
#ifndef ANDROID_HXIONG_ITEST_H
#define ANDROID_HXIONG_ITEST_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <binder/IInterface.h>
namespace android {
class ITestService : public IInterface
{
public:
DECLARE_META_INTERFACE(ITestService);
virtual status_t test(int api) = 0;
};
// ----------------------------------------------------------------------------
class BnTestService : public BnInterface<ITestService>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif
2、ITestService.cpp
#include <binder/Parcel.h>
#include <binder/IInterface.h>
#include <ITestService.h>
namespace android {
// ----------------------------------------------------------------------------
enum {
TEST = IBinder::FIRST_CALL_TRANSACTION,
}
class BpTestService : public BpInterface<ITestService>
{
BpTestService()
{
}
virtual ~BpTestService();
virtual status_t test(int api) {
Parcel data, reply;
data.writeInterfaceToken(ITestService::getInterfaceDescriptor());
data.writeInt32(api);
remote()->transact(TEST, data, &reply);
result = reply.readInt32();
return result;
}
};
IMPLEMENT_META_INTERFACE(TestService, "com.hxiong.ITestService");
status_t BnTestService::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch(code) {
case TEST: {
CHECK_INTERFACE(ITestService, data, reply);
int api = data.readInt32();
int result=test(api); //这里会调用到TestService 的test函数
reply->writeInt32(result);
return NO_ERROR;
}
}
return BBinder::onTransact(code, data, reply, flags);
}
3、TestService.h
#ifndef ANDROID_HXIONFG_TEST_H
#define ANDROID_HXIONFG_TEST_H
#include <ITestService.h>
namespace android {
class TestService : public BnTestService{
public:
TestService();
virtual ~TestService();
virtual status_t test(int api);
};
}
#endif
4、TestService.cpp
#include <TestService.h>
namespace android {
TestService::TestService(){}
TestService::~TestService() {}
status_t TestService::test(int api){
return 0;
}
}