news 2026/4/23 15:15:17

HIDL Hal 开发笔记3----Binderized HALs 实例分析

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
HIDL Hal 开发笔记3----Binderized HALs 实例分析

目录

  • 一、整体框架
  • 二、HAL 层服务端实现
  • 三、Framework 层客户端实现

Binderized HALs 实例分析

一、整体框架

对于Binderized HALs,HAL 层以进程的形式存在,内部有一个HwBinder服务端对象,对外提供HwBinder远程调用服务。Framework 通过HwBinder远程调用到 HAL 中的函数,这些函数直接访问具体的驱动。


在源码下device/google/coral/vibrator/目录下,是 Google 为 pixel4、pixel4 xl 实现的振动器 HAL,其类型就是 Binderized HALs。本文分析其具体实现


二、HAL 层服务端实现

HAL 层表现为一个进程:

进程对应的代码位于device/google/coral/vibrator

整体结构如下:

我们从 Android.bp 下手:

cc_defaults{name:"android.hardware.vibrator@1.3-defaults.coral",defaults:["hidl_defaults"],relative_install_path:"hw",shared_libs:["libhidlbase","libcutils","libhidltransport","liblog","libhwbinder","libutils","libhardware","android.hardware.vibrator@1.0","android.hardware.vibrator@1.1","android.hardware.vibrator@1.2","android.hardware.vibrator@1.3",],}cc_defaults{name:"PtsVibratorHalFloralDefaults",defaults:["android.hardware.vibrator@1.3-defaults.coral"],static_libs:["android.hardware.vibrator@1.3-impl.coral"],test_suites:["general-tests","pts",],multilib:{lib32:{suffix:"32",},lib64:{suffix:"64",},},}cc_library{name:"android.hardware.vibrator@1.3-impl.coral",defaults:["android.hardware.vibrator@1.3-defaults.coral"],srcs:["Hardware.cpp","Vibrator.cpp",],export_include_dirs:["."],vendor_available:true,}cc_binary{name:"android.hardware.vibrator@1.3-service.coral",defaults:["android.hardware.vibrator@1.3-defaults.coral"],init_rc:["android.hardware.vibrator@1.3-service.coral.rc"],vintf_fragments:["android.hardware.vibrator@1.3-service.coral.xml"],srcs:["service.cpp"],static_libs:["android.hardware.vibrator@1.3-impl.coral"],proprietary:true,}

一个共享库android.hardware.vibrator@1.3-impl.coral,一个 native 可执行程序android.hardware.vibrator@1.3-service.coral

  • android.hardware.vibrator@1.3-impl.coral共享库中 :
  • Hardware.cpp 中对振动器驱动的访问包装成了两个对象HwApi HwCal
  • Vibrator.cpp 链接了android.hardware.vibrator@1.3库,内部有一个 Vibrator类,继承自android.hardware.vibrator@1.3库中 IVibrator,IVibrator 是由hardware/interfaces/vibrator/1.3/IVibrator.hal编译出来的。Vibrator 类是一个HwBinder服务端类,对外提供了调用振动器的接口,内部实现是通过调用HwApi HwCal对象的成员函数实现的。
  • android.hardware.vibrator@1.3-service.coral可执行程序:
status_tregisterVibratorService(){sp<Vibrator>vibrator=newVibrator(std::make_unique<HwApi>(),std::make_unique<HwCal>());returnvibrator->registerAsService();}intmain(){configureRpcThreadpool(1,true);status_tstatus=registerVibratorService();if(status!=OK){returnstatus;}joinRpcThreadpool();}

实现上很简单:

  • 向 HwServiceManager 注册 Vibrator
  • 配置 HwBinder 线程

具体振动器的操作细节就不看了,这不是我们的重点。


三、Framework 层客户端实现

对于客户端,我们只要知道 Hal 对外提供的接口即可,这个接口由hardware/interfaces/vibrator/1.3/IVibrator.hal描述:

package android.hardware.vibrator@1.3;import @1.0::EffectStrength;import @1.0::Status;import @1.2::IVibrator;interface IVibrator extends @1.2::IVibrator{supportsExternalControl()generates(bool supports);setExternalControl(bool enabled)generates(Status status);perform_1_3(Effect effect,EffectStrength strength)generates(Status status,uint32_tlengthMs);};

frameworks/base/services/core/java/com/android/server/VibratorService.java本身是一个 Binder 服务端向 App 提供服务,同时也是一个HwBinder客户端通过 JNI 访问到 HAL 服务端。

publicclassVibratorServiceextendsIVibratorService.StubimplementsInputManager.InputDeviceListener{// ......staticnativebooleanvibratorExists();staticnativevoidvibratorInit();staticnativevoidvibratorOn(longmilliseconds);staticnativevoidvibratorOff();staticnativebooleanvibratorSupportsAmplitudeControl();staticnativevoidvibratorSetAmplitude(intamplitude);staticnativelongvibratorPerformEffect(longeffect,longstrength);staticnativebooleanvibratorSupportsExternalControl();staticnativevoidvibratorSetExternalControl(booleanenabled);// ......}

VibratorService 中有多个 native 方法,这些方法用于远程调用 Hal 层。

对应的 JNI 函数实现在frameworks/base/services/core/jni/com_android_server_VibratorService.cpp

#defineLOG_TAG"VibratorService"#include<android/hardware/vibrator/1.0/IVibrator.h>#include<android/hardware/vibrator/1.0/types.h>#include<android/hardware/vibrator/1.0/IVibrator.h>#include<android/hardware/vibrator/1.1/types.h>#include<android/hardware/vibrator/1.2/IVibrator.h>#include<android/hardware/vibrator/1.2/types.h>#include<android/hardware/vibrator/1.3/IVibrator.h>#include"jni.h"#include<nativehelper/JNIHelp.h>#include"android_runtime/AndroidRuntime.h"#include<utils/misc.h>#include<utils/Log.h>#include<hardware/vibrator.h>#include<inttypes.h>#include<stdio.h>using android::hardware::Return;using android::hardware::vibrator::V1_0::EffectStrength;using android::hardware::vibrator::V1_0::Status;using android::hardware::vibrator::V1_1::Effect_1_1;namespace V1_0=android::hardware::vibrator::V1_0;namespace V1_1=android::hardware::vibrator::V1_1;namespace V1_2=android::hardware::vibrator::V1_2;namespace V1_3=android::hardware::vibrator::V1_3;namespace android{staticconstexprintNUM_TRIES=2;// Creates a Return<R> with STATUS::EX_NULL_POINTER.template<class R>inlineReturn<R>NullptrStatus(){using::android::hardware::Status;returnReturn<R>{Status::fromExceptionCode(Status::EX_NULL_POINTER)};}// Helper used to transparently deal with the vibrator HAL becoming unavailable.template<class R,class I,class...Args0,class...Args1>Return<R>halCall(Return<R>(I::*fn)(Args0...),Args1&&...args1){// Assume that if getService returns a nullptr, HAL is not available on the// device.staticsp<I>sHal=I::getService();staticbool sAvailable=sHal!=nullptr;if(!sAvailable){returnNullptrStatus<R>();}// Return<R> doesn't have a default constructor, so make a Return<R> with// STATUS::EX_NONE.using::android::hardware::Status;Return<R>ret{Status::fromExceptionCode(Status::EX_NONE)};// Note that ret is guaranteed to be changed after this loop.for(inti=0;i<NUM_TRIES;++i){ret=(sHal==nullptr)?NullptrStatus<R>():(*sHal.*fn)(std::forward<Args1>(args1)...);if(ret.isOk()){break;}ALOGE("Failed to issue command to vibrator HAL. Retrying.");// Restoring connection to the HAL.sHal=I::tryGetService();}returnret;}template<class R>boolisValidEffect(jlong effect){if(effect<0){returnfalse;}R val=static_cast<R>(effect);autoiter=hardware::hidl_enum_range<R>();returnval>=*iter.begin()&&val<=*std::prev(iter.end());}staticvoidvibratorInit(JNIEnv/* env */,jobject/* clazz */){halCall(&V1_0::IVibrator::ping).isOk();}staticjbooleanvibratorExists(JNIEnv*/* env */,jobject/* clazz */){returnhalCall(&V1_0::IVibrator::ping).isOk()?JNI_TRUE:JNI_FALSE;}staticvoidvibratorOn(JNIEnv*/* env */,jobject/* clazz */,jlong timeout_ms){Status retStatus=halCall(&V1_0::IVibrator::on,timeout_ms).withDefault(Status::UNKNOWN_ERROR);if(retStatus!=Status::OK){ALOGE("vibratorOn command failed (%"PRIu32").",static_cast<uint32_t>(retStatus));}}staticvoidvibratorOff(JNIEnv*/* env */,jobject/* clazz */){Status retStatus=halCall(&V1_0::IVibrator::off).withDefault(Status::UNKNOWN_ERROR);if(retStatus!=Status::OK){ALOGE("vibratorOff command failed (%"PRIu32").",static_cast<uint32_t>(retStatus));}}staticjlongvibratorSupportsAmplitudeControl(JNIEnv*,jobject){returnhalCall(&V1_0::IVibrator::supportsAmplitudeControl).withDefault(false);}staticvoidvibratorSetAmplitude(JNIEnv*,jobject,jint amplitude){Status status=halCall(&V1_0::IVibrator::setAmplitude,static_cast<uint32_t>(amplitude)).withDefault(Status::UNKNOWN_ERROR);if(status!=Status::OK){ALOGE("Failed to set vibrator amplitude (%"PRIu32").",static_cast<uint32_t>(status));}}staticjbooleanvibratorSupportsExternalControl(JNIEnv*,jobject){returnhalCall(&V1_3::IVibrator::supportsExternalControl).withDefault(false);}staticvoidvibratorSetExternalControl(JNIEnv*,jobject,jboolean enabled){Status status=halCall(&V1_3::IVibrator::setExternalControl,static_cast<uint32_t>(enabled)).withDefault(Status::UNKNOWN_ERROR);if(status!=Status::OK){ALOGE("Failed to set vibrator external control (%"PRIu32").",static_cast<uint32_t>(status));}}staticjlongvibratorPerformEffect(JNIEnv*,jobject,jlong effect,jint strength){Status status;uint32_tlengthMs;autocallback=[&status,&lengthMs](Status retStatus,uint32_tretLengthMs){status=retStatus;lengthMs=retLengthMs;};EffectStrengtheffectStrength(static_cast<EffectStrength>(strength));Return<void>ret;if(isValidEffect<V1_0::Effect>(effect)){ret=halCall(&V1_0::IVibrator::perform,static_cast<V1_0::Effect>(effect),effectStrength,callback);}elseif(isValidEffect<Effect_1_1>(effect)){ret=halCall(&V1_1::IVibrator::perform_1_1,static_cast<Effect_1_1>(effect),effectStrength,callback);}elseif(isValidEffect<V1_2::Effect>(effect)){ret=halCall(&V1_2::IVibrator::perform_1_2,static_cast<V1_2::Effect>(effect),effectStrength,callback);}elseif(isValidEffect<V1_3::Effect>(effect)){ret=halCall(&V1_3::IVibrator::perform_1_3,static_cast<V1_3::Effect>(effect),effectStrength,callback);}else{ALOGW("Unable to perform haptic effect, invalid effect ID (%"PRId32")",static_cast<int32_t>(effect));return-1;}if(!ret.isOk()){ALOGW("Failed to perform effect (%"PRId32")",static_cast<int32_t>(effect));return-1;}if(status==Status::OK){returnlengthMs;}elseif(status!=Status::UNSUPPORTED_OPERATION){// Don't warn on UNSUPPORTED_OPERATION, that's a normal event and just means the motor// doesn't have a pre-defined waveform to perform for it, so we should just give the// opportunity to fall back to the framework waveforms.ALOGE("Failed to perform haptic effect: effect=%"PRId64", strength=%"PRId32", error=%"PRIu32").",static_cast<int64_t>(effect),static_cast<int32_t>(strength),static_cast<uint32_t>(status));}return-1;}staticconstJNINativeMethod method_table[]={{"vibratorExists","()Z",(void*)vibratorExists},{"vibratorInit","()V",(void*)vibratorInit},{"vibratorOn","(J)V",(void*)vibratorOn},{"vibratorOff","()V",(void*)vibratorOff},{"vibratorSupportsAmplitudeControl","()Z",(void*)vibratorSupportsAmplitudeControl},{"vibratorSetAmplitude","(I)V",(void*)vibratorSetAmplitude},{"vibratorPerformEffect","(JJ)J",(void*)vibratorPerformEffect},{"vibratorSupportsExternalControl","()Z",(void*)vibratorSupportsExternalControl},{"vibratorSetExternalControl","(Z)V",(void*)vibratorSetExternalControl},};intregister_android_server_VibratorService(JNIEnv*env){returnjniRegisterNativeMethods(env,"com/android/server/VibratorService",method_table,NELEM(method_table));}};

所有的函数都通过halcall来实现,halcall中会去从 HwServiceManager 中去获取Vibrator Hal的代理对象,然后通过这个代理对象发起远程调用,从而调用到 HAL 层。

最后我们再来看 HAL 端的 VINTF 配置文件/Project/android-10.0.0_r41/device/google/coral/vibrator/android.hardware.vibrator@1.3-service.coral.xml

<manifest version="1.0"type="device"><hal format="hidl"><name>android.hardware.vibrator</name><transport>hwbinder</transport><version>1.3</version><interface><name>IVibrator</name><instance>default</instance></interface></hal></manifest>

注意这里 transport 指定了 hal 的类型为 hwbinder,也就是我们说的Binderized hal


版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/23 15:36:07

商联达云成本优化实战:精细化资源调度与管理,助力企业降本增效

在数字化转型浪潮席卷全球的今天&#xff0c;企业纷纷拥抱云计算以提升业务敏捷性与创新能力。然而&#xff0c;随着云服务的大规模应用&#xff0c;一个不容忽视的挑战浮出水面——“云成本失控”。这一现象已成为制约企业数字化进程的关键瓶颈&#xff0c;迫使企业重新审视其…

作者头像 李华
网站建设 2026/4/23 14:08:41

医疗预测项目:CNN + XGBoost 实战全流程

一、项目背景与设计思路1. 为什么“端到端 CNN”在医疗中经常失败&#xff1f;很多教程喜欢这样做&#xff1a;CT 图像 → CNN → 预测是否患病 但在真实医疗场景中&#xff0c;问题很快会暴露&#xff1a;数据量不够&#xff08;几百 ~ 几千&#xff09;批次差异大&#xff08…

作者头像 李华
网站建设 2026/4/23 13:42:32

鸿蒙应用的云原生部署实战

鸿蒙应用的云原生部署实战一、章节概述 1.1 学习目标 ✅ 掌握鸿蒙云原生架构的核心组件、设计模式与端云协同逻辑 ✅ 落地《全生态智能待办》的云原生部署方案&#xff1a;容器化打包、微服务拆分、弹性扩容 ✅ 集成华为Cloud Engine与AGC云服务&#xff0c;实现端云数据同步与…

作者头像 李华
网站建设 2026/4/23 12:11:15

网络安全核心架构:一张图看懂关键技术与攻防体系

网络安全技术虽然非常复杂&#xff0c;但是归纳起来&#xff0c;主要就是为了解决以下三方面问题&#xff1a; 1.数据的机密性&#xff1a;即如何令人们发送数据&#xff0c;即使被其他无关人员截取&#xff0c;他们也无法获知数据的含义。 2.数据的有效性&#xff1a;指数据不…

作者头像 李华
网站建设 2026/4/23 13:38:59

基于SpringBoot的4s店车辆管理系统(源码+lw+部署文档+讲解等)

课题介绍本课题聚焦4s店车辆全流程规范化管理与运营效率提升的核心需求&#xff0c;设计并实现基于SpringBoot框架的4s店车辆管理系统。当前4s店车辆管理领域存在车辆库存信息混乱、销售流程跟踪不及时、维修保养记录分散、客户与车辆档案管理滞后等问题&#xff0c;制约了4s店…

作者头像 李华