• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.bluetooth.access (蓝牙access模块)
2
3<!--Kit: Connectivity Kit-->
4<!--Subsystem: Communication-->
5<!--Owner: @enjoy_sunshine-->
6<!--Designer: @chengguohong; @tangjia15-->
7<!--Tester: @wangfeng517-->
8<!--Adviser: @zhang_yixin13-->
9
10本模块提供了打开和关闭蓝牙、获取蓝牙开关状态以及其他相关方法。
11
12> **说明:**
13>
14> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
15
16## 导入模块
17
18```js
19import { access } from '@kit.ConnectivityKit';
20```
21
22## access.enableBluetooth
23
24enableBluetooth(): void
25
26开启蓝牙。
27
28- 调用该接口时,系统弹出开启蓝牙的对话框,由用户确认是否需要开启蓝牙。如果应用想要感知用户操作对话框的行为,建议使用[access.enableBluetoothAsync](#accessenablebluetoothasync20)。
29- 蓝牙开关状态结果可通过[access.on('stateChange')](#accessonstatechange)的回调函数获取到。
30- 建议蓝牙开关状态是[STATE_OFF](#bluetoothstate)时,才调用该接口开启蓝牙(可使用[access.getState](#accessgetstate)判断当前蓝牙开关状态)。
31
32**需要权限**:ohos.permission.ACCESS_BLUETOOTH
33
34**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
35
36**系统能力**:SystemCapability.Communication.Bluetooth.Core
37
38**错误码**:
39
40以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。
41
42| 错误码ID | 错误信息            |
43| -------- | ------------------ |
44|201 | Permission denied.                 |
45|801 | Capability not supported.          |
46|2900001   | Service stopped.   |
47|2900099   | Operation failed.  |
48
49**示例:**
50
51```js
52import { BusinessError } from '@kit.BasicServicesKit';
53
54try {
55    access.enableBluetooth();
56} catch (err) {
57    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
58}
59```
60
61## access.enableBluetoothAsync<sup>20+</sup>
62
63enableBluetoothAsync(): Promise&lt;void&gt;
64
65开启蓝牙。使用Promise异步回调。
66- 调用该接口时,系统弹出开启蓝牙的对话框,由用户确认是否需要开启蓝牙。应用可以感知用户操作对话框的行为。
67- 蓝牙开关状态结果可通过[access.on('stateChange')](#accessonstatechange)的回调函数获取到。
68- 建议蓝牙开关状态是[STATE_OFF](#bluetoothstate)时,才调用该接口开启蓝牙(可使用[access.getState](#accessgetstate)判断当前蓝牙开关状态)。
69
70**需要权限**:ohos.permission.ACCESS_BLUETOOTH
71
72**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。
73
74**系统能力**:SystemCapability.Communication.Bluetooth.Core
75
76**返回值:**
77
78| 类型                | 说明                                   |
79| ------------------- | -------------------------------------- |
80| Promise&lt;void&gt; | Promise对象,无返回结果。 |
81
82**错误码**:
83
84以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。
85
86| 错误码ID | 错误信息                   |
87| -------- | -------------------------- |
88| 201      | Permission denied.         |
89| 801      | Capability not supported.  |
90| 2900001  | Service stopped.           |
91| 2900013  | The user does not respond. |
92| 2900014  | User refuse the action.    |
93| 2900099  | Operation failed.          |
94
95**示例:**
96
97```js
98import { BusinessError } from '@kit.BasicServicesKit';
99
100try {
101    access.enableBluetoothAsync().then(() => {
102        console.info('enableBluetoothAsync');
103    }, (error: BusinessError) => {
104        console.error('enableBluetoothAsync: errCode:' + error.code + ',errMessage' + error.message);
105    })
106} catch (err) {
107    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
108}
109```
110
111## access.disableBluetooth
112
113disableBluetooth(): void
114
115关闭蓝牙。
116- 调用该接口时,系统弹出关闭蓝牙的对话框,由用户确认是否需要关闭蓝牙。如果应用想要感知用户操作对话框的行为,建议使用[access.disableBluetoothAsync](#accessdisablebluetoothasync20)。
117- 蓝牙开关状态结果可通过[access.on('stateChange')](#accessonstatechange)的回调函数获取到。
118- 建议蓝牙开关状态是[STATE_ON](#bluetoothstate)时,才调用该接口关闭蓝牙(可使用[access.getState](#accessgetstate)判断当前蓝牙开关状态)。
119
120**需要权限**:ohos.permission.ACCESS_BLUETOOTH
121
122**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
123
124**系统能力**:SystemCapability.Communication.Bluetooth.Core
125
126**错误码**:
127
128以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。
129
130|错误码ID   | 错误信息           |
131| -------- | ------------------ |
132|201 | Permission denied.                 |
133|801 | Capability not supported.          |
134|2900001   | Service stopped.   |
135|2900099   | Operation failed.  |
136
137**示例:**
138
139```js
140import { BusinessError } from '@kit.BasicServicesKit';
141
142try {
143    access.disableBluetooth();
144} catch (err) {
145    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
146}
147```
148
149## access.disableBluetoothAsync<sup>20+</sup>
150
151disableBluetoothAsync(): Promise&lt;void&gt;
152
153关闭蓝牙。使用Promise异步回调。
154- 调用该接口时,系统弹出关闭蓝牙的对话框,由用户确认是否需要关闭蓝牙。应用可以感知用户操作对话框的行为。
155- 蓝牙开关状态结果可通过[access.on('stateChange')](#accessonstatechange)的回调函数获取到。
156- 建议蓝牙开关状态是[STATE_ON](#bluetoothstate)时,才调用该接口关闭蓝牙(可使用[access.getState](#accessgetstate)判断当前蓝牙开关状态)。
157
158**需要权限**:ohos.permission.ACCESS_BLUETOOTH
159
160**原子化服务API**:从API version 20开始,该接口支持在原子化服务中使用。
161
162**系统能力**:SystemCapability.Communication.Bluetooth.Core
163
164**返回值:**
165
166| 类型                | 说明                                   |
167| ------------------- | -------------------------------------- |
168| Promise&lt;void&gt; | Promise对象,无返回结果。 |
169
170**错误码**:
171
172以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。
173
174| 错误码ID | 错误信息                   |
175| -------- | -------------------------- |
176| 201      | Permission denied.         |
177| 801      | Capability not supported.  |
178| 2900001  | Service stopped.           |
179| 2900013  | The user does not respond. |
180| 2900014  | User refuse the action.    |
181| 2900099  | Operation failed.          |
182
183**示例:**
184
185```js
186import { BusinessError } from '@kit.BasicServicesKit';
187
188try {
189    access.disableBluetoothAsync().then(() => {
190        console.info('disableBluetoothAsync');
191    }, (error: BusinessError) => {
192        console.error('disableBluetoothAsync: errCode:' + error.code + ',errMessage' + error.message);
193    })
194} catch (err) {
195    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
196}
197```
198
199## access.getState
200
201getState(): BluetoothState
202
203获取蓝牙开关状态。
204
205**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
206
207**系统能力**:SystemCapability.Communication.Bluetooth.Core
208
209**返回值:**
210
211| 类型                              | 说明              |
212| --------------------------------- | ---------------- |
213| [BluetoothState](#bluetoothstate) | 表示蓝牙开关状态。 |
214
215**错误码**:
216
217以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。
218
219|错误码ID   | 错误信息           |
220| -------- | ------------------ |
221|801 | Capability not supported.          |
222|2900001   | Service stopped.   |
223|2900099   | Operation failed.  |
224
225**示例:**
226
227```js
228import { BusinessError } from '@kit.BasicServicesKit';
229
230try {
231    let state = access.getState();
232} catch (err) {
233    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
234}
235```
236
237## access.on('stateChange')<a name="stateChange"></a>
238
239on(type: 'stateChange', callback: Callback&lt;BluetoothState&gt;): void
240
241订阅本端蓝牙开关状态变化事件。使用Callback异步回调。从API18开始不再校验ohos.permission.ACCESS_BLUETOOTH权限。
242
243**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
244
245**系统能力**:SystemCapability.Communication.Bluetooth.Core
246
247**参数:**
248
249| 参数名   | 类型                                               | 必填  | 说明                                                       |
250| -------- | ------------------------------------------------- | ----- | ---------------------------------------------------------- |
251| type     | string                                            | 是    | 事件回调类型,支持的事件为'stateChange',表示蓝牙开关状态变化事件。<br>如:当调用[access.enableBluetooth](#accessenablebluetooth)或[access.disableBluetooth](#accessdisablebluetooth)时,可触发该事件。               |
252| callback | Callback&lt;[BluetoothState](#bluetoothstate)&gt; | 是    | 指定订阅的回调函数,会携带蓝牙开关状态。 |
253
254**错误码**:
255
256以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。
257
258|错误码ID   | 错误信息           |
259| -------- | ------------------ |
260|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.                 |
261|801 | Capability not supported.          |
262|2900099   | Operation failed.  |
263
264**示例:**
265
266```js
267import { BusinessError } from '@kit.BasicServicesKit';
268
269function onReceiveEvent(data: access.BluetoothState) {
270    console.info('bluetooth state = '+ JSON.stringify(data));
271}
272try {
273    access.on('stateChange', onReceiveEvent);
274} catch (err) {
275    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
276}
277```
278
279## access.off('stateChange')
280
281off(type: 'stateChange', callback?: Callback&lt;BluetoothState&gt;): void
282
283取消订阅本端蓝牙开关状态变化事件。从API18开始不再校验ohos.permission.ACCESS_BLUETOOTH权限。
284
285**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
286
287**系统能力**:SystemCapability.Communication.Bluetooth.Core
288
289**参数:**
290
291| 参数名      | 类型                                       | 必填   | 说明                                       |
292| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
293| type     | string                                   | 是    | 事件回调类型,支持的事件为'stateChange',表示蓝牙开关状态变化事件。           |
294| callback | Callback&lt;[BluetoothState](#bluetoothstate)&gt; | 否    | 指定取消订阅的回调函数通知。<br>若传参,则需与[access.on('stateChange')](#accessonstatechange)中的回调函数一致;若无传参,则取消订阅该type对应的所有回调函数通知。 |
295
296**错误码**:
297
298以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。
299
300| 错误码ID | 错误信息 |
301| -------- | ---------------------------- |
302|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.                 |
303|801 | Capability not supported.          |
304|2900099 | Operation failed.                        |
305
306**示例:**
307
308```js
309import { BusinessError } from '@kit.BasicServicesKit';
310
311function onReceiveEvent(data: access.BluetoothState) {
312    console.info('bluetooth state = '+ JSON.stringify(data));
313}
314try {
315    access.on('stateChange', onReceiveEvent);
316    access.off('stateChange', onReceiveEvent);
317} catch (err) {
318    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
319}
320```
321
322## access.addPersistentDeviceId<sup>16+</sup>
323
324addPersistentDeviceId(deviceId: string): Promise&lt;void&gt;
325
326持久化存储蓝牙设备的虚拟MAC地址。
327- 应用通过蓝牙相关接口,如扫描等途径获取到的设备地址(虚拟MAC地址)和实际的设备MAC地址不同。蓝牙子系统会保存一个虚拟MAC地址和实际设备MAC地址的映射关系。若应用想长期对该蓝牙设备进行操作使用,建议用此接口持久化存储该设备的虚拟MAC地址,后续可直接使用,该地址映射关系不会再改变。
328- 指定持久化存储的虚拟MAC地址需是有效的(可使用[access.isValidRandomDeviceId](#accessisvalidrandomdeviceid16)判断)。
329- 使用该接口时,开发者应确保该虚拟MAC地址对应的对端蓝牙设备实际地址是保持不变的,若对端设备实际地址发生变化,持久化存储的地址信息将失效,无法继续使用。
330- 可调用[access.deletePersistentDeviceId](#accessdeletepersistentdeviceid16)删除已持久化存储的虚拟MAC地址。
331
332**需要权限**:ohos.permission.ACCESS_BLUETOOTHohos.permission.PERSISTENT_BLUETOOTH_PEERS_MAC
333
334**原子化服务API**:从API version 16开始,该接口支持在原子化服务中使用。
335
336**系统能力**:SystemCapability.Communication.Bluetooth.Core
337
338**参数:**
339
340| 参数名      | 类型                                       | 必填   | 说明                                       |
341| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
342| deviceId     | string                                   | 是    | 对端设备的虚拟MAC地址,例如:"XX:XX:XX:XX:XX:XX"。<br>该地址一般来源于蓝牙扫描结果,如:可通过调用[startScan](js-apis-bluetooth-ble.md#startscan15)或[connection.startBluetoothDiscovery](js-apis-bluetooth-connection.md#connectionstartbluetoothdiscovery)扫描得到。  |
343
344**返回值:**
345
346| 类型                            | 说明         |
347| ----------------------------- | ---------- |
348| Promise&lt;void&gt; | Promise对象,无返回结果。 |
349
350**错误码**:
351
352以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。
353
354| 错误码ID | 错误信息 |
355| -------- | ---------------------------- |
356|201 | Permission denied.                 |
357|401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.                 |
358|801 | Capability not supported.          |
359|2900003 | Bluetooth disabled. |
360|2900010 | The number of supported device addresses has reached the upper limit. |
361|2900099 | Add persistent device address failed.                        |
362
363**示例:**
364
365```js
366import { BusinessError } from '@kit.BasicServicesKit';
367
368let deviceId = '11:22:33:44:55:66'  // 该地址可通过BLE扫描获取
369try {
370    access.addPersistentDeviceId(deviceId);
371} catch (err) {
372    console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
373}
374```
375
376## access.deletePersistentDeviceId<sup>16+</sup>
377
378deletePersistentDeviceId(deviceId: string): Promise&lt;void&gt;
379
380删除已持久化存储的蓝牙虚拟MAC地址。
381- 该虚拟MAC地址通过[access.addPersistentDeviceId](#accessaddpersistentdeviceid16)持久化存储。
382
383**需要权限**:ohos.permission.ACCESS_BLUETOOTHohos.permission.PERSISTENT_BLUETOOTH_PEERS_MAC
384
385**原子化服务API**:从API version 16开始,该接口支持在原子化服务中使用。
386
387**系统能力**:SystemCapability.Communication.Bluetooth.Core
388
389**参数:**
390
391| 参数名      | 类型                                       | 必填   | 说明                                       |
392| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
393| deviceId     | string                                   | 是    | 对端设备的虚拟MAC地址,例如:"XX:XX:XX:XX:XX:XX",<br>该地址一般来源于蓝牙扫描结果,如:通过调用[startScan](js-apis-bluetooth-ble.md#startscan15)或[connection.startBluetoothDiscovery](js-apis-bluetooth-connection.md#connectionstartbluetoothdiscovery)扫描得到。           |
394
395**返回值:**
396
397| 类型                            | 说明         |
398| ----------------------------- | ---------- |
399| Promise&lt;void&gt; | Promise对象,无返回结果。 |
400
401**错误码**:
402
403以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。
404
405| 错误码ID | 错误信息 |
406| -------- | ---------------------------- |
407|201 | Permission denied.                 |
408|401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.                 |
409|801 | Capability not supported.          |
410|2900003 | Bluetooth disabled. |
411|2900099 | delete persistent device address failed.                        |
412
413**示例:**
414
415```js
416import { BusinessError } from '@kit.BasicServicesKit';
417
418let deviceId = '11:22:33:44:55:66'  // 该地址可通过BLE扫描获取
419try {
420    access.deletePersistentDeviceId(deviceId);
421} catch (err) {
422    console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
423}
424```
425
426## access.getPersistentDeviceIds<sup>16+</sup>
427
428getPersistentDeviceIds(): string[];
429
430获取应用持久化存储过的蓝牙虚拟MAC地址。
431
432**需要权限**:ohos.permission.ACCESS_BLUETOOTHohos.permission.PERSISTENT_BLUETOOTH_PEERS_MAC
433
434**原子化服务API**:从API version 16开始,该接口支持在原子化服务中使用。
435
436**系统能力**:SystemCapability.Communication.Bluetooth.Core
437
438**返回值:**
439
440| 类型                              | 说明              |
441| --------------------------------- | ---------------- |
442| string[] | 持久化存储过的蓝牙虚拟MAC地址列表。 |
443
444**错误码**:
445
446以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。
447
448| 错误码ID | 错误信息 |
449| -------- | ---------------------------- |
450|201 | Permission denied.                 |
451|801 | Capability not supported.          |
452|2900003 | Bluetooth disabled. |
453|2900099 | Get persistent device address failed.                        |
454
455**示例:**
456
457```js
458import { BusinessError } from '@kit.BasicServicesKit';
459
460try {
461    let deviceIds = access.getPersistentDeviceIds();
462} catch (err) {
463    console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
464}
465```
466
467## access.isValidRandomDeviceId<sup>16+</sup>
468
469isValidRandomDeviceId(deviceId: string): boolean;
470
471判断对端蓝牙设备的虚拟MAC地址是否有效。
472- 有效的虚拟MAC地址一般来源于蓝牙扫描结果,如:通过调用[startScan](js-apis-bluetooth-ble.md#startscan15)或[connection.startBluetoothDiscovery](js-apis-bluetooth-connection.md#connectionstartbluetoothdiscovery)扫描得到。
473
474**需要权限**:ohos.permission.ACCESS_BLUETOOTH
475
476**原子化服务API**:从API version 16开始,该接口支持在原子化服务中使用。
477
478**系统能力**:SystemCapability.Communication.Bluetooth.Core
479
480**参数:**
481
482| 参数名      | 类型                                       | 必填   | 说明                                       |
483| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
484| deviceId     | string                                   | 是    | 对端设备的虚拟MAC地址,例如:"XX:XX:XX:XX:XX:XX"。           |
485
486**返回值:**
487
488| 类型                              | 说明              |
489| --------------------------------- | ---------------- |
490| boolean | 蓝牙设备的虚拟MAC地址是否是有效的。true表示有效地址,false表示无效地址。|
491
492**错误码**:
493
494以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)和[蓝牙服务子系统错误码](errorcode-bluetoothManager.md)。
495
496| 错误码ID | 错误信息 |
497| -------- | ---------------------------- |
498|201 | Permission denied.                 |
499|401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.                 |
500|801 | Capability not supported.          |
501|2900003 | Bluetooth disabled. |
502|2900099 | Check persistent device address failed.                        |
503
504**示例:**
505
506```js
507import { BusinessError } from '@kit.BasicServicesKit';
508
509try {
510    let deviceId = '11:22:33:44:55:66'  // 该地址可通过BLE扫描获取
511    let isValid = access.isValidRandomDeviceId(deviceId);
512    console.info("isValid: " + isValid);
513} catch (err) {
514    console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
515}
516```
517
518## BluetoothState
519
520枚举,蓝牙开关状态。
521
522**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
523
524**系统能力**:SystemCapability.Communication.Bluetooth.Core
525
526| 名称                    | 值  | 说明                 |
527| --------------------- | ---- | ------------------ |
528| STATE_OFF             | 0    | 表示蓝牙已关闭。          |
529| STATE_TURNING_ON      | 1    | 表示蓝牙正在打开。          |
530| STATE_ON              | 2    | 表示蓝牙已打开。           |
531| STATE_TURNING_OFF     | 3    | 表示蓝牙正在关闭。          |
532| STATE_BLE_TURNING_ON  | 4    | 表示蓝牙正在打开LE-only模式。 |
533| STATE_BLE_ON          | 5    | 表示蓝牙正处于LE-only模式。  |
534| STATE_BLE_TURNING_OFF | 6    | 表示蓝牙正在关闭LE-only模式。 |
535