以截屏功能为例,分析一下Android中Binder通信的流程。
class ISurfaceComposer: public IInterface {
DECLARE_META_INTERFACE(SurfaceComposer);
// flags for setTransactionState()
enum {
eSynchronous = 0x01,
eAnimation = 0x02,
};
enum {
eDisplayIdMain = 0,
eDisplayIdHdmi = 1
};
enum Rotation {
eRotateNone = 0,
eRotate90 = 1,
eRotate180 = 2,
eRotate270 = 3
};
...
/* Capture the specified screen. requires READ_FRAME_BUFFER permission.
* This function will fail if there is a secure window on screen.
*/
virtual status_t captureScreen(const sp<IBinder>& display,
const sp<IGraphicBufferProducer>& producer,
Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
uint32_t minLayerZ, uint32_t maxLayerZ,
bool useIdentityTransform,
Rotation rotation = eRotateNone) = 0;
...
};
其中宏
1. DECLARE_META_INTERFACE
2. IMPLEMENT_META_INTERFACE
3. CHECK_INTERFACE
三个宏定义在Binder库中,如下:
#define DECLARE_META_INTERFACE(INTERFACE) \
static const android::String16 descriptor; \
static android::sp<I##INTERFACE> asInterface( \
const android::sp<android::IBinder>& obj); \
virtual const android::String16& getInterfaceDescriptor() const; \
I##INTERFACE(); \
virtual ~I##INTERFACE(); \
#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME) \
const android::String16 I##INTERFACE::descriptor(NAME); \
const android::String16& \
I##INTERFACE::getInterfaceDescriptor() const { \
return I##INTERFACE::descriptor; \
} \
android::sp<I##INTERFACE> I##INTERFACE::asInterface( \
const android::sp<android::IBinder>& obj) \
{ \
android::sp<I##INTERFACE> intr; \
if (obj != NULL) { \
intr = static_cast<I##INTERFACE*>( \
obj->queryLocalInterface( \
I##INTERFACE::descriptor).get()); \
if (intr == NULL) { \
intr = new Bp##INTERFACE(obj); \
} \
} \
return intr; \
} \
I##INTERFACE::I##INTERFACE() { } \
I##INTERFACE::~I##INTERFACE() { } \
#define CHECK_INTERFACE(interface, data, reply) \
if (!data.checkInterface(this)) { return PERMISSION_DENIED; } \
那么宏DECLARE_META_INTERFACE(SurfaceComposer)展开就是:
static const android::String16 descriptor;
static android::sp<ISurfaceComposer> asInterface(
const android::sp<android::IBinder>& obj);
virtual const android::String16& getInterfaceDescriptor() const;
ISurfaceComposer();
virtual ~ISurfaceComposer();
对应的实现就是:
const android::String16 ISurfaceComposer::descriptor("android.ui.ISurfaceComposer");
const android::String16& ISurfaceComposer::getInterfaceDescriptor() const {
return ISurfaceComposer::descriptor;
}
android::sp<ISurfaceComposer> ISurfaceComposer::asInterface(
const android::sp<android::IBinder>& obj)
{
android::sp<ISurfaceComposer> intr;
if (obj != NULL) {
intr = static_cast<ISurfaceComposer*>(
obj->queryLocalInterface(ISurfaceComposer::descriptor).get()
);
if (intr == NULL) {
intr = new BpSurfaceComposer(obj);
}
}
return intr;
}
ISurfaceComposer:: ISurfaceComposer(){ }
ISurfaceComposer::~ISurfaceComposer() { }