系统蓝牙界面显示“已连接”需要发起配对的应用去连蓝牙的profile,可以使用connection.connectAllowedProfiles接口连接对端设备支持的profile(只包括A2DP、HFP和HID)。
三方应用在蓝牙配对成功后,需要主动使用connection.connectAllowedProfiles接口连接对端设备支持的profile,才能在系统蓝牙界面显示“已连接”。
参考示例如下:
import { connection } from '@kit.ConnectivityKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct connectAllowedProfiles {
connectAllowedProfiles() {
// 发起蓝牙配对请求,此处的mac需要提前获取
connection.pairDevice('xx.xx.xx.xx', (err: BusinessError) => {
console.info(`pairDevice, device name err:${err}`);
});
// 订阅蓝牙配对状态变化事件
connection.on('bondStateChange', (data: connection.BondStateParam) => {
// 蓝牙已配对
if (data.state === connection.BondState.BOND_STATE_BONDED) {
// 调用getRemoteProfileUuids接口获取对端蓝牙支持的Profile类型
connection.getRemoteProfileUuids(data.deviceId,
(err: BusinessError, dataArray: Array<connection.ProfileUuids>) => {
console.error(`getRemoteProfileUuids errCode: ${(err as BusinessError).code}, errMessage: ${(err as BusinessError).message}, dataArray: ${dataArray}`);
// 当dataArray中支持类型包含A2DP、HFP和HID其中的一种,可调用connectAllowedProfiles接口发起连接。
connection.connectAllowedProfiles(data.deviceId, (err: BusinessError) => {
if (err) {
console.error(`connectAllowedProfiles errCode: ${(err as BusinessError).code}, errMessage: ${(err as BusinessError).message}`);
return;
}
console.info('connectAllowedProfiles');
});
});
}
});
}
build() {
Column() {
Button('connect Allowed Profiles')
.onClick(() => {
// 创建蓝牙配对状态变化监听,发起蓝牙配对,连接蓝牙
this.connectAllowedProfiles();
});
};
}
} 权限说明:需要在module.json5文件中配置允许应用接入蓝牙并使用蓝牙功能权限ohos.permission.ACCESS_BLUETOOTH。
调用connection.disconnectAllowedProfiles接口断开对端设备支持的profile连接,即可取消系统蓝牙界面的“已连接”显示。该接口从API Version 26开始支持,API Version 26以下版本无系统能力取消系统蓝牙“已连接”显示,无需处理。