namespace android
{
enum {
TRANSACTION_0 = IBinder::FIRST_CALL_TRANSACTION,
TRANSACTION_1,//...
};
class IXXX : public IInterface
{
public:
DECLARE_META_INTERFACE(XXX);
virtual void fun0(...) = 0;
virtual void fun1(...) = 0;
};
class BnXXX : public BnInterface<IXXX>
{
public:
virtual status_t onTransact(uint32_t code,const Parcel& data,Parcel* reply, uint32_t flags = 0);
}
class BpXXX : public BpInterface<IXXX>
{
public:
BpXXX(const sp<IBinder>& impl) : BpInterface<IXXX>(impl){}
void fun0(...){
Parcel data;
data.writeInterfaceToken(IXXX::getInterfaceDescriptor());
remote()->transact(TRANSACTION_0 ,data, NULL);
}
void fun1(...){
Parcel data;
data.writeInterfaceToken(IXXX::getInterfaceDescriptor());
remote()->transact(TRANSACTION_1 ,data, NULL);
}
//...
}
IMPLEMENT_META_INTERFACE(XXX, "android.test.IXXX"); // android/test/IXXX.aidl
status_t BnXXX::onTransact(uint32_t code,const Parcel& data,Parcel* reply, uint32_t flags)
{
switch(code) {
case TRANSACTION_0 :
CHECK_INTERFACE(IXXX,data,reply);
fun0();
return OK;
case TRANSACTION_1 :
CHECK_INTERFACE(IXXX,data,reply);
fun1();
return OK;
//...
}
return BBinder::onTransact(code,data,reply,flags);
}
};
Service例子:
IFooService.aidl
oneway interface IFooService{
void foo();
}
FooService.java //编译到services库中
import android.os.Binder;
import android.os.IBinder;
import java.io.IOException;
import IFooService;
public class FooService extends Binder{
private static final String TAG = "FooService";
private final Context mContext;
private FS fs;
public FooService(Context context){
mContext = context;
fs = new FS();
}
private final class FS extends IFooService.Stub{
public void foo(){
System.out.println("Call foo OK!");
}
}
}
IFooService.cpp
#include <stdint.h>
#include <sys/types.h>
#include <binder/Parcel.h>
#include <IFooService.h>
namespace android{
class BpFooService : public BpInterface<IFooService>{
public:
BpFooService(const sp<IBinder>& impl) : BpInterface<IFooService>(impl)
{
}
void foo()
{
Parcel data,reply;
data.writeInterfaceToken(IFooService::getInterfaceDescriptor());
data.writeInt32(1);
status_t result = remote()->transact(TRANSACTION_foo,data,&reply,IBinder::FLAY_ONLYWAY);
}
};
IMPLEMENT_META_INTERFACE(FooService,"IFooService");
};
IFooService.h
#ifndef ANDROID_IFOOSERVICE_H
#define ANDROID_IFOOSERVICE_H
#include <binder/IInterface.h>
#include <binder/IBinder.h>
namespace android {
enum {
TRANSACTION_foo = IBinder::FIRST_CALL_TRANSACTION,
};
class IFooService :: public IInterface{
public:
DECLARE_META_INTERFACE(FooService,"IFooService");
virtual void foo() = 0;
}
};
#endif
Android.mk
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES:= \
IFooService.cpp
LOCAL_STATIC_LIBRARIES := \
libutils \
libbinder
LOCAL_MODULE:= libfooservice
LOCAL_MODULE_TAGS := optional
include $(BUILD_STATIC_LIBRARY)