1# @ohos.bluetooth.connection (蓝牙connection模块) 2 3connection模块提供了对蓝牙操作和管理的方法。 4 5> **说明:** 6> 7> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 8 9 10 11## 导入模块 12 13```js 14import { connection } from '@kit.ConnectivityKit'; 15``` 16 17 18## ProfileConnectionState 19 20type ProfileConnectionState = constant.ProfileConnectionState 21 22蓝牙设备的profile连接状态。 23 24**系统能力**:SystemCapability.Communication.Bluetooth.Core 25 26| 类型 | 说明 | 27| ------------------- | ------------------- | 28| [constant.ProfileConnectionState](js-apis-bluetooth-constant.md#profileconnectionstate) | 蓝牙设备的profile连接状态。 | 29 30 31## ProfileId 32 33type ProfileId = constant.ProfileId 34 35蓝牙profile枚举。 36 37**系统能力**:SystemCapability.Communication.Bluetooth.Core 38 39| 类型 | 说明 | 40| ------------------- | ------------------- | 41| [constant.ProfileId](js-apis-bluetooth-constant.md#profileid) | 蓝牙profile枚举。 | 42 43 44## ProfileUuids<sup>12+</sup> 45 46type ProfileUuids = constant.ProfileUuids 47 48表示Profile的UUID。 49 50**系统能力**:SystemCapability.Communication.Bluetooth.Core 51 52| 类型 | 说明 | 53| ------------------- | ------------------- | 54| [constant.ProfileUuids](js-apis-bluetooth-constant.md#profileuuids) | 表示Profile的UUID。 | 55 56 57## MajorClass 58 59type MajorClass = constant.MajorClass 60 61蓝牙设备主要类别。 62 63**系统能力**:SystemCapability.Communication.Bluetooth.Core 64 65| 类型 | 说明 | 66| ------------------- | ------------------- | 67| [constant.MajorClass](js-apis-bluetooth-constant.md#majorclass) | 蓝牙设备主要类别。 | 68 69 70## MajorMinorClass 71 72type MajorMinorClass = constant.MajorMinorClass 73 74主要次要蓝牙设备类别。 75 76**系统能力**:SystemCapability.Communication.Bluetooth.Core 77 78| 类型 | 说明 | 79| ------------------- | ------------------- | 80| [constant.MajorMinorClass](js-apis-bluetooth-constant.md#majorminorclass) | 主要次要蓝牙设备类别。 | 81 82 83## connection.pairDevice 84 85pairDevice(deviceId: string, callback: AsyncCallback<void>): void 86 87发起蓝牙配对。使用Callback异步回调。 88 89**需要权限**:ohos.permission.ACCESS_BLUETOOTH 90 91**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 92 93**系统能力**:SystemCapability.Communication.Bluetooth.Core 94 95**参数:** 96 97| 参数名 | 类型 | 必填 | 说明 | 98| -------- | ------ | ---- | ----------------------------------- | 99| deviceId | string | 是 | 表示配对的远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | 100| callback | AsyncCallback<void> | 是 | 回调函数。当配对成功,err为undefined,否则为错误对象。 | 101 102**错误码**: 103 104以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 105 106| 错误码ID | 错误信息 | 107| -------- | ---------------------------- | 108|201 | Permission denied. | 109|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 110|801 | Capability not supported. | 111|2900001 | Service stopped. | 112|2900003 | Bluetooth disabled. | 113|2900099 | Operation failed. | 114 115**示例:** 116 117```js 118import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 119// callback 120try { 121 connection.pairDevice('11:22:33:44:55:66', (err: BusinessError) => { 122 console.info('pairDevice, device name err:' + JSON.stringify(err)); 123 }); 124} catch (err) { 125 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 126} 127 128``` 129 130 131## connection.pairDevice 132 133pairDevice(deviceId: string): Promise<void> 134 135发起蓝牙配对。使用Promise异步回调。 136 137**需要权限**:ohos.permission.ACCESS_BLUETOOTH 138 139**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 140 141**系统能力**:SystemCapability.Communication.Bluetooth.Core 142 143**参数:** 144 145| 参数名 | 类型 | 必填 | 说明 | 146| -------- | ------ | ---- | ----------------------------------- | 147| deviceId | string | 是 | 表示配对的远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | 148 149**返回值:** 150 151| 类型 | 说明 | 152| ------------------- | ------------- | 153| Promise<void> | 返回promise对象。 | 154 155**错误码**: 156 157以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 158 159| 错误码ID | 错误信息 | 160| -------- | ---------------------------- | 161|201 | Permission denied. | 162|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 163|801 | Capability not supported. | 164|2900001 | Service stopped. | 165|2900003 | Bluetooth disabled. | 166|2900099 | Operation failed. | 167 168**示例:** 169 170```js 171import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 172// promise 173try { 174 connection.pairDevice('11:22:33:44:55:66').then(() => { 175 console.info('pairDevice'); 176 }, (error: BusinessError) => { 177 console.info('pairDevice: errCode:' + error.code + ',errMessage' + error.message); 178 }) 179 180} catch (err) { 181 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 182} 183``` 184 185 186## connection.getRemoteDeviceName 187 188getRemoteDeviceName(deviceId: string): string 189 190获取对端蓝牙设备的名称。 191 192**需要权限**:ohos.permission.ACCESS_BLUETOOTH 193 194**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 195 196**系统能力**:SystemCapability.Communication.Bluetooth.Core 197 198**参数:** 199 200| 参数名 | 类型 | 必填 | 说明 | 201| -------- | ------ | ---- | --------------------------------- | 202| deviceId | string | 是 | 表示远程设备的地址,例如:"XX:XX:XX:XX:XX:XX"。 | 203 204**返回值:** 205 206| 类型 | 说明 | 207| ------ | ------------- | 208| string | 以字符串格式返回设备名称。 | 209 210**错误码**: 211 212以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 213 214| 错误码ID | 错误信息 | 215| -------- | ---------------------------- | 216|201 | Permission denied. | 217|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 218|801 | Capability not supported. | 219|2900001 | Service stopped. | 220|2900003 | Bluetooth disabled. | 221|2900099 | Operation failed. | 222 223**示例:** 224 225```js 226import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 227try { 228 let remoteDeviceName: string = connection.getRemoteDeviceName('XX:XX:XX:XX:XX:XX'); 229} catch (err) { 230 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 231} 232``` 233 234 235## connection.getRemoteDeviceName<sup>16+</sup> 236 237getRemoteDeviceName(deviceId: string, alias?: boolean): string 238 239获取对端蓝牙设备的名称,其中alias为可选参数。 240- 如果携带alias,则根据alias判断是否获取对端蓝牙设备别名。 241- 如果未携带alias,则默认返回对端蓝牙设备别名。 242 243**需要权限**:ohos.permission.ACCESS_BLUETOOTH 244 245**原子化服务API**:从API version 16开始,该接口支持在原子化服务中使用。 246 247**系统能力**:SystemCapability.Communication.Bluetooth.Core 248 249**参数:** 250 251| 参数名 | 类型 | 必填 | 说明 | 252| -------- | ------ | ---- | --------------------------------- | 253| deviceId | string | 是 | 表示远程设备的地址,例如:"XX:XX:XX:XX:XX:XX"。 | 254| alias | boolean | 否 | 是否获取对端蓝牙设备别名。获取成功为true,否则设置为false。 | 255 256**返回值:** 257 258| 类型 | 说明 | 259| ------ | ------------- | 260| string | 以字符串格式返回设备名称。 | 261 262**错误码**: 263 264以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 265 266| 错误码ID | 错误信息 | 267| -------- | ---------------------------- | 268|201 | Permission denied. | 269|401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 270|801 | Capability not supported. | 271|2900001 | Service stopped. | 272|2900003 | Bluetooth disabled. | 273|2900099 | Failed to obtain the name or alias of the peer Bluetooth device. | 274 275**示例:** 276 277```js 278import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 279try { 280 let remoteDeviceName: string = connection.getRemoteDeviceName('XX:XX:XX:XX:XX:XX', true); 281} catch (err) { 282 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 283} 284``` 285 286 287## connection.getRemoteDeviceClass 288 289getRemoteDeviceClass(deviceId: string): DeviceClass 290 291获取对端蓝牙设备的类别。 292 293**需要权限**:ohos.permission.ACCESS_BLUETOOTH 294 295**系统能力**:SystemCapability.Communication.Bluetooth.Core 296 297**参数:** 298 299| 参数名 | 类型 | 必填 | 说明 | 300| -------- | ------ | ---- | --------------------------------- | 301| deviceId | string | 是 | 表示远程设备的地址,例如:"XX:XX:XX:XX:XX:XX"。 | 302 303**返回值:** 304 305| 类型 | 说明 | 306| --------------------------- | -------- | 307| [DeviceClass](#deviceclass) | 远程设备的类别。 | 308 309**错误码**: 310 311以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 312 313| 错误码ID | 错误信息 | 314| -------- | ---------------------------- | 315|201 | Permission denied. | 316|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 317|801 | Capability not supported. | 318|2900001 | Service stopped. | 319|2900003 | Bluetooth disabled. | 320|2900099 | Operation failed. | 321 322**示例:** 323 324```js 325import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 326try { 327 let remoteDeviceClass: connection.DeviceClass = connection.getRemoteDeviceClass('XX:XX:XX:XX:XX:XX'); 328} catch (err) { 329 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 330} 331``` 332 333 334## connection.getRemoteProfileUuids<sup>12+</sup> 335 336getRemoteProfileUuids(deviceId: string, callback: AsyncCallback<Array<ProfileUuids>>): void 337 338获取对端蓝牙设备支持的Profile UUID。使用Callback异步回调。 339 340**需要权限**:ohos.permission.ACCESS_BLUETOOTH 341 342**系统能力**:SystemCapability.Communication.Bluetooth.Core 343 344**参数:** 345 346| 参数名 | 类型 | 必填 | 说明 | 347| -------- | ------ | ---- | ----------------------------------- | 348| deviceId | string | 是 | 表示配对的远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | 349| callback | AsyncCallback<Array<[ProfileUuids](js-apis-bluetooth-constant.md#profileuuids12)>> | 是 | 回调函数。当获取UUID成功,err为undefined,否则为错误对象。 | 350 351**错误码**: 352 353以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 354 355| 错误码ID | 错误信息 | 356| -------- | ---------------------------- | 357|201 | Permission denied. | 358|401 | Invalid parameter. | 359|801 | Capability not supported. | 360|2900001 | Service stopped. | 361|2900003 | Bluetooth disabled. | 362|2900099 | Operation failed. | 363 364**示例:** 365 366```js 367import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 368try { 369 connection.getRemoteProfileUuids('XX:XX:XX:XX:XX:XX', (err: BusinessError, data: Array<connection.ProfileUuids>) => { 370 console.info('getRemoteProfileUuids, err: ' + JSON.stringify(err) + ', data: ' + JSON.stringify(data)); 371 }); 372} catch (err) { 373 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 374} 375 376``` 377 378 379## connection.getRemoteProfileUuids<sup>12+</sup> 380 381getRemoteProfileUuids(deviceId: string): Promise<Array<ProfileUuids>> 382 383获取对端蓝牙设备支持的Profile UUID。使用Promise异步回调。 384 385**需要权限**:ohos.permission.ACCESS_BLUETOOTH 386 387**系统能力**:SystemCapability.Communication.Bluetooth.Core 388 389**参数:** 390 391| 参数名 | 类型 | 必填 | 说明 | 392| -------- | ------ | ---- | ----------------------------------- | 393| deviceId | string | 是 | 表示配对的远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | 394 395**返回值:** 396 397| 类型 | 说明 | 398| ------------------- | ------------- | 399| Promise<Array<[ProfileUuids](js-apis-bluetooth-constant.md#profileuuids12)>> | 返回promise对象。 | 400 401**错误码**: 402 403以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 404 405| 错误码ID | 错误信息 | 406| -------- | ---------------------------- | 407|201 | Permission denied. | 408|401 | Invalid parameter. | 409|801 | Capability not supported. | 410|2900001 | Service stopped. | 411|2900003 | Bluetooth disabled. | 412|2900099 | Operation failed. | 413 414**示例:** 415 416```js 417import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 418try { 419 connection.getRemoteProfileUuids('XX:XX:XX:XX:XX:XX').then(() => { 420 console.info('getRemoteProfileUuids'); 421 }, (err: BusinessError) => { 422 console.error('getRemoteProfileUuids: errCode' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 423 }); 424} catch (err) { 425 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 426} 427``` 428 429 430## connection.getLocalName 431 432getLocalName(): string 433 434获取蓝牙本地设备名称。 435 436**需要权限**:ohos.permission.ACCESS_BLUETOOTH 437 438**系统能力**:SystemCapability.Communication.Bluetooth.Core 439 440**返回值:** 441 442| 类型 | 说明 | 443| ------ | --------- | 444| string | 蓝牙本地设备名称。 | 445 446**错误码**: 447 448以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 449 450| 错误码ID | 错误信息 | 451| -------- | ---------------------------- | 452|201 | Permission denied. | 453|801 | Capability not supported. | 454|2900001 | Service stopped. | 455|2900099 | Operation failed. | 456 457**示例:** 458 459```js 460import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 461try { 462 let localName: string = connection.getLocalName(); 463} catch (err) { 464 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 465} 466``` 467 468 469## connection.getPairedDevices 470 471getPairedDevices(): Array<string> 472 473获取蓝牙配对列表。 474 475**需要权限**:ohos.permission.ACCESS_BLUETOOTH 476 477**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 478 479**系统能力**:SystemCapability.Communication.Bluetooth.Core 480 481**返回值:** 482 483| 类型 | 说明 | 484| ------------------- | ------------- | 485| Array<string> | 已配对蓝牙设备的地址列表。<br>- 基于信息安全考虑,此处获取的设备地址为随机MAC地址。<br>- 配对成功后,该地址不会变更。<br>- 已配对设备取消配对后重新扫描或蓝牙服务下电时,该随机地址会变更。 | 486 487**错误码**: 488 489以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 490 491| 错误码ID | 错误信息 | 492| -------- | ---------------------------- | 493|201 | Permission denied. | 494|801 | Capability not supported. | 495|2900001 | Service stopped. | 496|2900003 | Bluetooth disabled. | 497|2900099 | Operation failed. | 498 499**示例:** 500 501```js 502import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 503try { 504 let devices: Array<string> = connection.getPairedDevices(); 505} catch (err) { 506 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 507} 508``` 509 510 511## connection.getPairState<sup>11+</sup> 512 513getPairState(deviceId: string): BondState 514 515获取蓝牙配对状态。 516 517**需要权限**:ohos.permission.ACCESS_BLUETOOTH 518 519**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 520 521**系统能力**:SystemCapability.Communication.Bluetooth.Core 522 523**参数:** 524 525| 参数名 | 类型 | 必填 | 说明 | 526| -------- | ------ | ---- | --------------------------------- | 527| deviceId | string | 是 | 表示远程设备的地址,例如:"XX:XX:XX:XX:XX:XX"。 | 528 529**返回值:** 530 531| 类型 | 说明 | 532| --------------------------- | -------- | 533| [BondState](#bondstate) | 表示设备的蓝牙配对状态。 | 534 535**错误码**: 536 537以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 538 539| 错误码ID | 错误信息 | 540| -------- | ---------------------------- | 541|201 | Permission denied. | 542|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 543|801 | Capability not supported. | 544|2900001 | Service stopped. | 545|2900003 | Bluetooth disabled. | 546|2900099 | Operation failed. | 547 548**示例:** 549 550```js 551import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 552try { 553 let res: connection.BondState = connection.getPairState("XX:XX:XX:XX:XX:XX"); 554 console.info('getPairState: ' + res); 555} catch (err) { 556 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 557} 558``` 559 560 561## connection.getProfileConnectionState 562 563getProfileConnectionState(profileId?: ProfileId): ProfileConnectionState 564 565获取蓝牙Profile的连接状态,其中ProfileId为可选参数。 566- 如果携带ProfileId,则返回的是当前Profile的连接状态。 567- 如果未携带ProfileId,任一Profile已连接则返回[STATE_CONNECTED](js-apis-bluetooth-constant.md#profileconnectionstate),否则返回[STATE_DISCONNECTED](js-apis-bluetooth-constant.md#profileconnectionstate)。 568 569**需要权限**:ohos.permission.ACCESS_BLUETOOTH 570 571**系统能力**:SystemCapability.Communication.Bluetooth.Core 572 573**参数:** 574 575| 参数名 | 类型 | 必填 | 说明 | 576| --------- | --------- | ---- | ------------------------------------- | 577| profileId | [ProfileId](js-apis-bluetooth-constant.md#profileid) | 否 | 表示profile的枚举值,例如:PROFILE_A2DP_SOURCE。 | 578 579**返回值:** 580 581| 类型 | 说明 | 582| ------------------------------------------------- | ------------------- | 583| [ProfileConnectionState](js-apis-bluetooth-constant.md#profileconnectionstate) | profile的连接状态。 | 584 585**错误码**: 586 587以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 588 589| 错误码ID | 错误信息 | 590| -------- | ---------------------------- | 591|201 | Permission denied. | 592|401 | Invalid parameter. Possible causes: 1. Incorrect parameter types. | 593|801 | Capability not supported. | 594|2900001 | Service stopped. | 595|2900003 | Bluetooth disabled. | 596|2900004 | Profile not supported. | 597|2900099 | Operation failed. | 598 599**示例:** 600 601```js 602import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 603import { constant } from '@kit.ConnectivityKit'; 604try { 605 let result: connection.ProfileConnectionState = connection.getProfileConnectionState(constant.ProfileId.PROFILE_A2DP_SOURCE); 606} catch (err) { 607 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 608} 609``` 610 611 612## connection.setDevicePairingConfirmation 613 614setDevicePairingConfirmation(deviceId: string, accept: boolean): void 615 616设置设备配对请求确认。 617 618**需要权限**:ohos.permission.ACCESS_BLUETOOTH 和 ohos.permission.MANAGE_BLUETOOTH(该权限仅系统应用可申请) 619 620**系统能力**:SystemCapability.Communication.Bluetooth.Core 621 622**参数:** 623 624| 参数名 | 类型 | 必填 | 说明 | 625| ------ | ------- | ---- | -------------------------------- | 626| deviceId | string | 是 | 表示远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。 | 627| accept | boolean | 是 | 接受配对请求设置为true,否则设置为false。 | 628 629**错误码**: 630 631以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 632 633| 错误码ID | 错误信息 | 634| -------- | ---------------------------- | 635|201 | Permission denied. | 636|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 637|801 | Capability not supported. | 638|2900001 | Service stopped. | 639|2900003 | Bluetooth disabled. | 640|2900099 | Operation failed. | 641 642**示例:** 643 644```js 645import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 646// 订阅“pinRequired”配对请求事件,收到远端配对请求后设置配对确认。 647function onReceivePinRequiredEvent(data: connection.PinRequiredParam) { // data为配对请求的入参,配对请求参数。 648 console.info('pin required = '+ JSON.stringify(data)); 649 connection.setDevicePairingConfirmation(data.deviceId, true); 650} 651try { 652 connection.on('pinRequired', onReceivePinRequiredEvent); 653} catch (err) { 654 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 655} 656``` 657 658 659## connection.setDevicePinCode 660 661setDevicePinCode(deviceId: string, code: string, callback: AsyncCallback<void>): void 662 663当蓝牙配对类型PinType为PIN_TYPE_ENTER_PIN_CODE或PIN_TYPE_PIN_16_DIGITS时调用此接口,请求用户输入PIN码。使用Callback异步回调。 664 665**需要权限**:ohos.permission.ACCESS_BLUETOOTH 666 667**系统能力**:SystemCapability.Communication.Bluetooth.Core 668 669**参数:** 670 671| 参数名 | 类型 | 必填 | 说明 | 672| ------ | ------- | ---- | -------------------------------- | 673| deviceId | string | 是 | 表示远端设备MAC地址,例如:"XX:XX:XX:XX:XX:XX"。 | 674| code | string | 是 | 用户输入的PIN码。 | 675| callback | AsyncCallback<void> | 是 | 回调函数,当设置PinCode成功,err为undefined,否则为错误对象。 | 676 677**错误码**: 678 679以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 680 681| 错误码ID | 错误信息 | 682| -------- | ---------------------------- | 683|201 | Permission denied. | 684|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 685|801 | Capability not supported. | 686|2900001 | Service stopped. | 687|2900003 | Bluetooth disabled. | 688|2900099 | Operation failed. | 689 690**示例:** 691 692```js 693import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 694// callback 695try { 696 connection.setDevicePinCode('11:22:33:44:55:66', '12345', (err: BusinessError) => { 697 console.info('setDevicePinCode,device name err:' + JSON.stringify(err)); 698 }); 699} catch (err) { 700 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 701} 702``` 703 704 705## connection.setDevicePinCode 706 707setDevicePinCode(deviceId: string, code: string): Promise<void> 708 709当蓝牙配对类型PinType为PIN_TYPE_ENTER_PIN_CODE或PIN_TYPE_PIN_16_DIGITS时调用此接口,请求用户输入PIN码。使用Promise异步回调。 710 711**需要权限**:ohos.permission.ACCESS_BLUETOOTH 712 713**系统能力**:SystemCapability.Communication.Bluetooth.Core 714 715**参数:** 716 717| 参数名 | 类型 | 必填 | 说明 | 718| ------ | ------- | ---- | -------------------------------- | 719| deviceId | string | 是 | 表示远端设备MAC地址,例如:"XX:XX:XX:XX:XX:XX"。 | 720| code | string | 是 | 用户输入的PIN码。 | 721 722**返回值:** 723 724| 类型 | 说明 | 725| ------------------- | ------------- | 726| Promise<void> | 返回promise对象。 | 727 728**错误码**: 729 730以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 731 732| 错误码ID | 错误信息 | 733| -------- | ---------------------------- | 734|201 | Permission denied. | 735|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 736|801 | Capability not supported. | 737|2900001 | Service stopped. | 738|2900003 | Bluetooth disabled. | 739|2900099 | Operation failed. | 740 741**示例:** 742 743```js 744import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 745// promise 746try { 747 connection.setDevicePinCode('11:22:33:44:55:66', '12345').then(() => { 748 console.info('setDevicePinCode'); 749 }, (error: BusinessError) => { 750 console.info('setDevicePinCode: errCode:' + error.code + ',errMessage' + error.message); 751 }) 752 753} catch (err) { 754 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 755} 756``` 757 758 759## connection.setLocalName<sup>(deprecated)</sup> 760 761setLocalName(name: string): void 762 763设置蓝牙本地设备名称。 764 765> **说明:**<br/> 766> 从API version 10开始支持,从API version 12开始废弃,不再提供替代接口。 767 768**需要权限**:ohos.permission.ACCESS_BLUETOOTH 769 770**系统能力**:SystemCapability.Communication.Bluetooth.Core 771 772**参数:** 773 774| 参数名 | 类型 | 必填 | 说明 | 775| ---- | ------ | ---- | --------------------- | 776| name | string | 是 | 要设置的蓝牙名称,最大长度为248字节数。 | 777 778**错误码**: 779 780以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 781 782| 错误码ID | 错误信息 | 783| -------- | ---------------------------- | 784|201 | Permission denied. | 785|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 786|801 | Capability not supported. | 787|2900001 | Service stopped. | 788|2900003 | Bluetooth disabled. | 789|2900099 | Operation failed. | 790 791**示例:** 792 793```js 794import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 795try { 796 connection.setLocalName('device_name'); 797} catch (err) { 798 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 799} 800``` 801 802 803## connection.setBluetoothScanMode 804 805setBluetoothScanMode(mode: ScanMode, duration: number): void 806 807设置蓝牙扫描模式,可以被远端设备发现。 808 809**需要权限**:ohos.permission.ACCESS_BLUETOOTH 810 811**系统能力**:SystemCapability.Communication.Bluetooth.Core 812 813**参数:** 814 815| 参数名 | 类型 | 必填 | 说明 | 816| -------- | --------------------- | ---- | ---------------------------- | 817| mode | [ScanMode](#scanmode) | 是 | 蓝牙扫描模式。当扫描模式为SCAN_MODE_GENERAL_DISCOVERABLE时,超出duration持续时间(不为0),扫描模式会重新设置为SCAN_MODE_CONNECTABLE。 | 818| duration | number | 是 | 设备可被发现的持续时间,单位为毫秒。设置为0则持续可发现。 | 819 820**错误码**: 821 822以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 823 824| 错误码ID | 错误信息 | 825| -------- | ---------------------------- | 826|201 | Permission denied. | 827|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 828|801 | Capability not supported. | 829|2900001 | Service stopped. | 830|2900003 | Bluetooth disabled. | 831|2900099 | Operation failed. | 832 833**示例:** 834 835```js 836import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 837try { 838 // 设置为可连接可发现才可被远端设备扫描到,可以连接。 839 connection.setBluetoothScanMode(connection.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100); 840} catch (err) { 841 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 842} 843``` 844 845 846## connection.getBluetoothScanMode 847 848getBluetoothScanMode(): ScanMode 849 850获取蓝牙扫描模式。 851 852**需要权限**:ohos.permission.ACCESS_BLUETOOTH 853 854**系统能力**:SystemCapability.Communication.Bluetooth.Core 855 856**返回值:** 857 858| 类型 | 说明 | 859| --------------------- | ------- | 860| [ScanMode](#scanmode) | 蓝牙扫描模式。 | 861 862**错误码**: 863 864以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 865 866| 错误码ID | 错误信息 | 867| -------- | ---------------------------- | 868|201 | Permission denied. | 869|801 | Capability not supported. | 870|2900001 | Service stopped. | 871|2900003 | Bluetooth disabled. | 872|2900099 | Operation failed. | 873 874**示例:** 875 876```js 877import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 878try { 879 let scanMode: connection.ScanMode = connection.getBluetoothScanMode(); 880} catch (err) { 881 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 882} 883``` 884 885 886## connection.startBluetoothDiscovery 887 888startBluetoothDiscovery(): void 889 890开启蓝牙扫描,可以发现远端设备。 891 892**需要权限**:ohos.permission.ACCESS_BLUETOOTH 893 894**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 895 896**系统能力**:SystemCapability.Communication.Bluetooth.Core 897 898**错误码**: 899 900以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 901 902| 错误码ID | 错误信息 | 903| -------- | ---------------------------- | 904|201 | Permission denied. | 905|801 | Capability not supported. | 906|2900001 | Service stopped. | 907|2900003 | Bluetooth disabled. | 908|2900099 | Operation failed. | 909 910**示例:** 911 912```js 913import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 914function onReceiveEvent(data: Array<string>) { 915 console.info('data length' + data.length); 916} 917try { 918 connection.on('bluetoothDeviceFind', onReceiveEvent); 919 connection.startBluetoothDiscovery(); 920} catch (err) { 921 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 922} 923``` 924 925 926## connection.stopBluetoothDiscovery 927 928stopBluetoothDiscovery(): void 929 930关闭蓝牙扫描。 931 932**需要权限**:ohos.permission.ACCESS_BLUETOOTH 933 934**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 935 936**系统能力**:SystemCapability.Communication.Bluetooth.Core 937 938**错误码**: 939 940以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 941 942| 错误码ID | 错误信息 | 943| -------- | ---------------------------- | 944|201 | Permission denied. | 945|801 | Capability not supported. | 946|2900001 | Service stopped. | 947|2900003 | Bluetooth disabled. | 948|2900099 | Operation failed. | 949 950**示例:** 951 952```js 953import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 954try { 955 connection.stopBluetoothDiscovery(); 956} catch (err) { 957 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 958} 959``` 960 961 962## connection.isBluetoothDiscovering<sup>11+</sup> 963 964isBluetoothDiscovering(): boolean 965 966查询设备的蓝牙发现状态。 967 968**需要权限**:ohos.permission.ACCESS_BLUETOOTH 969 970**系统能力**:SystemCapability.Communication.Bluetooth.Core 971 972**返回值:** 973 974| 类型 | 说明 | 975| ------------------- | ------------- | 976| boolean | 设备已开启蓝牙发现为true,否则为false。 | 977 978**错误码**: 979 980以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 981 982| 错误码ID | 错误信息 | 983| -------- | ---------------------------- | 984|201 | Permission denied. | 985|801 | Capability not supported. | 986|2900001 | Service stopped. | 987|2900003 | Bluetooth disabled. | 988|2900099 | Operation failed. | 989 990**示例:** 991 992```js 993import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 994try { 995 let res: boolean = connection.isBluetoothDiscovering(); 996 console.info('isBluetoothDiscovering: ' + res); 997} catch (err) { 998 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 999} 1000``` 1001 1002## connection.setRemoteDeviceName<sup>12+</sup> 1003 1004setRemoteDeviceName(deviceId: string, name: string): Promise<void> 1005 1006设置蓝牙远端设备名称。使用Promise异步回调。 1007 1008**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1009 1010**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1011 1012**系统能力**:SystemCapability.Communication.Bluetooth.Core 1013 1014**参数:** 1015 1016| 参数名 | 类型 | 必填 | 说明 | 1017| -------- | ----------------------------------- | ---- | -------------------------------------- | 1018| deviceId | string | 是 | 表示远端设备MAC地址,例如:"XX:XX:XX:XX:XX:XX"。 | 1019| name | string | 是 | 修改远端设备名称,最大长度为64字节。 | 1020 1021**返回值:** 1022 1023| 类型 | 说明 | 1024| ------------------- | ------------- | 1025| Promise<void> | 以Promise形式返回设置蓝牙远端设备名称的结果,设置失败时返回错误码信息。 | 1026 1027**错误码**: 1028 1029以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1030 1031| 错误码ID | 错误信息 | 1032| -------- | ---------------------------- | 1033|201 | Permission denied. | 1034|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1035|2900001 | Service stopped. | 1036|2900003 | Bluetooth disabled. | 1037 1038**示例:** 1039 1040```js 1041import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1042// promise 1043try { 1044 connection.setRemoteDeviceName('11:22:33:44:55:66', 'RemoteDeviceName').then(() => { 1045 console.info('setRemoteDeviceName success'); 1046 }, (error: BusinessError) => { 1047 console.error('setRemoteDeviceName: errCode:' + error.code + ',errMessage' + error.message); 1048 }) 1049 1050} catch (err) { 1051 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1052} 1053``` 1054 1055 1056## connection.getRemoteDeviceBatteryInfo<sup>12+</sup> 1057 1058getRemoteDeviceBatteryInfo(deviceId: string): Promise<BatteryInfo> 1059 1060获取蓝牙远端设备的电量信息。使用Promise异步回调。 1061 1062**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1063 1064**系统能力**:SystemCapability.Communication.Bluetooth.Core 1065 1066**参数:** 1067 1068| 参数名 | 类型 | 必填 | 说明 | 1069| ------ | ------- | ---- | -------------------------------- | 1070| deviceId | string | 是 | 表示远端设备MAC地址,例如:"11:22:33:AA:BB:FF"。 | 1071 1072**返回值:** 1073 1074| 类型 | 说明 | 1075| ------------------- | ------------- | 1076| Promise<[BatteryInfo](#batteryinfo12)> | 以Promise形式返回蓝牙远端设备的电量信息。 | 1077 1078**错误码**: 1079 1080以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1081 1082| 错误码ID | 错误信息 | 1083| -------- | ---------------------------- | 1084|201 | Permission denied. | 1085|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1086|2900001 | Service stopped. | 1087|2900003 | Bluetooth disabled. | 1088 1089**示例:** 1090 1091```js 1092import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1093// promise 1094try { 1095 connection.getRemoteDeviceBatteryInfo('11:22:33:AA:BB:FF').then((data: connection.BatteryInfo) => { 1096 console.info('getRemoteDeviceBatteryInfo success, DeviceType:' + JSON.stringify(data)); 1097 }); 1098} catch (err) { 1099 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1100} 1101``` 1102 1103 1104## connection.on('batteryChange')<sup>12+</sup> 1105 1106on(type: 'batteryChange', callback: Callback<BatteryInfo>): void 1107 1108订阅蓝牙远程设备的电量信息变更事件。使用Callback异步回调。 1109 1110**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1111 1112**系统能力**:SystemCapability.Communication.Bluetooth.Core 1113 1114**参数:** 1115 1116| 参数名 | 类型 | 必填 | 说明 | 1117| -------- | ----------------------------------- | ---- | -------------------------------------- | 1118| type | string | 是 | 填写"batteryChange"字符串,表示蓝牙远端设备的电池信息变更事件。 | 1119| callback | Callback<[BatteryInfo](#batteryinfo12)> | 是 | 表示回调函数的入参,返回电量信息。 | 1120 1121**错误码**: 1122 1123以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1124 1125| 错误码ID | 错误信息 | 1126| -------- | ---------------------------- | 1127|201 | Permission denied. | 1128|2900099 | Operation failed. | 1129 1130**示例:** 1131 1132```js 1133import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1134let onReceiveEvent: (data: connection.BatteryInfo) => void = (data: connection.BatteryInfo) => { 1135 console.info('BatteryInfo = '+ JSON.stringify(data)); 1136} 1137try { 1138 connection.on('batteryChange', onReceiveEvent); 1139} catch (err) { 1140 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1141} 1142``` 1143 1144 1145## connection.off('batteryChange')<sup>12+</sup> 1146 1147off(type: 'batteryChange', callback?: Callback<BatteryInfo>): void 1148 1149取消订阅蓝牙远程设备的电量信息变更事件。 1150 1151**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1152 1153**系统能力**:SystemCapability.Communication.Bluetooth.Core 1154 1155**参数:** 1156 1157| 参数名 | 类型 | 必填 | 说明 | 1158| -------- | ----------------------------------- | ---- | ---------------------------------------- | 1159| type | string | 是 | 填写"batteryChange"字符串,表示取消蓝牙远端设备的电池信息变更事件。 | 1160| callback | Callback<[BatteryInfo](#batteryinfo12)> | 否 | 表示回调函数的入参,返回电量信息。 | 1161 1162**错误码**: 1163 1164以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1165 1166| 错误码ID | 错误信息 | 1167| -------- | ---------------------------- | 1168|201 | Permission denied. | 1169|2900099 | Operation failed. | 1170 1171**示例:** 1172 1173```js 1174import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1175let onReceiveEvent: (data: connection.BatteryInfo) => void = (data: connection.BatteryInfo) => { 1176 console.info('BatteryInfo = '+ JSON.stringify(data)); 1177} 1178try { 1179 connection.on('batteryChange', onReceiveEvent); 1180 connection.off('batteryChange', onReceiveEvent); 1181} catch (err) { 1182 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1183} 1184``` 1185 1186 1187## connection.on('bluetoothDeviceFind') 1188 1189on(type: 'bluetoothDeviceFind', callback: Callback<Array<string>>): void 1190 1191订阅蓝牙设备发现上报事件。使用Callback异步回调。 1192 1193**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1194 1195**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1196 1197**系统能力**:SystemCapability.Communication.Bluetooth.Core 1198 1199**参数:** 1200 1201| 参数名 | 类型 | 必填 | 说明 | 1202| -------- | ----------------------------------- | ---- | -------------------------------------- | 1203| type | string | 是 | 填写"bluetoothDeviceFind"字符串,表示蓝牙设备发现事件。 | 1204| callback | Callback<Array<string>> | 是 | 表示回调函数的入参,发现的设备集合。回调函数由用户创建通过该接口注册。基于信息安全考虑,此处获取的设备地址为随机MAC地址。配对成功后,该地址不会变更;已配对设备取消配对后重新扫描或蓝牙服务下电时,该随机地址会变更。 | 1205 1206**错误码**: 1207 1208以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1209 1210| 错误码ID | 错误信息 | 1211| -------- | ---------------------------- | 1212|201 | Permission denied. | 1213|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1214|801 | Capability not supported. | 1215|2900099 | Operation failed. | 1216 1217**示例:** 1218 1219```js 1220import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1221function onReceiveEvent(data: Array<string>) { // data为蓝牙设备地址集合。 1222 console.info('bluetooth device find = '+ JSON.stringify(data)); 1223} 1224try { 1225 connection.on('bluetoothDeviceFind', onReceiveEvent); 1226} catch (err) { 1227 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1228} 1229``` 1230 1231 1232## connection.off('bluetoothDeviceFind') 1233 1234off(type: 'bluetoothDeviceFind', callback?: Callback<Array<string>>): void 1235 1236取消订阅蓝牙设备发现上报事件。 1237 1238**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1239 1240**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1241 1242**系统能力**:SystemCapability.Communication.Bluetooth.Core 1243 1244**参数:** 1245 1246| 参数名 | 类型 | 必填 | 说明 | 1247| -------- | ----------------------------------- | ---- | ---------------------------------------- | 1248| type | string | 是 | 填写"bluetoothDeviceFind"字符串,表示蓝牙设备发现事件。 | 1249| callback | Callback<Array<string>> | 否 | 表示取消订阅蓝牙设备发现事件上报。不填该参数则取消订阅该type对应的所有回调。 | 1250 1251**错误码**: 1252 1253以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1254 1255| 错误码ID | 错误信息 | 1256| -------- | ---------------------------- | 1257|201 | Permission denied. | 1258|801 | Capability not supported. | 1259|2900099 | Operation failed. | 1260 1261**示例:** 1262 1263```js 1264import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1265function onReceiveEvent(data: Array<string>) { 1266 console.info('bluetooth device find = '+ JSON.stringify(data)); 1267} 1268try { 1269 connection.on('bluetoothDeviceFind', onReceiveEvent); 1270 connection.off('bluetoothDeviceFind', onReceiveEvent); 1271} catch (err) { 1272 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1273} 1274``` 1275 1276 1277## connection.on('bondStateChange') 1278 1279on(type: 'bondStateChange', callback: Callback<BondStateParam>): void 1280 1281订阅蓝牙配对状态改变事件。使用Callback异步回调。 1282 1283**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1284 1285**系统能力**:SystemCapability.Communication.Bluetooth.Core 1286 1287**参数:** 1288 1289| 参数名 | 类型 | 必填 | 说明 | 1290| -------- | ---------------------------------------- | ---- | ------------------------------------ | 1291| type | string | 是 | 填写"bondStateChange"字符串,表示蓝牙配对状态改变事件。 | 1292| callback | Callback<[BondStateParam](#bondstateparam)> | 是 | 表示回调函数的入参,配对的状态。回调函数由用户创建通过该接口注册。 | 1293 1294**错误码**: 1295 1296以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1297 1298| 错误码ID | 错误信息 | 1299| -------- | ---------------------------- | 1300|201 | Permission denied. | 1301|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1302|801 | Capability not supported. | 1303|2900099 | Operation failed. | 1304 1305**示例:** 1306 1307```js 1308import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1309function onReceiveEvent(data: connection.BondStateParam) { // data为回调函数入参,表示配对的状态。 1310 console.info('pair state = '+ JSON.stringify(data)); 1311} 1312try { 1313 connection.on('bondStateChange', onReceiveEvent); 1314} catch (err) { 1315 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1316} 1317``` 1318 1319 1320## connection.off('bondStateChange') 1321 1322off(type: 'bondStateChange', callback?: Callback<BondStateParam>): void 1323 1324取消订阅蓝牙配对状态改变事件。 1325 1326**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1327 1328**系统能力**:SystemCapability.Communication.Bluetooth.Core 1329 1330**参数:** 1331 1332| 参数名 | 类型 | 必填 | 说明 | 1333| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 1334| type | string | 是 | 填写"bondStateChange"字符串,表示蓝牙配对状态改变事件。 | 1335| callback | Callback<[BondStateParam](#bondstateparam)> | 否 | 表示取消订阅蓝牙配对状态改变事件上报。不填该参数则取消订阅该type对应的所有回调。 | 1336 1337**错误码**: 1338 1339以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1340 1341| 错误码ID | 错误信息 | 1342| -------- | ---------------------------- | 1343|201 | Permission denied. | 1344|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1345|801 | Capability not supported. | 1346|2900099 | Operation failed. | 1347 1348**示例:** 1349 1350```js 1351import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1352function onReceiveEvent(data: connection.BondStateParam) { 1353 console.info('bond state = '+ JSON.stringify(data)); 1354} 1355try { 1356 connection.on('bondStateChange', onReceiveEvent); 1357 connection.off('bondStateChange', onReceiveEvent); 1358} catch (err) { 1359 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1360} 1361``` 1362 1363 1364## connection.on('pinRequired') 1365 1366on(type: 'pinRequired', callback: Callback<PinRequiredParam>): void 1367 1368订阅远端蓝牙设备的配对请求事件。使用Callback异步回调。 1369 1370**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1371 1372**系统能力**:SystemCapability.Communication.Bluetooth.Core 1373 1374**参数:** 1375 1376| 参数名 | 类型 | 必填 | 说明 | 1377| -------- | ---------------------------------------- | ---- | -------------------------------- | 1378| type | string | 是 | 填写"pinRequired"字符串,表示配对请求事件。 | 1379| callback | Callback<[PinRequiredParam](#pinrequiredparam)> | 是 | 表示回调函数的入参,配对请求。回调函数由用户创建通过该接口注册。 | 1380 1381**错误码**: 1382 1383以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1384 1385| 错误码ID | 错误信息 | 1386| -------- | ---------------------------- | 1387|201 | Permission denied. | 1388|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1389|801 | Capability not supported. | 1390|2900099 | Operation failed. | 1391 1392**示例:** 1393 1394```js 1395import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1396function onReceiveEvent(data: connection.PinRequiredParam) { // data为配对请求参数。 1397 console.info('pin required = '+ JSON.stringify(data)); 1398} 1399try { 1400 connection.on('pinRequired', onReceiveEvent); 1401} catch (err) { 1402 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1403} 1404``` 1405 1406 1407## connection.off('pinRequired') 1408 1409off(type: 'pinRequired', callback?: Callback<PinRequiredParam>): void 1410 1411取消订阅远端蓝牙设备的配对请求事件。 1412 1413**需要权限**:ohos.permission.ACCESS_BLUETOOTH 1414 1415**系统能力**:SystemCapability.Communication.Bluetooth.Core 1416 1417**参数:** 1418 1419| 参数名 | 类型 | 必填 | 说明 | 1420| -------- | ---------------------------------------- | ---- | ---------------------------------------- | 1421| type | string | 是 | 填写"pinRequired"字符串,表示配对请求事件。 | 1422| callback | Callback<[PinRequiredParam](#pinrequiredparam)> | 否 | 表示取消订阅蓝牙配对请求事件上报,入参为配对请求参数。不填该参数则取消订阅该type对应的所有回调。 | 1423 1424**错误码**: 1425 1426以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1427 1428| 错误码ID | 错误信息 | 1429| -------- | ---------------------------- | 1430|201 | Permission denied. | 1431|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1432|801 | Capability not supported. | 1433|2900099 | Operation failed. | 1434 1435**示例:** 1436 1437```js 1438import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1439function onReceiveEvent(data: connection.PinRequiredParam) { 1440 console.info('pin required = '+ JSON.stringify(data)); 1441} 1442try { 1443 connection.on('pinRequired', onReceiveEvent); 1444 connection.off('pinRequired', onReceiveEvent); 1445} catch (err) { 1446 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1447} 1448``` 1449 1450 1451## connection.getLastConnectionTime<sup>15+</sup> 1452 1453getLastConnectionTime(deviceId: string): Promise<number> 1454 1455获取蓝牙远端设备最近一次连接的时间点。使用Promise异步回调。 1456 1457**系统能力**:SystemCapability.Communication.Bluetooth.Core 1458 1459**参数:** 1460 1461| 参数名 | 类型 | 必填 | 说明 | 1462| ------ | ------- | ---- | -------------------------------- | 1463| deviceId | string | 是 | 表示远端设备MAC地址。例如:"XX:XX:XX:XX:XX:XX"。 | 1464 1465**返回值:** 1466 1467| 类型 | 说明 | 1468| ------------------- | ------------- | 1469| Promise<number> | 以Promise形式返回设置蓝牙远端设备最近一次连接的时间点结果,返回promise对象。 | 1470 1471**错误码**: 1472 1473以下错误码的详细介绍请参见[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1474 1475| 错误码ID | 错误信息 | 1476| -------- | ---------------------------- | 1477|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1478|801 | Capability not supported. | 1479|2900001 | Service stopped. | 1480|2900003 | Bluetooth disabled. | 1481|2900099 | Operation failed. | 1482 1483**示例:** 1484 1485```js 1486import { connection } from '@kit.ConnectivityKit'; 1487// promise 1488try { 1489 connection.getLastConnectionTime('11:22:33:44:55:66').then((time: number) => { 1490 console.info('connectionTime: ${time}'); 1491 }); 1492} catch (err) { 1493 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1494} 1495``` 1496 1497## connection.connectAllowedProfiles<sup>16+</sup> 1498 1499connectAllowedProfiles(deviceId: string, callback: AsyncCallback<void>): void 1500 1501连接远端设备所有允许连接的profiles。使用Callback异步回调。<br/>需先调用pairDevice发起配对,且仅允许在每次发起配对后30s内调用此接口一次。<br/>建议用法:订阅UUID_VALUE公共事件回调,配对成功后会收到公共事件回调。建议在此回调中调用connectAllowedProfiles接口。 1502 1503**需要权限:**: ohos.permission.ACCESS_BLUETOOTH 1504 1505**系统能力:**: SystemCapability.Communication.Bluetooth.Core 1506 1507**参数:** 1508 1509| 参数名 | 类型 | 必填 | 说明 | 1510| -------- | ------ | ---- | ----------------------------------- | 1511| deviceId | string | 是 | 表示连接的远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。| 1512| callback | AsyncCallback<void> | 是 | 回调函数。当发起连接成功,err为undefined,否则为错误对象。 | 1513 1514**错误码:** 1515 1516以下错误码的详细介绍请参见 [通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1517 1518| 错误码ID| 错误信息| 1519| -------- | ---------------------------- | 1520|201 | Permission denied. | 1521|401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1522|801 | Capability not supported. | 1523|2900001 | Service stopped. | 1524|2900003 | Bluetooth disabled. | 1525|2900099 | Operation failed. | 1526 1527**示例:** 1528 1529```js 1530import { commonEventManager, AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1531import { connection } from '@kit.ConnectivityKit'; 1532// 定义订阅者,用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 1533let subscriber: commonEventManager.CommonEventSubscriber; 1534// 订阅者信息 1535let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = { 1536 events: ["usual.event.bluetooth.remotedevice.UUID_VALUE"] 1537}; 1538// 订阅公共事件回调 1539function SubscribeCB(err: BusinessError, data: commonEventManager.CommonEventData) { 1540 if (err) { 1541 console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`); 1542 } else { 1543 console.info(`Succeeded in subscribing, data is ` + JSON.stringify(data)); 1544 // 调用connectAllowedProfiles前,需确保已收到UUID_VALUE的系统公共事件 1545 try { 1546 connection.connectAllowedProfiles('68:13:24:79:4C:8C', (err: BusinessError) => { 1547 if (err) { 1548 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1549 return; 1550 } 1551 console.info('connectAllowedProfiles, err: ' + JSON.stringify(err)); 1552 }); 1553 } catch (err) { 1554 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1555 } 1556 } 1557} 1558// 创建订阅者回调 1559function createCB(err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) { 1560 if(!err) { 1561 console.info(`Succeeded in creating subscriber.`); 1562 subscriber = commonEventSubscriber; 1563 // 订阅公共事件 1564 try { 1565 commonEventManager.subscribe(subscriber, SubscribeCB); 1566 } catch (error) { 1567 let err: BusinessError = error as BusinessError; 1568 console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`); 1569 } 1570 } else { 1571 console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`); 1572 } 1573} 1574 1575// 创建订阅者,并订阅公共事件回调 1576try { 1577 commonEventManager.createSubscriber(subscribeInfo, createCB); 1578} catch (error) { 1579 let err: BusinessError = error as BusinessError; 1580 console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`); 1581} 1582``` 1583 1584 1585## connection.connectAllowedProfiles<sup>16+</sup> 1586 1587connectAllowedProfiles(deviceId: string): Promise<void> 1588 1589连接远端设备所有允许连接的profiles。使用Promise异步回调。<br/>需先调用pairDevice发起配对,且仅允许在每次发起配对后30s内调用此接口一次。<br/>建议用法:订阅UUID_VALUE公共事件回调,配对成功后会收到公共事件回调.建议在此回调中调用connectAllowedProfiles接口。 1590 1591**需要权限:**: ohos.permission.ACCESS_BLUETOOTH 1592 1593**系统能力:**: SystemCapability.Communication.Bluetooth.Core 1594 1595**参数:** 1596 1597| 参数名 | 类型 | 必填 | 说明 | 1598| -------- | ------ | ---- | ----------------------------------- | 1599| deviceId | string | 是 | 表示连接的远端设备地址,例如:"XX:XX:XX:XX:XX:XX"。| 1600 1601**返回值:** 1602 1603| 类型 | 说明 | 1604| ------------------------------------------------- | ------------------- | 1605| Promise<void> | Promise对象。| 1606 1607**错误码:** 1608 1609以下错误码的详细介绍请参见 [通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。 1610 1611| 错误码ID| 错误信息| 1612| -------- | ---------------------------- | 1613|201 | Permission denied. | 1614|401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | 1615|801 | Capability not supported. | 1616|2900001 | Service stopped. | 1617|2900003 | Bluetooth disabled. | 1618|2900099 | Operation failed. | 1619 1620**示例:** 1621 1622```js 1623import { commonEventManager, AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; 1624import { connection } from '@kit.ConnectivityKit'; 1625// 定义订阅者,用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 1626let subscriber: commonEventManager.CommonEventSubscriber; 1627// 订阅者信息 1628let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = { 1629 events: ["usual.event.bluetooth.remotedevice.UUID_VALUE"] 1630}; 1631// 订阅公共事件回调 1632function SubscribeCB(err: BusinessError, data: commonEventManager.CommonEventData) { 1633 if (err) { 1634 console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`); 1635 } else { 1636 console.info(`Succeeded in subscribing, data is ` + JSON.stringify(data)); 1637 // 调用connectAllowedProfiles前,需确保已收到UUID_VALUE的系统公共事件 1638 try { 1639 connection.connectAllowedProfiles('68:13:24:79:4C:8C').then(() => { 1640 console.info('connectAllowedProfiles'); 1641 }, (err: BusinessError) => { 1642 console.error('connectAllowedProfiles:errCode' + err.code + ', errMessage: ' + err.message); 1643 }); 1644 } catch (err) { 1645 console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); 1646 } 1647 } 1648} 1649// 创建订阅者回调 1650function createCB(err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) { 1651 if(!err) { 1652 console.info(`Succeeded in creating subscriber.`); 1653 subscriber = commonEventSubscriber; 1654 // 订阅公共事件 1655 try { 1656 commonEventManager.subscribe(subscriber, SubscribeCB); 1657 } catch (error) { 1658 let err: BusinessError = error as BusinessError; 1659 console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`); 1660 } 1661 } else { 1662 console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`); 1663 } 1664} 1665 1666// 创建订阅者,并订阅公共事件回调 1667try { 1668 commonEventManager.createSubscriber(subscribeInfo, createCB); 1669} catch (error) { 1670 let err: BusinessError = error as BusinessError; 1671 console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`); 1672} 1673``` 1674 1675## BondStateParam 1676 1677描述配对状态参数。 1678 1679**系统能力**:SystemCapability.Communication.Bluetooth.Core 1680 1681| 名称 | 类型 | 可读 | 可写 | 说明 | 1682| -------- | ------ | ---- | ---- | ----------- | 1683| deviceId | string | 是 | 否 | 表示要配对的设备ID。 | 1684| state | BondState | 是 | 否 | 表示配对设备的状态。 | 1685| cause<sup>12+</sup>| [UnbondCause](#unbondcause12) | 是 | 否 | 表示配对失败的原因。| 1686 1687 1688## PinRequiredParam 1689 1690描述配对请求参数。 1691 1692**系统能力**:SystemCapability.Communication.Bluetooth.Core 1693 1694| 名称 | 类型 | 可读 | 可写 | 说明 | 1695| -------- | ------ | ---- | ---- | ----------- | 1696| deviceId | string | 是 | 否 | 表示要配对的设备ID。 | 1697| pinCode | string | 是 | 否 | 表示要配对的密钥。 | 1698 1699 1700 1701## DeviceClass 1702 1703描述蓝牙设备的类别。 1704 1705**系统能力**:SystemCapability.Communication.Bluetooth.Core 1706 1707| 名称 | 类型 | 可读 | 可写 | 说明 | 1708| --------------- | ----------------------------------- | ---- | ---- | ---------------- | 1709| majorClass | [MajorClass](js-apis-bluetooth-constant.md#majorclass) | 是 | 否 | 表示蓝牙设备主要类别的枚举。 | 1710| majorMinorClass | [MajorMinorClass](js-apis-bluetooth-constant.md#majorminorclass) | 是 | 否 | 表示主要次要蓝牙设备类别的枚举。 | 1711| classOfDevice | number | 是 | 否 | 表示设备类别。 | 1712 1713 1714## BatteryInfo<sup>12+</sup> 1715 1716描述电量信息的内容。 1717 1718**系统能力**:SystemCapability.Communication.Bluetooth.Core 1719 1720| 名称 | 类型 | 可读 | 可写 | 说明 | 1721| -------- | ------ | ---- | ---- | ----------- | 1722| batteryLevel | number | 是 | 否 | 表示远端设备的电量值,如果值为-1,表示没有电量信息。 | 1723| leftEarBatteryLevel | number | 是 | 否 | 表示左侧耳机的电量值,如果值为-1,表示没有电量信息。 | 1724| leftEarChargeState | [DeviceChargeState](#devicechargestate12) | 是 | 否 | 表示左侧耳机的充电状态。 | 1725| rightEarBatteryLevel | number | 是 | 否 | 表示右侧耳机的电量值,如果值为-1,表示没有电量信息。 | 1726| rightEarChargeState | [DeviceChargeState](#devicechargestate12) | 是 | 否 | 表示右侧耳机的充电状态。 | 1727| boxBatteryLevel | number | 是 | 否 | 表示耳机仓的电量值,如果值为-1,表示没有电量信息。 | 1728| boxChargeState | [DeviceChargeState](#devicechargestate12) | 是 | 否 | 表示耳机仓的充电状态。 | 1729 1730 1731## BluetoothTransport 1732 1733枚举,表示设备类型。例如传统蓝牙设备或低功耗蓝牙设备,支持双模默认使用TRANSPORT_BR_EDR。 1734 1735**系统能力**:SystemCapability.Communication.Bluetooth.Core 1736 1737| 名称 | 值 | 说明 | 1738| -------------------------------- | ------ | --------------- | 1739| TRANSPORT_BR_EDR | 0 | 表示传统蓝牙(BR/EDR)设备。 | 1740| TRANSPORT_LE | 1 | 表示低功耗蓝牙(BLE)设备。 | 1741 1742 1743## ScanMode 1744 1745枚举,扫描模式。 1746 1747**系统能力**:SystemCapability.Communication.Bluetooth.Core 1748 1749| 名称 | 值 | 说明 | 1750| ---------------------------------------- | ---- | --------------- | 1751| SCAN_MODE_NONE | 0 | 没有扫描模式。 | 1752| SCAN_MODE_CONNECTABLE | 1 | 可连接扫描模式。 | 1753| SCAN_MODE_GENERAL_DISCOVERABLE | 2 | general发现模式。 | 1754| SCAN_MODE_LIMITED_DISCOVERABLE | 3 | limited发现模式。 | 1755| SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE | 4 | 可连接general发现模式。 | 1756| SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE | 5 | 可连接limited发现模式。 | 1757 1758 1759## BondState 1760 1761枚举,配对状态。 1762 1763**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。 1764 1765**系统能力**:SystemCapability.Communication.Bluetooth.Core 1766 1767| 名称 | 值 | 说明 | 1768| ------------------ | ---- | ------ | 1769| BOND_STATE_INVALID | 0 | 无效的配对。 | 1770| BOND_STATE_BONDING | 1 | 正在配对。 | 1771| BOND_STATE_BONDED | 2 | 已配对。 | 1772 1773 1774## UnbondCause<sup>12+</sup> 1775 1776枚举,配对失败原因。 1777 1778**系统能力**:SystemCapability.Communication.Bluetooth.Core 1779 1780| 名称 | 值 | 说明 | 1781| ------------------ | ---- | ------ | 1782| USER_REMOVED | 0 | 用户主动移除设备。| 1783| REMOTE_DEVICE_DOWN | 1 | 远端设备关闭。| 1784| AUTH_FAILURE | 2 | PIN码错误。| 1785| AUTH_REJECTED | 3 | 远端设备鉴权拒绝。 | 1786| INTERNAL_ERROR | 4 | 内部错误。 | 1787 1788 1789## DeviceChargeState<sup>12+</sup> 1790 1791枚举,表示充电状态。 1792 1793**系统能力**:SystemCapability.Communication.Bluetooth.Core 1794 1795| 名称 | 值 | 说明 | 1796| ------------------ | ---- | ------ | 1797| DEVICE_NORMAL_CHARGE_NOT_CHARGED | 0 | 未充电,不支持超级充电。| 1798| DEVICE_NORMAL_CHARGE_IN_CHARGING | 1 | 正在充电,不支持超级充电。| 1799| DEVICE_SUPER_CHARGE_NOT_CHARGED | 2 | 未充电,支持超级充电。| 1800| DEVICE_SUPER_CHARGE_IN_CHARGING | 3 | 正在充电,支持超级充电。| 1801