
蓝牙是 AOSP 中功能最丰富的子系统之一,包含传统蓝牙(BR/EDR)、低功耗蓝牙(BLE)、数十种协议配置文件、完整的原生 HCI 协议栈,并且与音频、电话框架深度集成。Android 蓝牙实现主要位于packages/modules/Bluetooth/,以可更新的 APEX 模块(com.android.bt)形式发布。本章逐层讲解:从 Java 框架 API,经过原生 Gabeldorsche/Fluoride 协议栈,一直到与控制器固件交互的 AIDL HAL 层。37.1 蓝牙架构37.1.1 高层概览Android 蓝牙协议栈采用分层垂直架构。上层应用调用 SDK 公开类;通过 AIDL Binder 调用特权系统服务;系统服务驱动 C++/Rust 编写的原生协议栈;原生协议栈通过厂商 HAL 层使用 HCI 与硬件交互。37.1.2 BluetoothManagerBluetoothManager 是应用访问系统蓝牙服务的入口。注解为@SystemService(Context.BLUETOOTH_SERVICE),通过Context.getSystemService()获取。源码路径:packages/modules/Bluetooth/framework/java/android/bluetooth/BluetoothManager.java@SystemService(Context.BLUETOOTH_SERVICE) @RequiresFeature(PackageManager.FEATURE_BLUETOOTH) public final class BluetoothManager { private final BluetoothAdapter mAdapter; private final Context mContext; /** @hide */ public BluetoothManager(Context context) { mContext = context.createDeviceContext(Context.DEVICE_ID_DEFAULT); mAdapter = BluetoothAdapter.createAdapter(mContext); } @RequiresNoPermission public BluetoothAdapter getAdapter() { return mAdapter; } // ... }BluetoothManager 提供三大核心能力:适配器访问:getAdapter()返回本地蓝牙控制器的单例 BluetoothAdapter 对象。GATT 连接状态:getConnectionState()与getConnectedDevices()上报 BLE‑GATT 连接状态。GATT 服务端创建:openGattServer()实例化 BluetoothGattServer,用于托管本地服务。37.1.3 BluetoothAdapterBluetoothAdapter(代码 5500 行以上)是所有蓝牙操作的核心 API 类,代表本地蓝牙射频模块,是设备发现、配对绑定、协议配置文件连接、BLE 操作的入口。源码路径:packages/modules/Bluetooth/framework/java/android/bluetooth/BluetoothAdapter.java关键状态常量定义适配器生命周期:public static final int STATE_OFF = 10; public static final int STATE_TURNING_ON = 11; public static final int STATE_ON = 12; public static final int STATE_TURNING_OFF = 13; public static final int STATE_BLE_TURNING_ON = 14; // @hide public static final int STATE_BLE_ON = 15; // @SystemApi public static final int STATE_BLE_TURNING_OFF = 16; // @hide适配器状态机包含两级 “开启” 状态:STATE_BLE_ON仅启用 BLE 子系统(广播、扫描);STATE_ON同时启用传统 BR/EDR 传输以及全部协议配置文件。BluetoothAdapter 关键方法:方法用途enable() / disable()开启 / 关闭蓝牙,需要 BLUETOOTH_CONNECT 权限startDiscovery()开始扫描周边 BR/EDR 设备getBondedDevices()返回已配对设备集合getBluetoothLeScanner()获取 BLE 扫描器对象getBluetoothLeAdvertiser()获取 BLE 广播器对象listenUsingRfcommWithServiceRecord()创建 RFCOMM 服务端 SocketlistenUsingL2capChannel()创建 L2CAP CoC 服务端 SocketgetProfileProxy()绑定协议配置文件服务(A2DP、HFP 等)getRemoteDevice()通过 MAC 地址生成 BluetoothDevice 对象nameForState()将状态整型转换为可读字符串37.1.4 BluetoothManagerService 和 BluetoothService在 system_server 进程中,Kotlin 实现的BluetoothService负责启动蓝牙子系统。它属于 SystemService,会创建 Handler 线程,构造 BluetoothSupervisor,并发布 Binder 服务。源码路径:packages/modules/Bluetooth/service/src/BluetoothService.ktclass BluetoothService(context: Context) : SystemService(context) { private val looper = HandlerThread("BluetoothSystemServer").apply { start() }.looper private var supervisor: BluetoothSupervisor init { val bluetoothComponent = BluetoothComponent(context) supervisor = if (Flags.systemServerMigrateBmsToKotlin()) { BluetoothSupervisorNew(context, looper, bluetoothComponent) } else { BluetoothSupervisorLegacy(context, looper, bluetoothComponent) } // ... } override fun onStart() { publishBinderService(SERVICE_NAME, ServerBinder(looper, supervisor.api, context)) } }功能开关Flags.systemServerMigrateBmsToKotlin()(aconfig 标记system_server_migrate_bms_to_kotlin)用于 Kotlin 迁移过程中切换新旧两套 Supervisor 实现。BluetoothComponent解析蓝牙应用包名与组件名称,校验设备配置;用户限制逻辑在独立类BluetoothRestriction中,同步初始化。BluetoothManagerService是 Java 实现,承担核心业务:绑定 AdapterService、管理开关状态流转、崩溃恢复(最多 6 次重试)、飞行模式联动、多用户切换。源码路径:packages/modules/Bluetooth/service/src/com/android/server/bluetooth/BluetoothManagerService.javaBluetoothManagerService 核心设计:崩溃恢复:mCrashTimestamps记录崩溃时间戳,最多重试MAX_ERROR_RESTART_RETRIES=6次,重启延时SERVICE_RESTART_DELAY为 400ms,延时随重试次数倍增。状态管理:基于 Kotlin Flow 的BluetoothAdapterState跟踪适配器状态流转,支持超时等待。Handler 消息:全部状态切换通过 Handler 消息串行处理,例如MESSAGE_BLUETOOTH_SERVICE_CONNECTED、MESSAGE_BLUETOOTH_STATE_CHANGE、MESSAGE_TIMEOUT_BIND。飞行模式:对接AirplaneModeListener、SatelliteModeListener完成射频状态管理。源码路径:packages/modules/Bluetooth/service/src/AdapterState.ktclass BluetoothAdapterState { private val _uiState = MutableSharedFlowInt(1) init { set(State.OFF) } fun set(s: Int) = runBlocking { _uiState.emit(s) if (!disableCacheForTesting) { IpcDataCache.invalidateCache(IPC_CACHE_MODULE_SYSTEM, GET_SYSTEM_STATE_API) } } fun get(): Int = _uiState.replayCache.get(0) suspend fun waitForState(timeout: Duration, vararg states: Int): Boolean = withTimeoutOrNull(timeout) { _uiState.filter { states.contains(it) }.first() } != null }37.1.5 AdapterServiceAdapterService 是运行在蓝牙 APK(com.android.bluetooth)内部的 Android Service。作为 Java 层与 C++ 原生协议栈之间的桥梁,所有协议配置文件服务都向它注册,同时管理蓝牙协议栈整体生命周期。源码路径:packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.javaAdapterService 导入并协调全部协议配置文件服务:import com.android.bluetooth.a2dp.A2dpService; import com.android.bluetooth.a2dpsink.A2dpSinkService; import com.android.bluetooth.avrcp.AvrcpTargetService; import com.android.bluetooth.avrcpcontroller.AvrcpControllerService; import com.android.bluetooth.bas.BatteryService; import com.android.bluetooth.bass_client.BassClientService; import com.android.bluetooth.csip.CsipSetCoordinatorService; import com.android.bluetooth.gatt.GattService; import com.android.bluetooth.hap.HapClientService; import com.android.bluetooth.hearingaid.HearingAidService; import com.android.bluetooth.hfp.HeadsetService; import com.android.bluetooth.hfpclient.HeadsetClientService; import com.android.bluetooth.hid.HidDeviceService; import com.android.bluetooth.hid.HidHostService; // ……更多服务37.1.6 蓝牙 APEX 模块Android12 起,蓝牙协议栈作为 Mainline 模块打包进 APEX 容器com.android.bt发布。Google 可以通过 Google Play 系统更新推送蓝牙安全补丁与功能更新,无需完整 OTA 升级。目录:packages/modules/Bluetooth/apex/APEX 包包含:框架 JAR 包(android.bluetooth包)蓝牙 APK(com.android.bluetooth)原生动态库(C++/Rust 协议栈)配置文件(bt_did.conf等)系统服务(BluetoothService)37.1.7 权限模型Android12 及以上引入细粒度蓝牙权限,替代旧的BLUETOOTH、BLUETOOTH_ADMIN权限:权限用途BLUETOOTH_CONNECT连接已绑定设备,访问设备信息BLUETOOTH_SCAN扫描周边设备(可能获取位置信息)BLUETOOTH_ADVERTISE让本机对外可被发现BLUETOOTH_PRIVILEGED仅系统使用的特权操作框架 API 使用自定义注解强制权限校验:@RequiresBluetoothConnectPermission @RequiresPermission(BLUETOOTH_CONNECT) public SetBluetoothDevice getBondedDevices() { ... }37.2 蓝牙协议栈37.2.1 协议栈演进:Fluoride 到 GabeldorscheAndroid 蓝牙原生协议栈经历一次重大架构迭代:Fluoride(Android13 之前):源自博通 BlueDroid 的传统 C++ 蓝牙协议栈,单体架构,模块强耦合,大量全局状态。Gabeldorsche(GD):新一代模块化协议栈实现。GD 模块自底向上逐步替换 Fluoride 组件:先 HCI 层,再 ACL 管理,之后上层协议配置文件。main/shim/下的适配层提供桥接,允许原有 Fluoride 代码调用已经迁移完成的 GD 模块。37.2.2 源码目录布局蓝牙原生协议栈位于packages/modules/Bluetooth/system/system/ gd/ # Gabeldorsche 新一代模块化协议栈 hal/ # HAL抽象层,支持AIDL/HIDL后端 hci/ # HCI层、控制器抽象、ACL管理器 storage/ # 设备持久化数据库 crypto_toolbox/ # 密码学基础组件 os/ # OS抽象(Handler、定时器等) metrics/ # 蓝牙指标统计 packet/ # 数据包序列化框架 btif/ # 蓝牙接口,JNI桥接层 src/ # btif_core.cc, btif_dm.cc, btif_av.cc…… avrcp/ # AVRCP Target实现 bta/ # 蓝牙应用层 av/ # A2DP/AVRCP应用层 dm/ # 设备管理 gatt/ # GATT客户端/服务端应用层 hf_client/ # HFP客户端 hfp/ # HFP音频网关 hh/ # HID主机 hd/ # HID设备 le_audio/ # LE Audio pan/ # PAN协议配置文件 sdp/ # 服务发现协议 sys/ # 系统管理器 stack/ # 核心协议实现 a2dp/ # A2DP编解码处理 acl/ # ACL连接管理 avct/ # AVCTP协议 avdt/ # AVDTP协议 avrc/ # AVRCP协议 bnep/ # 蓝牙网络封装协议 btm/ # 蓝牙管理器(传统蓝牙安全) btu/ # 蓝牙上层 gatt/ # GATT协议 hid/ # HID协议 l2cap/ # L2CAP协议 pan/ # PAN协议 rfcomm/ # RFCOMM串口仿真协议 sdp/ # SDP协议 smp/ # BLE安全管理协议 srvc/ # GATT基础服务(DIS等) audio_hal_interface/ # Audio HAL集成 aidl/ # AIDL音频HAL客户端 rust/ # Rust组件 src/ # bluetooth_rs crate:le_audio(ISO + 周期性广播同步)、pdl、types模块 private_gatt/ # Rust实现GATT服务端,通过仲裁器与C++共享ATT通道 macros/ # 过程宏支持 main/ # 协议栈初始化与shim适配层 shim/ # GD对接Fluoride适配层 include/ # 对外头文件 osi/ # OS接口抽象 common/ # 通用工具37.2.3 Gabeldorsche (GD) 模块详解system/gd/下所有 GD 模块遵循统一设计模式:每个模块定义抽象接口,分别提供 Android(产品环境)与 Host(单元测试)两套实现。GD HAL 模块HAL 模块抽象协议栈与控制器之间的传输通道,支持 AIDL(新版)与 HIDL(旧版)两种后端。源码路径:packages/modules/Bluetooth/system/gd/hal/hci_backend.hnamespace bluetooth::hal { class HciBackend { public: static std::shared_ptrHciBackend CreateAidl(); static std::shared_ptrHciBackend CreateAidl(const std::string hci_instance_name); static std::shared_ptrHciBackend CreateHidl(::bluetooth::os::Handler*); virtual ~HciBackend() = default; virtual void initialize(std::shared_ptrHciBackendCallbacks) = 0; virtual void sendHciCommand(const std::vectoruint8_t) = 0; virtual void sendAclData(const std::vectoruint8_t) = 0; virtual void sendScoData(const std::vectoruint8_t) = 0; virtual void sendIsoData(const std::vectoruint8_t) = 0; }; } // namespace bluetooth::halHciHal类(hci_hal.h)封装后端,向协议栈其余部分暴露统一接口。源码路径:packages/modules/Bluetooth/system/gd/hal/hci_hal.hclass HciHal { public: virtual void registerIncomingPacketCallback(HciHalCallbacks* callback) = 0; virtual void unregisterIncomingPacketCallback() = 0; virtual void sendHciCommand(HciPacket command) = 0; virtual void sendAclData(HciPacket data) = 0; virtual void sendScoData(HciPacket data) = 0; virtual void sendIsoData(HciPacket data) = 0; };回调接口与 HAL 一一对应:class HciHalCallbacks { public: virtual void hciEventReceived(HciPacket event) = 0; virtual void aclDataReceived(HciPacket data) = 0; virtual void scoDataReceived(HciPacket data) = 0; virtual void isoDataReceived(HciPacket data) = 0; virtual void controllerNeedsReset() {} };GD HCI 模块HCI 模块完成控制器初始化、能力探测,为各个 HCI 子系统提供管理器。源码路径:packages/modules/Bluetooth/system/gd/hci/controller_impl.hControllerImpl通过 HCI 命令查询控制器能力,以布尔特征标记对外暴露:class ControllerImpl : public Controller { public: // 传统蓝牙能力 virtual bool SupportsSimplePairing() const override; virtual bool SupportsSecureConnections() const override; virtual bool SupportsRoleSwitch() const override; virtual bool SupportsSco() const override; // BLE能力 virtual bool SupportsBle() const override; virtual bool SupportsBleExtendedAdvertising() const override; virtual bool SupportsBlePeriodicAdvertising() const override; virtual bool SupportsBle2mPhy() const override; virtual bool SupportsBleCodedPhy() const override; virtual bool SupportsBlePrivacy() const override; virtual bool SupportsBleConnectedIsochronousStreamCentral() const override; virtual bool SupportsBleIsochronousBroadcaster() const override; virtual bool SupportsBleChannelSounding() const override; // 缓冲区信息 virtual uint16_t GetAclPacketLength() const override; virtual uint16_t GetNumAclPacketBuffers() const override; virtual LeBufferSize GetLeBufferSize() const override; virtual LeBufferSize GetControllerIsoBufferSize() const override; };LE 事件掩码按蓝牙版本做版本保护,避免设置控制器不支持的比特位:static constexpr uint64_t kLeEventMask53 = 0x00000007ffffffff; // BT 5.3 static constexpr uint64_t kLeEventMask52 = 0x00000003ffffffff; // BT 5.2 static constexpr uint64_t kLeEventMask51 = 0x0000000000ffffff; // BT 5.1 static constexpr uint64_t kLeEventMask50 = 0x00000000000fffff; // BT 5.0GD HCI 模块提供专用管理器:管理器源码位置用途LeAdvertisingManagerImplhci/le_advertising_manager_impl.hBLE 广播集管理LeScanningManagerImplhci/le_scanning_manager_impl.h带过滤器的 BLE 扫描管理AclManagerClassicImplhci/acl_manager/acl_manager_classic_impl.h传统蓝牙 ACL 连接AclManagerLeImplhci/acl_manager/acl_manager_le_impl.hBLE ACL 连接LeAddressManagerhci/le_address_manager.hRPA 地址轮换、地址管理DistanceMeasurementManagerImplhci/distance_measurement_manager_impl.h信道探测 / 测距功能GD Storage 模块Storage 模块持久化保存配对信息、设备属性、适配器配置,磁盘上使用 INI 风格配置文件。源码路径:packages/modules/Bluetooth/system/gd/storage/storage_module.h存储键通过预处理宏定义:源码路径:packages/modules/Bluetooth/system/gd/storage/config_keys.h#define BTIF_STORAGE_SECTION_ADAPTER "Adapter" #define BTIF_STORAGE_KEY_ADDR_TYPE "AddrType" #define BTIF_STORAGE_KEY_ADDRESS "Address" #define BTIF_STORAGE_KEY_ALIAS "Aliase" #define BTIF_STORAGE_KEY_DEV_CLASS "DevClass" #define BTIF_STORAGE_KEY_DEV_TYPE "DevType" #define BTIF_STORAGE_KEY_HFP_VERSION "HfpVersion" #define BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH "GattClientDatabaseHash" // ……更多键37.2.4 Rust 组件Android 逐步在蓝牙协议栈引入 Rust,提升内存安全;Android17 对 Rust 组件做了目录重构。packages/modules/Bluetooth/system/rust/包含三部分:rust/ src/ # bluetooth_rs crate:le_audio(ISO管理器 + 周期性广播同步)、pdl、types模块 private_gatt/ # Rust实现GATT服务端,Android17从src移出为独立crate macros/ # 过程宏支持Rust GATT 服务端(private_gatt)Rust 实现的 GATT 服务端与原有 C++ GATT 客户端共享 ATT 承载通道。Android17 将其从system/rust/src/迁移到独立 cratesystem/rust/private_gatt/,移除全局状态,不再依赖静态单例。源码路径:packages/modules/Bluetooth/system/rust/private_gatt/src/gatt.rs//! This module is a simple GATT server that shares the ATT channel with the //! existing C++ GATT client. See go/private-gatt-in-platform for the design. mod arbiter; mod callbacks; mod channel; mod ffi; mod ids; #[cfg(test)] mod mocks; mod mtu; mod opcode_types; mod server;仲裁器arbiter根据句柄范围决定由 C++ 或者 Rust 处理每一条入站 ATT‑PDU;mtu模块实现 ATT MTU 协商;ffi提供 C++ 互操作绑定,C++ 侧对应头文件stack/arbiter/acl_arbiter.h。Rust LE Audio 模块Android17 新增的重要组件:bluetooth_rscrate 下le_audio模块,与 pdl、types 模块同位于system/rust/src/,在lib.rs中对外导出。源码路径:packages/modules/Bluetooth/system/rust/src/lib.rspub mod le_audio; pub mod pdl; pub mod types;le_audio包含两个等时传输管理器,供 LE Audio 上层协议配置文件调用;每个管理器拆分为traits.rs(接口)、manager.rs(实现)、ffi.rs(cxx 桥接 C++ 适配层)。模块源码路径用途ISO Managersystem/rust/src/le_audio/iso_manager/管理 CIG/CIS(连接态)、BIG/BIS(广播态)等时组与流Periodic Advertising Syncsystem/rust/src/le_audio/periodic_advertising_sync/同步周期性广播序列 (PAST/PA sync),上报 BIGInfo 事件