harmony 鸿蒙@ohos.bluetooth.connection (Bluetooth Connection Module)

  • 2025-06-12
  • 浏览 (8)

@ohos.bluetooth.connection (Bluetooth Connection Module)

The connection module provides APIs for operating and managing Bluetooth.

NOTE

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.

Modules to Import

import { connection } from '@kit.ConnectivityKit';

ProfileConnectionState

type ProfileConnectionState = constant.ProfileConnectionState

Defines the profile connection status of the Bluetooth device.

System capability: SystemCapability.Communication.Bluetooth.Core

Type Description
constant.ProfileConnectionState Profile connection status of the Bluetooth device.

ProfileId

type ProfileId = constant.ProfileId

Enumerates profiles of the Bluetooth device.

System capability: SystemCapability.Communication.Bluetooth.Core

Type Description
constant.ProfileId Profile of the Bluetooth device.

ProfileUuids12+

type ProfileUuids = constant.ProfileUuids

Defines the UUID of a profile.

System capability: SystemCapability.Communication.Bluetooth.Core

Type Description
constant.ProfileUuids UUID of the profile.

MajorClass

type MajorClass = constant.MajorClass

Main class of the Bluetooth device.

System capability: SystemCapability.Communication.Bluetooth.Core

Type Description
constant.MajorClass Main class of the Bluetooth device.

MajorMinorClass

type MajorMinorClass = constant.MajorMinorClass

Major and minor classes of the Bluetooth device.

System capability: SystemCapability.Communication.Bluetooth.Core

Type Description
constant.MajorMinorClass Major and minor classes of the Bluetooth device.

connection.pairDevice

pairDevice(deviceId: string, callback: AsyncCallback<void>): void

Pairs a Bluetooth device. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes Address of the device to pair, for example, XX:XX:XX:XX:XX:XX.
callback AsyncCallback<void> Yes Callback used to return the result. If the pairing is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
// callback
try {
    connection.pairDevice('11:22:33:44:55:66', (err: BusinessError) => {
        console.info('pairDevice, device name err:' + JSON.stringify(err));
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.pairDevice

pairDevice(deviceId: string): Promise<void>

Pairs a Bluetooth device. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes Address of the device to pair, for example, XX:XX:XX:XX:XX:XX.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
// promise
try {
    connection.pairDevice('11:22:33:44:55:66').then(() => {
        console.info('pairDevice');
    }, (error: BusinessError) => {
        console.info('pairDevice: errCode:' + error.code + ',errMessage' + error.message);
    })

} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getRemoteDeviceName

getRemoteDeviceName(deviceId: string): string

Obtains the name of a remote Bluetooth device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes Address of the peer device, for example, XX:XX:XX:XX:XX:XX.

Return value

Type Description
string Device name (a string) obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let remoteDeviceName: string = connection.getRemoteDeviceName('XX:XX:XX:XX:XX:XX');
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getRemoteDeviceName16+

getRemoteDeviceName(deviceId: string, alias?: boolean): string

Obtains the name of the peer device. The alias parameter is optional. - If the alias parameter is specified, the application determines whether to obtain the alias of the peer device. - If the alias parameter is not specified, the alias of the peer device is returned by default.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 16.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes Address of the peer device, for example, XX:XX:XX:XX:XX:XX.
alias boolean No Whether to obtain the alias of the peer device. The value true means to obtain the alias, and the value false means the opposite.

Return value

Type Description
string Device name (a string) obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Failed to obtain the name or alias of the peer Bluetooth device.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let remoteDeviceName: string = connection.getRemoteDeviceName('XX:XX:XX:XX:XX:XX', true);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getRemoteDeviceClass

getRemoteDeviceClass(deviceId: string): DeviceClass

Obtains the class of a remote Bluetooth device. Since API version 18, the ohos.permission.ACCESS_BLUETOOTH permission is no longer verified.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes Address of the peer device, for example, XX:XX:XX:XX:XX:XX.

Return value

Type Description
DeviceClass Class of the peer device obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let remoteDeviceClass: connection.DeviceClass = connection.getRemoteDeviceClass('XX:XX:XX:XX:XX:XX');
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getRemoteProfileUuids12+

getRemoteProfileUuids(deviceId: string, callback: AsyncCallback<Array<ProfileUuids>>): void

Obtains the profile UUIDs of a remote Bluetooth device. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes Address of the device to pair, for example, XX:XX:XX:XX:XX:XX.
callback AsyncCallback<Array<ProfileUuids>> Yes Callback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    connection.getRemoteProfileUuids('XX:XX:XX:XX:XX:XX', (err: BusinessError, data: Array<connection.ProfileUuids>) => {
        console.info('getRemoteProfileUuids, err: ' + JSON.stringify(err) + ', data: ' + JSON.stringify(data));
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getRemoteProfileUuids12+

getRemoteProfileUuids(deviceId: string): Promise&lt;Array&lt;ProfileUuids&gt;&gt;

Obtains the profile UUIDs of a remote Bluetooth device. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes Address of the device to pair, for example, XX:XX:XX:XX:XX:XX.

Return value

Type Description
Promise&lt;Array&lt;ProfileUuids&gt;&gt; Promise used to return the result.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    connection.getRemoteProfileUuids('XX:XX:XX:XX:XX:XX').then(() => {
        console.info('getRemoteProfileUuids');
    }, (err: BusinessError) => {
        console.error('getRemoteProfileUuids: errCode' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getLocalName

getLocalName(): string

Obtains the name of the local Bluetooth device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

Type Description
string Name of the local Bluetooth device obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
801 Capability not supported.
2900001 Service stopped.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let localName: string = connection.getLocalName();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getPairedDevices

getPairedDevices(): Array&lt;string&gt;

Obtains the paired devices.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

Type Description
Array&lt;string&gt; Addresses of the paired Bluetooth devices.
- For security purposes, the device addresses obtained are random MAC addresses.
- The random MAC address remains unchanged after a device is paired successfully.
- The random address changes when the paired device is unpaired and scanned again or the Bluetooth service is turned off.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let devices: Array<string> = connection.getPairedDevices();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getPairState11+

getPairState(deviceId: string): BondState

Obtains the Bluetooth pairing state.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes Address of the peer device, for example, XX:XX:XX:XX:XX:XX.

Return value

Type Description
BondState Bluetooth pairing state obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let res: connection.BondState = connection.getPairState("XX:XX:XX:XX:XX:XX");
    console.info('getPairState: ' + res);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getProfileConnectionState

getProfileConnectionState(profileId?: ProfileId): ProfileConnectionState

Obtains the connection state of a Bluetooth profile. The ProfileId parameter is optional. - If ProfileId is specified, the connection state of the specified profile is returned. - If no ProfileId is specified, STATE_CONNECTED is returned by any connected profile. If no profile is connected, STATE_DISCONNECTED is returned.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
profileId ProfileId No ID of the target profile, for example, PROFILE_A2DP_SOURCE.

Return value

Type Description
ProfileConnectionState Profile connection state obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Incorrect parameter types.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900004 Profile not supported.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
import { constant } from '@kit.ConnectivityKit';
try {
    let result: connection.ProfileConnectionState = connection.getProfileConnectionState(constant.ProfileId.PROFILE_A2DP_SOURCE);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.setDevicePairingConfirmation

setDevicePairingConfirmation(deviceId: string, accept: boolean): void

Sets the device pairing confirmation.

Required permissions: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH (available only for system applications)

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes Address of the peer device, for example, XX:XX:XX:XX:XX:XX.
accept boolean Yes Whether to accept the pairing request. The value true means to accept the pairing request, and the value false means the opposite.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
// Subscribe to the pinRequired event and configure the pairing confirmation after receiving a pairing request from the peer device.
function onReceivePinRequiredEvent(data: connection.PinRequiredParam) { // data is the input parameter for the pairing request.
    console.info('pin required  = '+ JSON.stringify(data));
    connection.setDevicePairingConfirmation(data.deviceId, true);
}
try {
    connection.on('pinRequired', onReceivePinRequiredEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.setDevicePinCode

setDevicePinCode(deviceId: string, code: string, callback: AsyncCallback&lt;void&gt;): void

Sets the PIN for the device when PinType is PIN_TYPE_ENTER_PIN_CODE or PIN_TYPE_PIN_16_DIGITS. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes MAC address of the peer device, for example, XX:XX:XX:XX:XX:XX.
code string Yes PIN to set.
callback AsyncCallback&lt;void&gt; Yes Callback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
// callback
try {
    connection.setDevicePinCode('11:22:33:44:55:66', '12345', (err: BusinessError) => {
        console.info('setDevicePinCode,device name err:' + JSON.stringify(err));
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.setDevicePinCode

setDevicePinCode(deviceId: string, code: string): Promise&lt;void&gt;

Sets the PIN for the device when PinType is PIN_TYPE_ENTER_PIN_CODE or PIN_TYPE_PIN_16_DIGITS. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes MAC address of the peer device, for example, XX:XX:XX:XX:XX:XX.
code string Yes PIN to set.

Return value

Type Description
Promise&lt;void&gt; Promise used to return the result.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
// promise
try {
    connection.setDevicePinCode('11:22:33:44:55:66', '12345').then(() => {
        console.info('setDevicePinCode');
    }, (error: BusinessError) => {
        console.info('setDevicePinCode: errCode:' + error.code + ',errMessage' + error.message);
    })

} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.setLocalName(deprecated)

setLocalName(name: string): void

Sets the name of the local Bluetooth device.

NOTE
This API is supported since API version 10 and deprecated since API version 12. No substitute is provided.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
name string Yes Bluetooth device name to set. It cannot exceed 248 bytes.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    connection.setLocalName('device_name');
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.setBluetoothScanMode

setBluetoothScanMode(mode: ScanMode, duration: number): void

Sets the Bluetooth scan mode so that the device can be discovered by a peer device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
mode ScanMode Yes Bluetooth scan mode to set. If the scan times out (duration is not 0) when the scan mode is SCAN_MODE_GENERAL_DISCOVERABLE, the scan mode will be reset to SCAN_MODE_CONNECTABLE.
duration number Yes Duration (in seconds) in which the device can be discovered. The value 0 indicates unlimited time.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    // The device can be discovered and connected only when the discoverable and connectable mode is used.
    connection.setBluetoothScanMode(connection.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getBluetoothScanMode

getBluetoothScanMode(): ScanMode

Obtains the Bluetooth scan mode.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

Type Description
ScanMode Bluetooth scan mode obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let scanMode: connection.ScanMode = connection.getBluetoothScanMode();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.startBluetoothDiscovery

startBluetoothDiscovery(): void

Starts to discover Bluetooth devices.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
function onReceiveEvent(data: Array<string>) {
    console.info('data length' + data.length);
}
try {
    connection.on('bluetoothDeviceFind', onReceiveEvent);
    connection.startBluetoothDiscovery();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.stopBluetoothDiscovery

stopBluetoothDiscovery(): void

Stops discovering Bluetooth devices.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    connection.stopBluetoothDiscovery();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.isBluetoothDiscovering11+

isBluetoothDiscovering(): boolean

Checks whether Bluetooth discovery is enabled.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

Type Description
boolean Returns true if Bluetooth discovery is enabled; returns false otherwise.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let res: boolean = connection.isBluetoothDiscovering();
    console.info('isBluetoothDiscovering: ' + res);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.setRemoteDeviceName12+

setRemoteDeviceName(deviceId: string, name: string): Promise&lt;void&gt;

Sets the name of a remote Bluetooth device. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes MAC address of the peer device, for example, XX:XX:XX:XX:XX:XX.
name string Yes Name of the peer device to set. The name cannot exceed 64 bytes.

Return value

Type Description
Promise&lt;void&gt; Promise used to return the device name set. If the operation fails, an error code is returned.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
2900001 Service stopped.
2900003 Bluetooth disabled.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
// promise
try {
    connection.setRemoteDeviceName('11:22:33:44:55:66', 'RemoteDeviceName').then(() => {
        console.info('setRemoteDeviceName success');
    }, (error: BusinessError) => {
        console.error('setRemoteDeviceName: errCode:' + error.code + ',errMessage' + error.message);
    })

} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getRemoteDeviceBatteryInfo12+

getRemoteDeviceBatteryInfo(deviceId: string): Promise&lt;BatteryInfo&gt;

obtains the battery information of a remote Bluetooth device. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes MAC address of the peer device, for example, 11:22:33:AA:BB:FF.

Return value

Type Description
Promise&lt;BatteryInfo&gt; Promise used to return the battery information obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
2900001 Service stopped.
2900003 Bluetooth disabled.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
// promise
try {
    connection.getRemoteDeviceBatteryInfo('11:22:33:AA:BB:FF').then((data: connection.BatteryInfo) => {
        console.info('getRemoteDeviceBatteryInfo success, DeviceType:' + JSON.stringify(data));
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.on(‘batteryChange’)12+

on(type: ‘batteryChange’, callback: Callback&lt;BatteryInfo&gt;): void

Subscribes to the changes in the battery information of a remote Bluetooth device. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The value is ‘batteryChange’, which indicates the change in battery information of a remote Bluetooth device.
callback Callback&lt;BatteryInfo&gt; Yes Callback used to return the battery information.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
let onReceiveEvent: (data: connection.BatteryInfo) => void = (data: connection.BatteryInfo) => {
    console.info('BatteryInfo = '+ JSON.stringify(data));
}
try {
    connection.on('batteryChange', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.off(‘batteryChange’)12+

off(type: ‘batteryChange’, callback?: Callback&lt;BatteryInfo&gt;): void

Unsubscribes from the changes in the battery information of a remote Bluetooth device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The value is ‘batteryChange’, which indicates the change in battery information of a remote Bluetooth device.
callback Callback&lt;BatteryInfo&gt; No Callback to unregister.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
let onReceiveEvent: (data: connection.BatteryInfo) => void = (data: connection.BatteryInfo) => {
    console.info('BatteryInfo = '+ JSON.stringify(data));
}
try {
    connection.on('batteryChange', onReceiveEvent);
    connection.off('batteryChange', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.on(‘bluetoothDeviceFind’)

on(type: ‘bluetoothDeviceFind’, callback: Callback&lt;Array&lt;string&gt;&gt;): void

Subscribes to the Bluetooth device discovered. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The value is bluetoothDeviceFind, which indicates an event of discovering a Bluetooth device.
callback Callback&lt;Array&lt;string&gt;&gt; Yes Callback used to return the discovered devices. You need to implement this callback. For security purposes, the device addresses are random MAC addresses. The random MAC address remains unchanged after a device is paired successfully. It changes when the paired device is unpaired and scanned again or the Bluetooth service is turned off.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
function onReceiveEvent(data: Array<string>) { // data is an array of Bluetooth device addresses.
    console.info('bluetooth device find = '+ JSON.stringify(data));
}
try {
    connection.on('bluetoothDeviceFind', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.off(‘bluetoothDeviceFind’)

off(type: ‘bluetoothDeviceFind’, callback?: Callback&lt;Array&lt;string&gt;&gt;): void

Unsubscribes from the Bluetooth device discovered.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The value is bluetoothDeviceFind, which indicates an event of discovering a Bluetooth device.
callback Callback&lt;Array&lt;string&gt;&gt; No Callback to unregister. If this parameter is not set, this API unregisters all callbacks for the specified type.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
801 Capability not supported.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
function onReceiveEvent(data: Array<string>) {
    console.info('bluetooth device find = '+ JSON.stringify(data));
}
try {
    connection.on('bluetoothDeviceFind', onReceiveEvent);
    connection.off('bluetoothDeviceFind', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.on(‘bondStateChange’)

on(type: ‘bondStateChange’, callback: Callback&lt;BondStateParam&gt;): void

Subscribes to Bluetooth pairing state changes. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The value is bondStateChange, which indicates a Bluetooth pairing state change event.
callback Callback&lt;BondStateParam&gt; Yes Callback used to return the pairing state. You need to implement this callback.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
function onReceiveEvent(data: connection.BondStateParam) { // data, as the input parameter of the callback, indicates the pairing state.
    console.info('pair state = '+ JSON.stringify(data));
}
try {
    connection.on('bondStateChange', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.off(‘bondStateChange’)

off(type: ‘bondStateChange’, callback?: Callback&lt;BondStateParam&gt;): void

Unsubscribes from Bluetooth pairing state changes.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The value is bondStateChange, which indicates a Bluetooth pairing state change event.
callback Callback&lt;BondStateParam&gt; No Callback to unregister. If this parameter is not set, this API unregisters all callbacks for the specified type.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
function onReceiveEvent(data: connection.BondStateParam) {
    console.info('bond state = '+ JSON.stringify(data));
}
try {
    connection.on('bondStateChange', onReceiveEvent);
    connection.off('bondStateChange', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.on(‘pinRequired’)

on(type: ‘pinRequired’, callback: Callback&lt;PinRequiredParam&gt;): void

Subscribes to the pairing request events of the remote Bluetooth device. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The value pinRequired indicates a pairing request event.
callback Callback&lt;PinRequiredParam&gt; Yes Callback used to return the pairing request. You need to implement this callback.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
function onReceiveEvent(data: connection.PinRequiredParam) { // data is the pairing request parameter.
    console.info('pin required = '+ JSON.stringify(data));
}
try {
    connection.on('pinRequired', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.off(‘pinRequired’)

off(type: ‘pinRequired’, callback?: Callback&lt;PinRequiredParam&gt;): void

Unsubscribes from the pairing request events of the remote Bluetooth device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The value pinRequired indicates a pairing request event.
callback Callback&lt;PinRequiredParam&gt; No Callback to unregister. The input parameter is the pairing request parameter. If this parameter is not set, this API unregisters all callbacks for the specified type.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
function onReceiveEvent(data: connection.PinRequiredParam) {
    console.info('pin required = '+ JSON.stringify(data));
}
try {
    connection.on('pinRequired', onReceiveEvent);
    connection.off('pinRequired', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.on(‘discoveryResult’)18+

on(type: ‘discoveryResult’, callback: Callback&lt;Array&lt;DiscoveryResult&gt;&gt;): void

Subscribes to the Bluetooth device discovered. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The value is discoveryResult, which indicates information about the Bluetooth devices discovered.
callback Callback&lt;Array&lt;DiscoveryResult&gt;&gt; Yes Callback used to return the discovered devices. You need to implement this callback.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
let onReceiveEvent: (data: Array<connection.DiscoveryResult>) => void = (data: Array<connection.DiscoveryResult>) => { // data is an array of Bluetooth devices discovered.
    console.info('bluetooth device find = '+ JSON.stringify(data));
}
try {
    connection.on('discoveryResult', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.off(‘discoveryResult’)18+

off(type: ‘discoveryResult’, callback?: Callback&lt;Array&lt;DiscoveryResult&gt;&gt;): void

Unsubscribes from the Bluetooth device discovered.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
type string Yes Event type. The value is discoveryResult, which indicates information about the Bluetooth devices discovered.
callback Callback&lt;Array&lt;DiscoveryResult&gt;&gt; No Callback to unregister. If this parameter is not set, this API unregisters all callbacks for the specified type.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
201 Permission denied.
801 Capability not supported.
2900099 Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
let onReceiveEvent: (data: Array<connection.DiscoveryResult>) => void = (data: Array<connection.DiscoveryResult>) => { // data is an array of Bluetooth devices discovered.
    console.info('bluetooth device find = '+ JSON.stringify(data));
}
try {
    connection.on('discoveryResult', onReceiveEvent);
    connection.off('discoveryResult', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getLastConnectionTime15+

getLastConnectionTime(deviceId: string): Promise&lt;number&gt;

Obtains the timestamp of the most recent connection to the peer device. This API uses a promise to return the result.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes MAC address of the peer device, for example, XX:XX:XX:XX:XX:XX.

Return value

Type Description
Promise&lt;number&gt; Promise used to return the result, which is the timestamp of the most recent connection to the peer device.

Error codes

For details about the error codes, see Bluetooth Error Codes.

ID Error Message
401 Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { connection } from '@kit.ConnectivityKit';
// promise
try {
    connection.getLastConnectionTime('11:22:33:44:55:66').then((time: number) => {
        console.info('connectionTime: ${time}');
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.connectAllowedProfiles16+

connectAllowedProfiles(deviceId: string, callback: AsyncCallback&lt;void&gt;): void

Connects all profiles allowed for a peer device. This API uses an asynchronous callback to return the result.
Call pairDevice to initiate pairing first. This API can be called only once within 30 seconds after each pairing is initiated.
Recommended usage: Subscribe to UUID_VALUE common event callbacks so that the application can receive a callback upon successful pairing of a Bluetooth device. You are advised to call connectAllowedProfiles in this callback.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes Address of the peer device, for example, XX:XX:XX:XX:XX.
callback AsyncCallback&lt;void&gt; Yes Callback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes and Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { commonEventManager, AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
import { connection } from '@kit.ConnectivityKit';
// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber: commonEventManager.CommonEventSubscriber;
// Subscriber information.
let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  events: ["usual.event.bluetooth.remotedevice.UUID_VALUE"]
};
// Subscribe to common event callbacks.
function SubscribeCB(err: BusinessError, data: commonEventManager.CommonEventData) {
  if (err) {
    console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
  } else {
    console.info(`Succeeded in subscribing, data is ` + JSON.stringify(data));
    // Before calling connectAllowedProfiles, ensure that the application has received the UUID_VALUE common event.
    try {
        connection.connectAllowedProfiles('68:13:24:79:4C:8C', (err: BusinessError) => {
            if (err) {
                console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
                return;
            }
            console.info('connectAllowedProfiles, err: ' + JSON.stringify(err));
        });
    } catch (err) {
        console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
  }
}
// Callback for subscriber creation.
function createCB(err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) {
  if(!err) {
    console.info(`Succeeded in creating subscriber.`);
    subscriber = commonEventSubscriber;
    // Subscribe to common events.
    try {
      commonEventManager.subscribe(subscriber, SubscribeCB);
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
    }
  } else {
    console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
  }
}

// Create a subscriber and subscribe to the common event callbacks.
try {
  commonEventManager.createSubscriber(subscribeInfo, createCB);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
}

connection.connectAllowedProfiles16+

connectAllowedProfiles(deviceId: string): Promise&lt;void&gt;

Connects all profiles allowed for a peer device. This API uses a promise to return the result.
Call pairDevice to initiate pairing first. This API can be called only once within 30 seconds after each pairing is initiated.
Recommended usage: Subscribe to UUID_VALUE common event callbacks so that the application can receive a callback upon successful pairing of a Bluetooth device. You are advised to call connectAllowedProfiles in this callback.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

Name Type Mandatory Description
deviceId string Yes Address of the peer device, for example, XX:XX:XX:XX:XX.

Return value

Type Description
Promise&lt;void&gt; Promise used to return the result.

Error codes

For details about the error codes, see Universal Error Codes and Bluetooth Error Codes.

ID Error Message
201 Permission denied.
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801 Capability not supported.
2900001 Service stopped.
2900003 Bluetooth disabled.
2900099 Operation failed.

Example

import { commonEventManager, AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
import { connection } from '@kit.ConnectivityKit';
// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber: commonEventManager.CommonEventSubscriber;
// Subscriber information.
let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  events: ["usual.event.bluetooth.remotedevice.UUID_VALUE"]
};
// Subscribe to common event callbacks.
function SubscribeCB(err: BusinessError, data: commonEventManager.CommonEventData) {
  if (err) {
    console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
  } else {
    console.info(`Succeeded in subscribing, data is ` + JSON.stringify(data));
    // Before calling connectAllowedProfiles, ensure that the application has received the UUID_VALUE common event.
    try {
        connection.connectAllowedProfiles('68:13:24:79:4C:8C').then(() => {
            console.info('connectAllowedProfiles');
        }, (err: BusinessError) => {
            console.error('connectAllowedProfiles:errCode' + err.code + ', errMessage: ' + err.message);
        });
    } catch (err) {
        console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
  }
}
// Callback for subscriber creation.
function createCB(err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) {
  if(!err) {
    console.info(`Succeeded in creating subscriber.`);
    subscriber = commonEventSubscriber;
    // Subscribe to common events.
    try {
      commonEventManager.subscribe(subscriber, SubscribeCB);
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
    }
  } else {
    console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
  }
}

// Create a subscriber and subscribe to the common event callbacks.
try {
  commonEventManager.createSubscriber(subscribeInfo, createCB);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
}

BondStateParam

Represents the pairing state parameters.

System capability: SystemCapability.Communication.Bluetooth.Core

Name Type Readable Writable Description
deviceId string Yes No ID of the device to pair.
state BondState Yes No State of the device.
cause12+ UnbondCause Yes No Cause of the pairing failure.

PinRequiredParam

Represents the pairing request parameters.

System capability: SystemCapability.Communication.Bluetooth.Core

Name Type Readable Writable Description
deviceId string Yes No ID of the device to pair.
pinCode string Yes No Key for the device pairing.

DeviceClass

Represents the class of a Bluetooth device.

System capability: SystemCapability.Communication.Bluetooth.Core

Name Type Readable Writable Description
majorClass MajorClass Yes No Major class of the Bluetooth device.
majorMinorClass MajorMinorClass Yes No Major and minor classes of the Bluetooth device.
classOfDevice number Yes No Class of the device.

BatteryInfo12+

Represents the battery information.

System capability: SystemCapability.Communication.Bluetooth.Core

Name Type Readable Writable Description
batteryLevel number Yes No Battery level of the peer device. If the value is -1, there is no battery information.
leftEarBatteryLevel number Yes No Battery level of the left earphone. If the value is -1, there is no battery information.
leftEarChargeState DeviceChargeState Yes No Charging state of the left earphone.
rightEarBatteryLevel number Yes No Battery level of the right earphone. If the value is -1, there is no battery information.
rightEarChargeState DeviceChargeState Yes No Charging state of the right earphone.
boxBatteryLevel number Yes No Battery level of the earbud compartment. If the value is -1, there is no battery information.
boxChargeState DeviceChargeState Yes No Charging state of the earbud compartment.

BluetoothTransport

Enumerates the device types. The default device type is TRANSPORT_BR_EDR.

System capability: SystemCapability.Communication.Bluetooth.Core

Name Value Description
TRANSPORT_BR_EDR 0 Classic Bluetooth (BR/EDR) device.
TRANSPORT_LE 1 BLE device.

ScanMode

Enumerates the scan modes.

System capability: SystemCapability.Communication.Bluetooth.Core

Name Value Description
SCAN_MODE_NONE 0 No scan mode.
SCAN_MODE_CONNECTABLE 1 Connectable mode.
SCAN_MODE_GENERAL_DISCOVERABLE 2 General discoverable mode.
SCAN_MODE_LIMITED_DISCOVERABLE 3 Limited discoverable mode.
SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE 4 General connectable and discoverable mode.
SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE 5 Limited connectable and discoverable mode.

BondState

Enumerates the pairing states.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Name Value Description
BOND_STATE_INVALID 0 Invalid pairing.
BOND_STATE_BONDING 1 Pairing.
BOND_STATE_BONDED 2 Paired.

UnbondCause12+

Enumerates the possible causes of a pairing failure.

System capability: SystemCapability.Communication.Bluetooth.Core

Name Value Description
USER_REMOVED 0 The user proactively removes the device.
REMOTE_DEVICE_DOWN 1 The peer device is shut down.
AUTH_FAILURE 2 The PIN is incorrect.
AUTH_REJECTED 3 The peer device authentication is rejected.
INTERNAL_ERROR 4 Internal error.

DeviceChargeState12+

Enumerates the charging states.

System capability: SystemCapability.Communication.Bluetooth.Core

Name Value Description
DEVICE_NORMAL_CHARGE_NOT_CHARGED 0 The device is not charged and does not support supercharging.
DEVICE_NORMAL_CHARGE_IN_CHARGING 1 The device is being charged and does not support supercharging.
DEVICE_SUPER_CHARGE_NOT_CHARGED 2 The device is not charged and supports supercharging.
DEVICE_SUPER_CHARGE_IN_CHARGING 3 The device is being charged and supports supercharging.

DiscoveryResult18+

Represents information about the discovered device.

System capability: SystemCapability.Communication.Bluetooth.Core

Name Type Readable Writable Description
deviceId string Yes No ID of the discovered device.
rssi number Yes No RSSI of the discovered device.
deviceName string Yes No Name of the discovered device.
deviceClass DeviceClass Yes No Bluetooth class of the discovered device.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Connectivity Kit (Short-Range Communication Service)

harmony 鸿蒙Bluetooth

harmony 鸿蒙Wifi

harmony 鸿蒙Bluetooth Error Codes

harmony 鸿蒙NFC Error Codes

harmony 鸿蒙SecureElement Error Codes

harmony 鸿蒙Wi-Fi Error Codes

harmony 鸿蒙@ohos.bluetooth.a2dp (Bluetooth A2DP Module) (System API)

harmony 鸿蒙@ohos.bluetooth.a2dp (Bluetooth A2DP Module)

harmony 鸿蒙@ohos.bluetooth.access (Bluetooth Access Module) (System API)

0  赞