android hidl
1、定义.hal接口文件,如:
在vendor/sprd/interface中新建目录hello,其中定义好hidl接口,如:
1 package vendor.sprd.hardware.hello@1.0; 2 3 interface IHello { 4 5 helloWorld(string name) generates (string result); 6 7 };
2、利用hidl-gen工具生成通信框架及业务类模板
# PACKAGE=vendor.sprd.hardware.hello@1.0
# LOC=vendor/sprd/interfaces/hello/1.0/default/
# hidl-gen -o $LOC -Lc++-impl -r vendor.sprd.hardware:vendor/sprd/interfaces -r android.hidl:system/libhidl/transport $PACKAGE
# hidl-gen -o $LOC -Landroidbp-impl -r vendor.sprd.hardware:vendor/sprd/interfaces -r android.hidl:system/libhidl/transport $PACKAGE
这样在default下,可见新生成Hello.cpp Hello.h文件,此为我们将要实现的业务逻辑类
1 struct Hello : public IHello { 2 // Methods from ::vendor::sprd::hardware::hello::V1_0::IHello follow. 3 Return<void> helloWorld(const hidl_string& name, helloWorld_cb _hidl_cb) override; 4 5 // Methods from ::android::hidl::base::V1_0::IBase follow. 6 7 }; 8 9 // FIXME: most likely delete, this is only for passthrough implementations 10 // extern "C" IHello* HIDL_FETCH_IHello(const char* name);
在Hello.cpp中实现之
3、运行业务逻辑,上面的Hello.cpp代码需要在进程中运行,所以需要新建一个
创建文件service.cpp、vendor.sprd.hardware.hello@1.0-service.rc,
上面的业务类可以编译成so加载到此进程中,也可以把代码直接编译成bin文件运行。这里采取前者
bp文件如下:
1 cc_binary {
2 name: "vendor.sprd.hardware.hello@1.0-service",
3 init_rc: ["vendor.sprd.hardware.hello@1.0-service.rc"],
4 relative_install_path: "hw",
5 vendor: true,
6
7 srcs: [
8 "Hello.cpp",
9 "service.cpp"
10 ],
11
12 shared_libs: [
13 "libcutils",
14 "liblog",
15 "libhidlbase",
16 "libhidltransport",
17 "libhardware",
18 "libutils",
19 "vendor.sprd.hardware.hello@1.0",
20 ],
21 }
sevice.cpp:
1 int main() { 2 ALOGD("Hello hidl main()..."); 3 4 android::sp<IHello> hello = new Hello(); 5 6 configureRpcThreadpool(1, true /*callerWillJoin*/); 7 8 if (hello != nullptr) { 9 if (::android::OK != hello->registerAsService()) { 10 ALOGE("Error while registering IHello service"); 11 return 1; 12 } 13 } else { 14 ALOGE("Can't create instance of Hello, nullptr"); 15 } 16 17 joinRpcThreadpool(); 18 19 return 0; // should never get here 20 }
4、至此,命令行下启动vendor.sprd.hardware.hello@1.0-service可执行文件,即可运行该hidl服务
5、测试文件:
1 int main() { 2 int ret; 3 4 android::sp<IHello> service = IHello::getService(); 5 if (service == nullptr) { 6 printf("Failed to get service\n"); 7 return -1; 8 } 9 10 service->helloWorld("Trump", [&](hidl_string result) { 11 printf("%s\n", result.c_str()); 12 }); 13 14 return 0; 15 }