> 文章列表 > Android的HIDL理解

Android的HIDL理解

Android的HIDL理解

安卓的HIDL和HAL在架构上的区别:

        HIDL(Hardware Interface Definition Language)和HAL(Hardware Abstraction Layer)是Android系统中用于实现硬件抽象层的两个关键技术。

HAL是Android系统中实现硬件抽象层的传统方法。它定义了一组抽象接口,这些接口将Android系统和底层硬件设备分离开来。HAL层将Android系统和底层硬件之间的交互进行封装,以使Android系统能够与各种硬件设备进行通信。

HIDL是HAL的升级版,其主要区别在于使用了IDL(Interface Definition Language)来定义接口,这使得HIDL接口更具可读性和可维护性。此外,HIDL支持将接口分成多个部分,以便只加载必要的部分,从而减少了启动时间和内存占用。

在架构上,HAL和HIDL的主要区别在于它们如何处理接口定义。HAL使用C/C++语言定义接口,而HIDL使用IDL语言定义接口。此外,HIDL在实现上使用了Binder驱动程序,这是一种Android系统中的进程间通信机制。这使得HIDL在跨进程通信方面更加灵活和高效,但也使得它的实现更加复杂。

安卓的HIDL的实现示例

下面是一个HIDL的实现示例:

1.定义HIDL接口:

// IMyHidlInterface.halpackage android.hardware.myhidlinterface;interface IMyHidlInterface {int myFunction(in int arg1, in int arg2, out int result);
};

2.生成HIDL的C++头文件:

$ hidl-gen -o /path/to/output -Lc++-headers IMyHidlInterface.hal

此命令将生成IMyHidlInterface.h和IMyHidlInterface.cpp文件,其中IMyHidlInterface.h文件包含了C++代码,以便将HIDL接口绑定到C++实现。

3.实现HIDL接口:

// MyHidlInterface.cpp#include <android/hardware/myhidlinterface/1.0/IMyHidlInterface.h>namespace android {
namespace hardware {
namespace myhidlinterface {
namespace V1_0 {
namespace implementation {using ::android::hardware::myhidlinterface::V1_0::IMyHidlInterface;
using ::android::hardware::Return;
using ::android::hardware::Void;struct MyHidlInterface : public IMyHidlInterface {Return<int32_t> myFunction(int32_t arg1, int32_t arg2) override {// 实现函数逻辑return arg1 + arg2;}
};}  // namespace implementation
}  // namespace V1_0
}  // namespace myhidlinterface
}  // namespace hardware
}  // namespace android

4.将HIDL接口实现注册到系统服务:

// MyHidlInterfaceService.cpp#include <android/hardware/myhidlinterface/1.0/IMyHidlInterface.h>#include "MyHidlInterface.h"using android::hardware::myhidlinterface::V1_0::IMyHidlInterface;
using android::hardware::myhidlinterface::V1_0::implementation::MyHidlInterface;int main() {// 获取IMyHidlInterface单例对象android::sp<IMyHidlInterface> myHidlInterface = MyHidlInterface::getInstance();if (myHidlInterface == nullptr) {ALOGE("Failed to get MyHidlInterface instance");return -1;}// 注册服务android::status_t status = myHidlInterface->registerAsService();if (status != android::OK) {ALOGE("Failed to register MyHidlInterface service");return -1;}ALOGI("MyHidlInterface service is running");// 阻塞等待服务停止android::hardware::joinRpcThreadpool();ALOGI("MyHidlInterface service is stopped");return 0;
}

5.编译和运行:

$ g++ -o MyHidlInterfaceService MyHidlInterfaceService.cpp MyHidlInterface.cpp \\-I/path/to/generated/include \\-L/path/to/hardware/interfaces/IMyHidlInterface/1.0/default/ \\-lhidltransport \\-lmyhidlinterface@1.0
$ ./MyHidlInterfaceService