• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.bluetooth.access (Bluetooth Access Module)
2
3The **access** module provides APIs for enabling and disabling Bluetooth and obtaining the Bluetooth status.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8
9
10## Modules to Import
11
12```js
13import { access } from '@kit.ConnectivityKit';
14```
15
16
17## access.enableBluetooth
18
19enableBluetooth(): void
20
21Enables Bluetooth.
22
23**Required permissions**: ohos.permission.ACCESS_BLUETOOTH
24
25**Atomic service API**: This API can be used in atomic services since API version 12.
26
27**System capability**: SystemCapability.Communication.Bluetooth.Core
28
29**Error codes**
30
31For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md).
32
33| ID| Error Message           |
34| -------- | ------------------ |
35|201 | Permission denied.                 |
36|801 | Capability not supported.          |
37|2900001   | Service stopped.   |
38|2900099   | Operation failed.  |
39
40**Example**
41
42```js
43import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
44try {
45    access.enableBluetooth();
46} catch (err) {
47    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
48}
49```
50
51
52## access.disableBluetooth
53
54disableBluetooth(): void
55
56Disables Bluetooth.
57
58**Required permissions**: ohos.permission.ACCESS_BLUETOOTH
59
60**Atomic service API**: This API can be used in atomic services since API version 12.
61
62**System capability**: SystemCapability.Communication.Bluetooth.Core
63
64**Error codes**
65
66For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md).
67
68|ID  | Error Message          |
69| -------- | ------------------ |
70|201 | Permission denied.                 |
71|801 | Capability not supported.          |
72|2900001   | Service stopped.   |
73|2900099   | Operation failed.  |
74
75**Example**
76
77```js
78import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
79try {
80    access.disableBluetooth();
81} catch (err) {
82    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
83}
84```
85
86
87## access.getState
88
89getState(): BluetoothState
90
91Obtains the Bluetooth state.
92
93**Atomic service API**: This API can be used in atomic services since API version 11.
94
95**System capability**: SystemCapability.Communication.Bluetooth.Core
96
97**Return value**
98
99| Type                             | Description             |
100| --------------------------------- | ---------------- |
101| [BluetoothState](#bluetoothstate) | Bluetooth state obtained.|
102
103**Error codes**
104
105For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md).
106
107|ID  | Error Message          |
108| -------- | ------------------ |
109|801 | Capability not supported.          |
110|2900001   | Service stopped.   |
111|2900099   | Operation failed.  |
112
113**Example**
114
115```js
116import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
117try {
118    let state = access.getState();
119} catch (err) {
120    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
121}
122```
123
124## access.on('stateChange')<a name="stateChange"></a>
125
126on(type: 'stateChange', callback: Callback&lt;BluetoothState&gt;): void
127
128Subscribes to Bluetooth state changes. This API uses an asynchronous callback to return the result. Since API version 16, the **ohos.permission.ACCESS_BLUETOOTH** permission is no longer verified.
129
130**Atomic service API**: This API can be used in atomic services since API version 12.
131
132**System capability**: SystemCapability.Communication.Bluetooth.Core
133
134**Parameters**
135
136| Name  | Type                                              | Mandatory | Description                                                      |
137| -------- | ------------------------------------------------- | ----- | ---------------------------------------------------------- |
138| type     | string                                            | Yes   | Event type. The value is **stateChange**, which indicates Bluetooth state changes.              |
139| callback | Callback&lt;[BluetoothState](#bluetoothstate)&gt; | Yes   | Callback used to return the Bluetooth state. You need to implement this callback.|
140
141**Error codes**
142
143For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md).
144
145|ID  | Error Message          |
146| -------- | ------------------ |
147|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.                 |
148|801 | Capability not supported.          |
149|2900099   | Operation failed.  |
150
151**Example**
152
153```js
154import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
155function onReceiveEvent(data: access.BluetoothState) {
156    console.info('bluetooth state = '+ JSON.stringify(data));
157}
158try {
159    access.on('stateChange', onReceiveEvent);
160} catch (err) {
161    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
162}
163```
164
165
166## access.off('stateChange')
167
168off(type: 'stateChange', callback?: Callback&lt;BluetoothState&gt;): void
169
170Unsubscribes from Bluetooth state changes.
171
172**Required permissions**: ohos.permission.ACCESS_BLUETOOTH
173
174**Atomic service API**: This API can be used in atomic services since API version 12.
175
176**System capability**: SystemCapability.Communication.Bluetooth.Core
177
178**Parameters**
179
180| Name     | Type                                      | Mandatory  | Description                                      |
181| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
182| type     | string                                   | Yes   | Event type. The value is **stateChange**, which indicates Bluetooth state changes.          |
183| callback | Callback&lt;[BluetoothState](#bluetoothstate)&gt; | No   | Callback to unregister. If this parameter is not set, this API unregisters all callbacks for Bluetooth state changes.|
184
185**Error codes**
186
187For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md).
188
189| ID| Error Message|
190| -------- | ---------------------------- |
191|201 | Permission denied.                 |
192|401 | Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.                 |
193|801 | Capability not supported.          |
194|2900099 | Operation failed.                        |
195
196**Example**
197
198```js
199import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
200function onReceiveEvent(data: access.BluetoothState) {
201    console.info('bluetooth state = '+ JSON.stringify(data));
202}
203try {
204    access.on('stateChange', onReceiveEvent);
205    access.off('stateChange', onReceiveEvent);
206} catch (err) {
207    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
208}
209```
210
211## access.addPersistentDeviceId<sup>16+</sup>
212
213addPersistentDeviceId(deviceId: string): Promise&lt;void&gt;
214
215The device address obtained by the application through Bluetooth scanning is a random virtual address. If the application needs to use this random virtual address for an extended period, it needs to call this API to persistently store the address.
216
217When using this API, ensure that the real address of the peer device corresponding to the virtual random address remains unchanged. If the real address of the peer device changes, the persistently stored virtual address will become invalid and unusable.
218
219**Required permissions**: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.PERSISTENT_BLUETOOTH_PEERS_MAC
220
221**Atomic service API**: This API can be used in atomic services since API version 16.
222
223**System capability**: SystemCapability.Communication.Bluetooth.Core
224
225**Parameters**
226
227| Name     | Type                                      | Mandatory  | Description                                      |
228| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
229| deviceId     | string                                   | Yes   | Virtual address of the peer device, for example, XX:XX:XX:XX:XX:XX. The address is generally obtained from Bluetooth scanning. |
230
231**Error codes**
232
233For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md).
234
235| ID| Error Message|
236| -------- | ---------------------------- |
237|201 | Permission denied.                 |
238|401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.                 |
239|801 | Capability not supported.          |
240|2900003 | Bluetooth disabled. |
241|2900010 | The number of supported device addresses has reached the upper limit. |
242|2900099 | Add persistent device address failed.                        |
243
244**Example**
245
246```js
247import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
248import { access } from '@kit.ConnectivityKit';
249
250let deviceId = '11:22:33:44:55:66' // The address can be obtained through BLE scanning.
251try {
252    access.addPersistentDeviceId(deviceId);
253} catch (err) {
254    console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
255}
256```
257
258## access.deletePersistentDeviceId<sup>16+</sup>
259
260deletePersistentDeviceId(deviceId: string): Promise&lt;void&gt;
261
262Deletes a persistently stored virtual address.
263
264
265**Required permissions**: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.PERSISTENT_BLUETOOTH_PEERS_MAC
266
267**Atomic service API**: This API can be used in atomic services since API version 16.
268
269**System capability**: SystemCapability.Communication.Bluetooth.Core
270
271**Parameters**
272
273| Name     | Type                                      | Mandatory  | Description                                      |
274| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
275| deviceId     | string                                   | Yes   | Virtual address of the peer device, for example, XX:XX:XX:XX:XX:XX. The address is generally obtained from Bluetooth scanning.          |
276
277**Error codes**
278
279For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md).
280
281| ID| Error Message|
282| -------- | ---------------------------- |
283|201 | Permission denied.                 |
284|401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.                 |
285|801 | Capability not supported.          |
286|2900003 | Bluetooth disabled. |
287|2900099 | delete persistent device address failed.                        |
288
289**Example**
290
291```js
292import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
293import { access } from '@kit.ConnectivityKit';
294
295let deviceId = '11:22:33:44:55:66' // The address can be obtained through BLE scanning.
296try {
297    access.deletePersistentDeviceId(deviceId);
298} catch (err) {
299    console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
300}
301```
302
303## access.getPersistentDeviceIds<sup>16+</sup>
304
305getPersistentDeviceIds(): string[];
306
307Obtains persistently stored virtual addresses.
308
309
310**Required permissions**: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.PERSISTENT_BLUETOOTH_PEERS_MAC
311
312**Atomic service API**: This API can be used in atomic services since API version 16.
313
314**System capability**: SystemCapability.Communication.Bluetooth.Core
315
316**Return value**
317
318| Type                             | Description             |
319| --------------------------------- | ---------------- |
320| string[] | List of persistently stored virtual addresses.|
321
322**Error codes**
323
324For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md).
325
326| ID| Error Message|
327| -------- | ---------------------------- |
328|201 | Permission denied.                 |
329|801 | Capability not supported.          |
330|2900003 | Bluetooth disabled. |
331|2900099 | Get persistent device address failed.                        |
332
333**Example**
334
335```js
336import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
337import { access } from '@kit.ConnectivityKit';
338
339try {
340    let deviceIds = access.getPersistentDeviceIds();
341    console.info("deviceIds: " + deviceIds);
342} catch (err) {
343    console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
344}
345```
346
347## access.isValidRandomDeviceId<sup>16+</sup>
348
349isValidRandomDeviceId(deviceId: string): boolean;
350
351Checks whether the virtual address of the peer device is valid.
352
353
354**Required permissions**: ohos.permission.ACCESS_BLUETOOTH
355
356**Atomic service API**: This API can be used in atomic services since API version 16.
357
358**System capability**: SystemCapability.Communication.Bluetooth.Core
359
360**Parameters**
361
362| Name     | Type                                      | Mandatory  | Description                                      |
363| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
364| deviceId     | string                                   | Yes   | Virtual address of the peer device, for example, XX:XX:XX:XX:XX:XX. The address is generally obtained from Bluetooth scanning.          |
365
366**Return value**
367
368| Type                             | Description             |
369| --------------------------------- | ---------------- |
370| boolean | Whether the virtual address is valid.|
371
372**Error codes**
373
374For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bluetooth Error Codes](errorcode-bluetoothManager.md).
375
376| ID| Error Message|
377| -------- | ---------------------------- |
378|201 | Permission denied.                 |
379|401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.                 |
380|801 | Capability not supported.          |
381|2900003 | Bluetooth disabled. |
382|2900099 | Check persistent device address failed.                        |
383
384**Example**
385
386```js
387import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
388import { access } from '@kit.ConnectivityKit';
389
390try {
391    let deviceId = '11:22:33:44:55:66' // The address can be obtained through BLE scanning.
392    let isValid = access.isValidRandomDeviceId(deviceId);
393    console.info("isValid: " + isValid);
394} catch (err) {
395    console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
396}
397```
398
399## BluetoothState
400
401Enumerates the Bluetooth states.
402
403**Atomic service API**: This API can be used in atomic services since API version 11.
404
405**System capability**: SystemCapability.Communication.Bluetooth.Core
406
407| Name                   | Value | Description                |
408| --------------------- | ---- | ------------------ |
409| STATE_OFF             | 0    | Bluetooth is turned off.         |
410| STATE_TURNING_ON      | 1    | Bluetooth is being turned on.         |
411| STATE_ON              | 2    | Bluetooth is turned on.          |
412| STATE_TURNING_OFF     | 3    | Bluetooth is being turned off.         |
413| STATE_BLE_TURNING_ON  | 4    | The LE-only mode is being turned on for Bluetooth.|
414| STATE_BLE_ON          | 5    | Bluetooth is in LE-only mode. |
415| STATE_BLE_TURNING_OFF | 6    | The LE-only mode is being turned off for Bluetooth.|
416