☰
仓颉 OpenHarmony 蓝牙连接状态枚举详解:ohos.bluetooth.constant 模块实战指南
2026/10/16 6:04:39 网站建设 项目流程
  • 文档
  • 知识库
  • 教程
  • OpenHarmony

【免费下载链接】CangjieCorpus

本仓库为仓颉编程语言语料库,聚焦 仓颉编程语言 核心知识体系,整合官方开发指南、API 文档、典型代码示例及语法规范等多维度资源,经结构化处理与专业标注,构建为支持 RAG(检索增强生成)技术 的高质量知识基座,适配智能编码助手、学习辅助工具等应用开发需求。 欢迎开发者基于本语料库构建仓颉语言智能应用,推动鸿蒙开发生态智能化升级!

项目地址:https://gitcode.com/Cangjie/CangjieCorpus
点击查看免费下载

本指南聚焦 OpenHarmony 蓝牙开发中ohos.bluetooth.constant(蓝牙 constant 模块)的核心内容,系统讲解ProfileConnectionState连接状态枚举的四个取值、判等与字符串化运算符,并结合本仓库中 cj-apis-bluetooth-base_profile.md、cj-apis-bluetooth-a2dp.md、cj-apis-bluetooth-ble.md 与 GATT 开发指南中的实际用法,说明如何在仓颉工程中订阅连接状态变化事件、用状态枚举做连接判断,以及处理蓝牙服务子系统错误码。读完本文,你将能够在仓颉应用中准确识别蓝牙 profile 的连接生命周期,并写出状态机正确的蓝牙连接逻辑。

模块定位与导入方式

constant模块是蓝牙能力中专门承载"常量定义"的模块,ProfileConnectionState即用于描述蓝牙设备 profile(如 A2DP 音频、HFP 通话等)的连接状态。在仓颉工程中,通过以下方式导入:

import kit.ConnectivityKit.*

该模块下所有接口均要求系统能力SystemCapability.Communication.Bluetooth.Core,起始版本为22,即仅在支持该系统能力的 OpenHarmony 设备上可用。导入后,即可直接使用ProfileConnectionState类型及其成员。

ProfileConnectionState 枚举:四个状态成员

枚举完整声明如下(...表示当前文档版本中未展开的预留成员):

public enum ProfileConnectionState <: Equatable<ProfileConnectionState> & ToString { | StateDisconnected | StateConnecting | StateConnected | StateDisconnecting | ... }

该枚举同时实现Equatable<ProfileConnectionState>(可判等)与ToString(可转字符串)两个父类型,因此可直接参与==、!=比较,也可调用toString()输出可读文本。四个成员语义如下:

枚举成员含义典型场景
StateDisconnectedprofile 已断连初始状态、断开完成后的稳定状态
StateConnectingprofile 正在连接已发起连接请求、等待握手完成
StateConnectedprofile 已连接连接建立成功,可进行数据传输
StateDisconnectingprofile 正在断开连接已发起断开请求、等待连接释放

从连接生命周期看,状态一般按StateDisconnected → StateConnecting → StateConnected → StateDisconnecting → StateDisconnected循环跃迁。在 cj-gatt-development-guide.md 中,官方明确指出整个连接过程会涉及多种状态的跃迁,其中StateConnected表示已连接、StateDisconnected表示已断连,这为状态判断提供了直接依据。

运算符与字符串化方法

ProfileConnectionState除枚举成员外还提供三个实例方法,用于状态比较与日志输出。

判等运算符==

public operator func ==(other: ProfileConnectionState): Bool

对两个 profile 连接状态判等,状态相同返回true,否则返回false。

参数:

参数名类型必填默认值说明
otherProfileConnectionState是-蓝牙设备的 profile 连接状态

返回值:Bool,状态相同返回true,否则返回false。

判不等运算符!=

public operator func !=(other: ProfileConnectionState): Bool

对两个 profile 连接状态判不等,状态不同返回true,否则返回false。

参数:

参数名类型必填默认值说明
otherProfileConnectionState是-蓝牙设备的 profile 连接状态

返回值:Bool,状态不同返回true,否则返回false。

字符串化方法toString()

public func toString(): String

返回 profile 连接状态的字符串表示,常用于日志输出,例如回调中打印"profile connection state has change to ${connectionState}"。

返回值:String,profile 连接状态的字符串表示。

在 BaseProfile 中的实际应用

ProfileConnectionState是 BaseProfile 接口体系中的核心返回类型:

public interface BaseProfile { func getConnectedDevices(): Array<String> func getConnectionState(deviceId: String): ProfileConnectionState func on(eventType: ProfileCallbackType, callback: Callback1Argument<StateChangeParam>): Unit func off(eventType: ProfileCallbackType, callback: CallbackObject): Unit func off(eventType: ProfileCallbackType): Unit }

其中getConnectionState(deviceId)返回指定设备的ProfileConnectionState,调用方据此判断设备当前所处的连接阶段:

// index.cj import ohos.business_exception.* import kit.ConnectivityKit.* import kit.PerformanceAnalysisKit.Hilog try { let a2dpSrc = createA2dpSrcProfile() let retArray = a2dpSrc.getConnectionState("XX:XX:XX:XX:XX:XX") } catch (e: BusinessException) { Hilog.info(0, "Bluetooth", "errCode: ${e.code}, errMessage: ${e.message}") }

同时,连接状态变化通过on(ProfileCallbackType.ConnectionStateChange, callback)以异步回调方式通知,回调入参StateChangeParam中即包含state: ProfileConnectionState字段(该类的完整定义见 cj-apis-bluetooth-base_profile.md)。完整订阅与取消订阅示例:

// index.cj import ohos.callback_invoke.* import ohos.business_exception.* import kit.ConnectivityKit.* import kit.PerformanceAnalysisKit.Hilog class StateChangeCallback <: Callback1Argument<StateChangeParam> { public func invoke(err: ?BusinessException, arg: StateChangeParam): Unit { let connectionState = arg.state.toString() Hilog.info(0, "Bluetooth", "profile connection state has change to ${connectionState}") } } let changeCallBack = StateChangeCallback() let a2dp = createA2dpSrcProfile() try { a2dp.on(ProfileCallbackType.ConnectionStateChange, changeCallBack) a2dp.off(ProfileCallbackType.ConnectionStateChange) } catch (e: BusinessException) { Hilog.info(0, "Bluetooth", "errCode: ${e.code}, errMessage: ${e.message}") }

A2DP、HFP 等具体 profile 类均继承自BaseProfile,因此这些订阅、查询连接状态的模式在 cj-apis-bluetooth-a2dp.md 与 cj-apis-bluetooth-hfp.md 中保持一致。

用状态枚举构建 GATT 连接状态机

在 cj-gatt-development-guide.md 的完整示例中,客户端管理器用ProfileConnectionState作为内部状态字段,初始化为StateDisconnected:

class GattClientManager { var device: ?String = None<String> var gattClient: ?GattClientDevice = None<GattClientDevice> var connectState: ProfileConnectionState = ProfileConnectionState.StateDisconnected ... }

其核心逻辑体现了状态枚举的两大典型用法:

1. 订阅回调中更新状态:连接状态变化回调将stateInfo.state写入connectState字段,保持本地状态与真实连接一致:

let onGattClientStateChange = BLEConnectionStateChangeCallback(){ err, stateInfo => Hilog.info(0, TAG, "onGattServerStateChange: device=" + stateInfo.deviceId + ", state=" + stateInfo.state.toString()) if (stateInfo.deviceId == this.device.getOrThrow()) { this.connectState = stateInfo.state } }

2. 通过!=/==校验前置条件:发起连接前,仅当当前状态为StateDisconnected才允许执行,避免重复发起连接:

if (this.connectState != ProfileConnectionState.StateDisconnected) { Hilog.error(1, TAG, 'startConnect failed') return }

而所有需要已连接前提的操作(如读写特征值、收发数据)均以StateConnected为门槛进行守卫,例如:

if (this.gattClient.isNone() || this.connectState != ProfileConnectionState.StateConnected) { Hilog.error(1, TAG, 'gattClient does not exist or state not connected') }

类似的初始化与守卫写法也出现在 cj-apis-bluetooth-ble.md 的客户端示例中(var connectState = ProfileConnectionState.StateDisconnected)。可见,将ProfileConnectionState与回调事件结合,是构建可靠蓝牙连接状态机、避免在未连接状态下误操作的标准做法。

异常处理与错误码对照

涉及连接状态查询与订阅的 API 均可能抛出BusinessException,需结合通用错误码与蓝牙服务子系统错误码定位问题:

错误码 ID错误信息说明与处理
201Permission denied.权限校验失败,需在工程中声明ohos.permission.ACCESS_BLUETOOTH
801Capability not supported.设备不支持此 API,需确认系统能力
2900001Service stopped.蓝牙服务已停止,重新执行打开或关闭蓝牙
2900003Bluetooth disabled.蓝牙开关已关闭,重新打开蓝牙开关
2900004Profile not supported.当前设备环境不支持该配置文件,检查设备能力后停止调用
2900099Operation failed.操作失败,请重试该操作

标准捕获写法:

try { // 查询或订阅连接状态 } catch (e: BusinessException) { Hilog.info(0, "Bluetooth", "errCode: ${e.code}, errMessage: ${e.message}") }

权限与系统能力约束

  • 权限:ohos.permission.ACCESS_BLUETOOTH。凡涉及查询已连接设备、读取连接状态、订阅/取消订阅状态变化事件的 API 均要求此权限,未授权时抛出 201 错误。
  • 系统能力:SystemCapability.Communication.Bluetooth.Core,缺失时抛出 801 错误。
  • 版本:ProfileConnectionState及其全部成员、运算符方法起始版本均为22,开发前需确认目标设备系统版本与系统能力声明。

小结

ohos.bluetooth.constant模块的ProfileConnectionState通过StateDisconnected、StateConnecting、StateConnected、StateDisconnecting四个成员完整刻画了蓝牙 profile 的连接生命周期,并依托Equatable与ToString父类型提供==、!=、toString()三个实用方法。在实战中,它与BaseProfile.getConnectionState()配合可主动查询连接状态,与on/off订阅机制结合可被动感知状态跃迁,配合 GATT 客户端/服务端的连接状态机模式,是仓颉蓝牙应用中不可绕过的核心类型。相关 API 详情可继续查阅 cj-apis-bluetooth-base_profile.md、cj-apis-bluetooth-a2dp.md、cj-apis-bluetooth-hfp.md 与 cj-gatt-development-guide.md。

  • 文档
  • 知识库
  • 教程
  • OpenHarmony

【免费下载链接】CangjieCorpus

本仓库为仓颉编程语言语料库,聚焦 仓颉编程语言 核心知识体系,整合官方开发指南、API 文档、典型代码示例及语法规范等多维度资源,经结构化处理与专业标注,构建为支持 RAG(检索增强生成)技术 的高质量知识基座,适配智能编码助手、学习辅助工具等应用开发需求。 欢迎开发者基于本语料库构建仓颉语言智能应用,推动鸿蒙开发生态智能化升级!

项目地址:https://gitcode.com/Cangjie/CangjieCorpus
点击查看免费下载

相关推荐

上一篇:RSpec与Ruby 1.9兼容性解决方案:避免踩坑的完整教程
下一篇:阿里Wan2.2-Animate开源:数字人视频创作的革命性突破

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询